Swift文法快速索引

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   使用   

在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

 

 

其他稍後補充

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.