swift 语法学习<一>

let 声明常量,var 声明变量:

var myVar = 42
let myConstant =30

明确声明类型:
var var1:Int;
拼接字符串:
let apples = 3; let fruit = "i have \(apples) apples"
统一[] 创建数组和字典;

      var array = ["heloo", "water"]
        array[1] = "friuit"
        var dict = ["key1":"value1",
            "key2":"value2"]
        dict["key1"] = "vlue3"

创建空数组和字典:

        let empArray = [String]()
        let empDict = [String:Float]()   

类型后面加一个问号来标记这个变量的值是可选的。
var optionStr:String? = "hello"

switch支持任意类型的数据以及各种比较操作——不仅仅是整数以及测试相等。
if ,for ,switch 后面跟{}

  switch vagetabl
        {
            case "calle":
             print("call")
            case "hello","hello2":
             println("ok sog")
            case let x where x.hasSuffix("pepper"):
            println("write songs")
            default:
            println("nothing")
        }

switch 不需要break语句;
for-in来遍历字典

let interestingNumbers = [ 
"Prime": [2, 3, 5, 7, 11, 13], 
"Fibonacci": [1, 1, 2, 3, 5, 8], 
"Square": [1, 4, 9, 16, 25],]
var largest = 0
for (kind, numbers) in interestingNumbers
 { 
   for number in numbers
  { 
     if number > largest
       {
          largest = number
       } 
  }
}
  for i in 0...5
   {
      //使用..<创建的范围不包含上界,如果想包含的话需要使用...
   }
    var i = 0
    while i<20
    {
    }

函数声明:
使用func来声明一个函数,使用名字和参数来调用函数。使用->来指定函数返回值。函数可以嵌套,可以当做返回值返回,也可以做为参数传入;

func returnFifteen() -> Int {
  var y = 10 
   func add() { 
      y += 5 
  } 
  add() 
  return y
 }
returnFifteen()
func makeIncrementer() -> (Int -> Int)
 {
   func addOne(number: Int) -> Int
     {
     return 1 + number 
     }
     return addOne
}
   var increment = makeIncrementer()

调用 increment(7)

func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool
 {
    for item in list
     {
        if condition(item)
        { 
            return true
       }
    }
     return false
   }
   func lessThanTen(number: Int) -> Bool 
   { 
     return number < 10
    }
   var numbers = [20, 19, 7, 12]
  hasAnyMatches(numbers,condition: lessThanTen)

入参声明: conditon:Int -> Bool

函数实际是特殊的闭包,可用{}来创建匿名闭包;

numbers.map({
   (number: Int) -> Int in
       let result = 3 * number
    return result
})

类,使用class声明;每个属性都需要赋值——无论是通过声明(就像numberOfSides)还是通过构造器(就像name)。

class NamedShape
 {
    var numberOfSides: Int = 0
    var name: String
    init(name: String) 
   { 
       self.name = name
   } 
    func simpleDescription() -> String 
   { 
      return "A shape with \(numberOfSides) sides." 
  }
}
class Square : NameShape
{
    var sideLength:Double = 0.0
    init(sideLength:Double,name:String)
    {
        self.sideLength = sideLength;
        super.init(name: name)
        numberOfSlides = 4;
    }
    
    var perimeter:Double
    {
        get
        {
            return 3.0 * sideLength;
        }
        
        set
        {
            sideLength = newValue / 3.0;
        }
      willSet
     {
      triangle.sideLength = newValue.sideLength
      }
      didSet
      {
      triangle.sideLength = newValue.sideLength
      }
    }
    
    func area() -> Double
    {
        return sideLength * sideLength;
    }
    override func simpleDescription() -> NSString {
        return "A square sides of length \(sideLength)."
    }
}

类中方法调用和普通函数区别:
函数的参数名只在函数内部使用,但是方法的参数名需要在调用的时候显式说明(除了第一个参数)。默认情况下,方法的参数名和它在方法内部的名字一样,不过你也可以定义第二个名字,这个名字被用在方法内部。

 class Counter 
  { 
      var count: Int = 0
     func incrementBy(amount: Int, numberOfTimes times: Int) 
{ 
     count += amount * times
  }
}
var counter = Counter()counter.incrementBy(2, numberOfTimes: 7)

类,枚举,结构体都可以实现协议;

使用protocol
来声明一个协议。
protocol ExampleProtocol {
 var simpleDescription: String { get } 
 mutating func adjust()
}
class SimpleClass: ExampleProtocol 
{
    var simpleDescription: String = "A very simple class." 
    var anotherProperty: Int = 69105
    func adjust()
   {
    simpleDescription += " Now 100% adjusted."    
   }
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescriptionstruct 
SimpleStructure: ExampleProtocol 
{
   var simpleDescription: String = "A simple structure" 
    mutating func adjust() 
  { 
     simpleDescription += " (adjusted)"  
  }
}
  var b = SimpleStructure()
  b.adjust()
  let bDescription = b.simpleDescription

注意声明SimpleStructure时候mutating关键字用来标记一个会修改结构体的方法。SimpleClass的声明不需要标记任何方法因为类中的方法经常会修改类。

使用extension来为现有的类型添加功能,比如新的方法和参数

extension Int:ExamplePro
{
    var simDes:String
    {
        return "the number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}
        println(7.simDes)

在尖括号里写一个名字来创建一个泛型函数或者类型

 func repeatIem(item:Item,numberOfTime:Int) ->[Item]
        {
            var result = [Item]()
            for _ in 0..

http://numbbbbb.gitbooks.io/-the-swift-programming-language-/content/chapter1/02_a_swift_tour.html
http://www.cocoachina.com/bbs/read.php?tid-206201.html
http://www.cocoachina.com/bbs/read.php?tid-205308.html
http://www.cocoachina.com/bbs/read.php?tid-204512.html
参考 http://www.cocoachina.com/bbs/thread.php?fid=57

你可能感兴趣的:(swift 语法学习<一>)