From: AceVest Date: Sun, 19 Jun 2016 14:15:52 +0000 (+0800) Subject: swift:functions & closures X-Git-Url: http://zhaoyanbai.com/repos/icons/debian/openlogo-25.jpg?a=commitdiff_plain;h=c4a3752c53eaf7cd9ca4bd17b518b4ed8f8e83c3;p=acecode.git swift:functions & closures --- diff --git a/learn/AcePlay/AcePlay.playground/Contents.swift b/learn/AcePlay/AcePlay.playground/Contents.swift deleted file mode 100644 index 2a17f16..0000000 --- a/learn/AcePlay/AcePlay.playground/Contents.swift +++ /dev/null @@ -1,8 +0,0 @@ -//: Playground - noun: a place where people can play - -import UIKit - - -SwiftBasics() - -SwiftFunctions() diff --git a/learn/AcePlay/AcePlay.playground/Pages/Basics.xcplaygroundpage/Contents.swift b/learn/AcePlay/AcePlay.playground/Pages/Basics.xcplaygroundpage/Contents.swift new file mode 100644 index 0000000..1ff1148 --- /dev/null +++ b/learn/AcePlay/AcePlay.playground/Pages/Basics.xcplaygroundpage/Contents.swift @@ -0,0 +1,104 @@ +//: Playground - noun: a place where people can play + +import UIKit + +let str = "Hello, playground.小狗:🐶 锤子:🔨" + +// Index +let strInx:String.Index = str.startIndex +strInx.successor() +print(strInx) + +for c in str.characters { + print(c, terminator: "") +} +print() + +// Print separator & terminator +var company:Array = [ "Apple", "Google", "Facebook", "Tencent" ] +print(company[0], company[1], company[2], company[3], separator: "#", terminator: " $$$$$\n") + +printLine("Count company Array 1") +for (i,v) in company.enumerate() { // enumerate 返回的是 index value 组成的元组 + print(i, v, separator: " - ", terminator: "\n") +} + +printLine("Count company Array 2") +company.insert("Alibaba", atIndex: company.count) +for i in 0..(0.. = [] +var SetB = Set() +var SetC: Set = ["ASM", "C", "C++", "go", "Swift"] +//var SetD: Set = ["mov", "pop", "push", "xchg"] // 可以通过数组类型推断出Set的类型 +SetB.insert("A") +SetB.insert("c") +SetB.insert("c") +SetB.count +//SetC.removeFirst() +SetC.remove("ASM") + +if let removedVal = SetC.remove("ASM") { + print("\(removedVal) I'm over it.") +} else { + print("I never much cared for that.") + SetC.insert("ASM") +} + +if SetC.contains("Swift") { + print("SetC Contains Swift") +} + +for v in SetC.sort() { + print(v) +} + +printLine("Dictionary") +//var DictA = Dictionary() +//var DictB = ["KA":"VA", "KB":"VB", "KC":"VC"] +//var DictC: [String:String] = [:] +var DictD = [Int:String]() + +DictD[1] = "V1" +DictD[4] = "V2" +DictD[99] = "V3" +DictD[36] = "F4" +if let oldValue = DictD.updateValue("V4", forKey: 36) { // means: if let oldValue = DictD[36] + print("The old value for Key:36 was \(oldValue)") +} + +print("DictD Item Count: ", DictD.count) + +for (k, v) in DictD { + print("Key:", k, " Value: ", v) +} + +for key in DictD.keys.sort() { + print(key) +} + +for value in DictD.values.sort() { + print(value) +} + +let keys = [Int](DictD.keys) +print(keys) diff --git a/learn/AcePlay/AcePlay.playground/Pages/Closure.xcplaygroundpage/Contents.swift b/learn/AcePlay/AcePlay.playground/Pages/Closure.xcplaygroundpage/Contents.swift new file mode 100644 index 0000000..66a43a8 --- /dev/null +++ b/learn/AcePlay/AcePlay.playground/Pages/Closure.xcplaygroundpage/Contents.swift @@ -0,0 +1,130 @@ +//: [Previous](@previous) + +import UIKit + + +// +//闭包采取如下三种形式之一: +// 1. 全局函数是一个有名字但不会捕获任何值的闭包 +// 2. 嵌套函数是一个有名字并可以捕获其封闭函数域内值的闭包 +// 3. 闭包表达式是一个利用轻量级语法所写的可以捕获其上下文中变量或常量值的匿名闭包 +// + +// +//Swift闭包语法特点: +// 1. 利用上下文推断参数和返回值类型 +// 2. 隐式返回单表达式闭包,即单表达式闭包可以省略return关键字 +// 3. 参数名称缩写 +// 4. 尾随(Trailing)闭包语法 +// + + +/* + The sort(_:) method accepts a closure that takes two arguments of the same type as the array’s contents, and returns a Bool value to say whether the first value should appear before or after the second value once the values are sorted. The sorting closure needs to return true if the first value should appear before the second value, and false otherwise. + + */ + +let company = ["Tencent", "Apple", "Facebook", "Google", "Twitter", "Amazon"] +var sortedCompany: [String] = [] + +printLine("Sort") +sortedCompany = company.sort() +print(sortedCompany) +sortedCompany = [] + +printLine("Sort With Function A") +func backwardsA(a: String, b: String) -> Bool { + return a > b +} +sortedCompany = company.sort(backwardsA) +print(sortedCompany) +sortedCompany = [] + +printLine("Sort With Backwards Closure A [Closure Expression Syntax]") +sortedCompany = company.sort({ (a: String, b: String) -> Bool in return a>b }) +print(sortedCompany) +sortedCompany = [] + +// 参数及返回类型自动推断 +printLine("Sort With Backwards Closure B [Inferring Type From Context]") +sortedCompany = company.sort({ a, b in return a > b }) +print(sortedCompany) +sortedCompany = [] + +// 隐式返回表达式闭包,省略return +printLine("Sort With Backwards Closure C [Implicit Returns from Single-Expression Closures]") +sortedCompany = company.sort({ a, b in a > b }) +print(sortedCompany) +sortedCompany = [] + +// 简写参数名 +printLine("Sort With Backwards Closure D [Shorthand Argument Names]") +sortedCompany = company.sort({ $0 > $1 }) +print(sortedCompany) +sortedCompany = [] + +/* + There’s actually an even shorter way to write the closure expression above. Swift’s String type defines its string-specific implementation of the greater-than operator (>) as a function that has two parameters of type String, and returns a value of type Bool. This exactly matches the function type needed by the sort(_:) method. Therefore, you can simply pass in the greater-than operator, and Swift will infer that you want to use its string-specific implementation: + */ +printLine("Sort With Backwards Closure E [Operator Functions]") +sortedCompany = company.sort(>) +print(sortedCompany) +sortedCompany = [] + +// Trailing Closure +printLine("Sort With Backwards Closure F [Trailing Closure]") +sortedCompany = company.sort() { a, b in a > b} // 如果闭包参数是这个函数的最后一个参数,是可以采用尾随闭包写法 +//sortedCompany = company.sort { a, b in a > b} // 如果闭包参数是这个函数的唯一一个参数,是可以不用写括号的 +print(sortedCompany) +sortedCompany = [] + + +let digitNames = [ + 0: "零", + 1: "壹", + 2: "贰", + 3: "叁", + 4: "肆", + 5: "伍", + 6: "陆", + 7: "柒", + 8: "捌", + 9: "玖", +] +let numbers = [9876543210, 1413, 110, 64] +// map函数可能不用指定参数类型,但要指定返回值类型 +let digitString = numbers.map() { + (digit) -> String in + var n = digit // 参数digit不能在函数体内被修改 + var s = "" + while n > 0 { + s = digitNames[n % 10]! + s + n /= 10 + } + return s +} + +print(digitString) + + +printLine("Captuare Value") + +// 捕获值 +func makeIncrementer(step:Int) -> () -> Int { + var total = 0 + func inc() -> Int { + total += step + return total + } + + return inc +} + +var closureFuncA = makeIncrementer(1) +print("ClosureFuncA:", closureFuncA()) +print("ClosureFuncA:", closureFuncA()) +var closureFuncB = closureFuncA +print("ClosureFunnB:", closureFuncB()) +var closureFuncC = makeIncrementer(1) +print("ClosureFuncC:", closureFuncC()) + diff --git a/learn/AcePlay/AcePlay.playground/Pages/Functions.xcplaygroundpage/Contents.swift b/learn/AcePlay/AcePlay.playground/Pages/Functions.xcplaygroundpage/Contents.swift new file mode 100644 index 0000000..ebcfc6e --- /dev/null +++ b/learn/AcePlay/AcePlay.playground/Pages/Functions.xcplaygroundpage/Contents.swift @@ -0,0 +1,56 @@ +//: [Previous](@previous) + +import Foundation + + +func Hello() -> Void { // func Hello() -> () { } + print("Hello Swift World") +} + + +printLine("Functions") + +Hello() + +printLine("Multiple Return Types") + +func minMax(data:Array) -> (min:Int, max:Int)? { + guard data.count > 0 else { + return nil + } + + var min = data[0] + var max = data[0] + + for i in 1.. data[i] ? data[i] : min + max = max < data[i] ? data[i] : max + } + + return (min, max) +} + +var Data: Array = [3, 8, 4, 1, 0, -2, 9, 6, 7] + +if let ret = minMax(Data) { + print("Min:", ret.min, " Max:", ret.max) +} + +// 外部参数包能相同, 但内部参数名不能相同 +func sameExternalParameterNames( ExName a: Int, ExName b: Int) -> Int { + return max(a, b) +} +print(sameExternalParameterNames(ExName: 10, ExName: 20)) + +// 引用传参 +func swapTwoInts(inout a: Int, inout _ b: Int) -> Void { + let t: Int = a + a = b + b = t +} + +var IntA = 10 +var IntB = 20 +swapTwoInts(&IntA, &IntB) + + diff --git a/learn/AcePlay/AcePlay.playground/Sources/Basic.swift b/learn/AcePlay/AcePlay.playground/Sources/Basic.swift deleted file mode 100644 index dddda1f..0000000 --- a/learn/AcePlay/AcePlay.playground/Sources/Basic.swift +++ /dev/null @@ -1,105 +0,0 @@ -import UIKit - -public -func SwiftBasics() -> Void { - let str = "Hello, playground.小狗:🐶 锤子:🔨" - - // Index - let strInx:String.Index = str.startIndex - strInx.successor() - print(strInx) - - for c in str.characters { - print(c, terminator: "") - } - print() - - // Print separator & terminator - var company:Array = [ "Apple", "Google", "Facebook", "Tencent" ] - print(company[0], company[1], company[2], company[3], separator: "#", terminator: " $$$$$\n") - - printLine("Count company Array 1") - for (i,v) in company.enumerate() { // enumerate 返回的是 index value 组成的元组 - print(i, v, separator: " - ", terminator: "\n") - } - - printLine("Count company Array 2") - company.insert("Alibaba", atIndex: company.count) - for i in 0..(0.. = [] - var SetB = Set() - var SetC: Set = ["ASM", "C", "C++", "go", "Swift"] - //var SetD: Set = ["mov", "pop", "push", "xchg"] // 可以通过数组类型推断出Set的类型 - SetB.insert("A") - SetB.insert("c") - SetB.insert("c") - SetB.count - //SetC.removeFirst() - SetC.remove("ASM") - - if let removedVal = SetC.remove("ASM") { - print("\(removedVal) I'm over it.") - } else { - print("I never much cared for that.") - SetC.insert("ASM") - } - - if SetC.contains("Swift") { - print("SetC Contains Swift") - } - - for v in SetC.sort() { - print(v) - } - - printLine("Dictionary") - //var DictA = Dictionary() - //var DictB = ["KA":"VA", "KB":"VB", "KC":"VC"] - //var DictC: [String:String] = [:] - var DictD = [Int:String]() - - DictD[1] = "V1" - DictD[4] = "V2" - DictD[99] = "V3" - DictD[36] = "F4" - if let oldValue = DictD.updateValue("V4", forKey: 36) { // means: if let oldValue = DictD[36] - print("The old value for Key:36 was \(oldValue)") - } - - print("DictD Item Count: ", DictD.count) - - for (k, v) in DictD { - print("Key:", k, " Value: ", v) - } - - for key in DictD.keys.sort() { - print(key) - } - - for value in DictD.values.sort() { - print(value) - } - - let keys = [Int](DictD.keys) - print(keys) -} diff --git a/learn/AcePlay/AcePlay.playground/Sources/Func.swift b/learn/AcePlay/AcePlay.playground/Sources/Func.swift deleted file mode 100644 index 344f9ab..0000000 --- a/learn/AcePlay/AcePlay.playground/Sources/Func.swift +++ /dev/null @@ -1,13 +0,0 @@ -//import Foundation -import UIKit - -func Hello() -> Void { - print("Hello Swift World") -} - - -public -func SwiftFunctions() -> Void { - printLine("Functions") - Hello() -} \ No newline at end of file diff --git a/learn/AcePlay/AcePlay.playground/contents.xcplayground b/learn/AcePlay/AcePlay.playground/contents.xcplayground index 5da2641..90f7190 100644 --- a/learn/AcePlay/AcePlay.playground/contents.xcplayground +++ b/learn/AcePlay/AcePlay.playground/contents.xcplayground @@ -1,4 +1,8 @@ - - + + + + + + \ No newline at end of file diff --git a/learn/AcePlay/AcePlay.playground/playground.xcworkspace/xcuserdata/Ace.xcuserdatad/UserInterfaceState.xcuserstate b/learn/AcePlay/AcePlay.playground/playground.xcworkspace/xcuserdata/Ace.xcuserdatad/UserInterfaceState.xcuserstate index 4665619..5f08ca2 100644 Binary files a/learn/AcePlay/AcePlay.playground/playground.xcworkspace/xcuserdata/Ace.xcuserdatad/UserInterfaceState.xcuserstate and b/learn/AcePlay/AcePlay.playground/playground.xcworkspace/xcuserdata/Ace.xcuserdatad/UserInterfaceState.xcuserstate differ