首页 > 代码库 > Swift语法快速索引

Swift语法快速索引

在WWDC的演示中就可以看出来Swift这个更接近于脚本的语言可以用更少的代码量完成和OC同样的功能。但是对于像我一样在战争中学习战争的同学们来说,天天抱着笨Swift Programming Language Reference之类的大部头看不实际。毕竟还是要养家糊口的。而且,那么1000+页内容讲的东西不是什么都要全部在平时工作中用到的。咱们就把平时用到的全部都放在一起,忘记了立马翻开看看,不知不觉的就学会了之后变成习惯。这样多省事。

变量

1 // Variable2 var int_variable = 1    // 类型推断3 var message : String4 var x = 0.0, y = 0.0, z = 0.0

 

常量

// Constantlet const_int = 1//const_int = 10  ERROR: can not assign to let value

 

字符串

// String// 1. 定义var empty_string = ""var another_empty_string = String()// 2. 拼接var hello_string = "hello"var world_string = " world"hello_string += world_string    // hello world let multiplier = 3//let multiplier_message = "\(mulitplier) times 2.5 is \(Double(multiplier) * 2.5)"// 3. 比较var hello_world_string = "hello world"hello_string == hello_world_string  // all are "hello world", result is trueif hello_string == hello_world_string {    println("These two are equal")}

 

Tuple

 

// Tuple// 1. Unnamed tuplelet http_not_found = (404, "Not Found")println("tuple item 1 \(http_not_found.0), tuple item 2 \(http_not_found.1)")// 2. Named tuplelet (statusCode, statusMessage) = (404, "Not Found")statusCode      // 404statusMessage   // "Not Found"let http_not_found2 = (statusCode:404, statusMessage:"Not Found")http_not_found2.statusCode      // 404http_not_found2.statusMessage   // "Not Found"// 3. return tuplefunc getHttpStatus() -> (statusCode : Int, statusMessage : String){    // request http    return (404, "Not Found")}

 

 

数组

 

// Array// 1. 定义//var empty_array = []  // 在swift里没事不要这样定义数组。这是NSArray类型的,一般是Array<T>类型的var empty_array : [Int]var empty_array2 = [Int]()var fire_works = [String]()var colors = ["red", "yellow"]var fires : [String] = ["small fire", "big fire"]; // Xcode6 beta3里数组的类型是放在方括号里的var red = colors[0]// 2. append & insertcolors.append("black")colors += "blue"colors += firescolors.insert("no color", atIndex: 0)// 3. updatecolors[2] = "light blue"//colors[5...9] = ["pink", "orange", "gray", "limon"]// 4. removecolors.removeAtIndex(5)//colors[0] = nil ERROR!// othercolors.isEmptycolors.count

 

 

字典

 

 

// Dictionary// 1. 定义var airports : Dictionary<String, String> = ["TYP":"Tokyo", "DUB":"Boublin"]var airports2 = ["TYP":"Tokyo", "DUB":"Boublin"]var empty_dic = Dictionary<String, String>()var empty_dic2 = [:]// 2. updateairports.updateValue("Dublin International", forKey: "DUB")airports["DUB"] = "Dublin International"// 3. insertairports["CHN"] = "China International"// 4. check existsif let airportName = airports["DUB"] {    println("The name of the airport is \(airportName).")}else{    println("That airport is not in the airports dictionary.")}// 5. iteratefor (airportCode, airportName) in airports{    println("\(airportCode):\(airportName)")}// 6. removeairports.removeValueForKey("TYP")airports["DUB"] = nil

 

 

枚举

 

// Enum// 1. defination & usageenum PowerStatus: Int{    case On = 1    case Off = 2}enum PowerStatus2: Int{    case On = 1, Off, Unknown}var status = PowerStatus.Onenum Barcode {    case UPCA(Int, Int, Int)    case QRCode(String)}var product_barcode = Barcode.UPCA(8, 8679_5449, 9)product_barcode = .QRCode("ABCDEFGHIJKLMN")switch product_barcode{case .UPCA(let numberSystem, let identifier, let check):    println("UPC-A with value of \(numberSystem), \(identifier), \(check)")case .QRCode(let productCode):    println("QR code with value of \(productCode)")}

 

 

方法

 

 

// Function// 1. 定义func yourFuncName(){}// 2. 返回值func yourFuncNameWithReturnType()->String{    return ""}// 3. 参数func funcWithParameter(parameter1:String, parameter2:String)->String{    return parameter1 + parameter2}funcWithParameter("1", "2")// 4. 外部参数名func funcWithExternalParameter(externalParameter p1:String) -> String{    return p1 + " " + p1}funcWithExternalParameter(externalParameter: "hello world")func joinString(string s1: String, toString s2: String, withJoiner joiner: String)    -> String {        return s1 + joiner + s2}joinString(string: "hello", toString: "world", withJoiner: "&")// 外部内部参数同名func containsCharacter(#string: String, #characterToFind: Character) -> Bool {    for character in string {        if character == characterToFind {            return true        }    }    return false}containsCharacter(string: "aardvark", characterToFind: "v")// 默认参数值func joinStringWithDefaultValue(string s1: String, toString s2: String, withJoiner joiner: String = " ")    -> String {        return s1 + joiner + s2}joinStringWithDefaultValue(string: "hello", toString: "world") //joiner的值默认为“ ”// inout参数func swapTwoInts(inout a: Int, inout b: Int) {    let temporaryA = a    a = b    b = temporaryA}var someInt = 3var anotherInt = 107swapTwoInts(&someInt, &anotherInt)println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")// prints "someInt is now 107, and anotherInt is now 3

 

 

 

 

// Class// 1. 定义class NamedShape {    var numberOfSides: Int = 0    var name: String        init(name: String) {        self.name = name    }        func simpleDescription() -> String {        return "A shape with \(numberOfSides) sides."    }}// 2. 继承 & 函数重载 & 属性getter setterclass Square: NamedShape {    var sideLength: Double        init(sideLength: Double, name: String) {        self.sideLength = sideLength        super.init(name: name)        numberOfSides = 4    }        func area() ->  Double {        return sideLength * sideLength    }        // 函数重载    override func simpleDescription() -> String {        return "A square with sides of length \(sideLength)."    }}class EquilateralTriangle: NamedShape {    var sideLength: Double = 0.0        init(sideLength: Double, name: String) {        self.sideLength = sideLength        super.init(name: name)        numberOfSides = 3    }        // 属性的getter setter    var perimeter: Double {        get {            return 3.0 * sideLength        }        set {            sideLength = newValue / 3.0        }    }    override func simpleDescription() -> String {        return "An equilateral triagle with sides of length \(sideLength)."    }}// 3. 使用var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")triangle.perimetertriangle.perimeter = 9.9triangle.sideLength

 

 

其他稍后补充