]> Zhao Yanbai Git Server - acecode.git/commitdiff
swift:functions & closures
authorAceVest <zhaoyanbai@126.com>
Sun, 19 Jun 2016 14:15:52 +0000 (22:15 +0800)
committerAceVest <zhaoyanbai@126.com>
Sun, 19 Jun 2016 14:15:52 +0000 (22:15 +0800)
learn/AcePlay/AcePlay.playground/Contents.swift [deleted file]
learn/AcePlay/AcePlay.playground/Pages/Basics.xcplaygroundpage/Contents.swift [new file with mode: 0644]
learn/AcePlay/AcePlay.playground/Pages/Closure.xcplaygroundpage/Contents.swift [new file with mode: 0644]
learn/AcePlay/AcePlay.playground/Pages/Functions.xcplaygroundpage/Contents.swift [new file with mode: 0644]
learn/AcePlay/AcePlay.playground/Sources/Basic.swift [deleted file]
learn/AcePlay/AcePlay.playground/Sources/Func.swift [deleted file]
learn/AcePlay/AcePlay.playground/contents.xcplayground
learn/AcePlay/AcePlay.playground/playground.xcworkspace/xcuserdata/Ace.xcuserdatad/UserInterfaceState.xcuserstate

diff --git a/learn/AcePlay/AcePlay.playground/Contents.swift b/learn/AcePlay/AcePlay.playground/Contents.swift
deleted file mode 100644 (file)
index 2a17f16..0000000
+++ /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 (file)
index 0000000..1ff1148
--- /dev/null
@@ -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<String> = [ "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..<company.count {
+    print(i, company[i], separator: " - ")
+}
+company.removeLast()
+
+var someIntsA: [Int] = []
+var someIntsB = [Int]()
+var someIntsC = [Int](count: 10, repeatedValue: 1)
+someIntsA.append(1)
+someIntsB.replaceRange(Range<Int>(0..<someIntsB.count), with: [1,3,4])
+someIntsC.removeAtIndex(4)
+someIntsC[1...4] = [1, 2, 3, 4, 5, 6]  //实际赋值量可以与下标Range量不等
+
+printLine("Set")
+
+// Set 只能存储能提供计算出hash value的类型
+str.hashValue
+3.1415926.hashValue
+2005061325.hashValue
+true.hashValue
+
+//var SetA: Set<Int> = []
+var SetB = Set<Character>()
+var SetC: Set<String> = ["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<Int, String>()
+//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 (file)
index 0000000..66a43a8
--- /dev/null
@@ -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 (file)
index 0000000..ebcfc6e
--- /dev/null
@@ -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<Int>) -> (min:Int, max:Int)? {
+    guard data.count > 0 else {
+        return nil
+    }
+    
+    var min = data[0]
+    var max = data[0]
+    
+    for i in 1..<data.count {
+        min = min > data[i] ? data[i] : min
+        max = max < data[i] ? data[i] : max
+    }
+    
+    return (min, max)
+}
+
+var Data: Array<Int> = [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 (file)
index dddda1f..0000000
+++ /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<String> = [ "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..<company.count {
-        print(i, company[i], separator: " - ")
-    }
-    company.removeLast()
-
-    var someIntsA: [Int] = []
-    var someIntsB = [Int]()
-    var someIntsC = [Int](count: 10, repeatedValue: 1)
-    someIntsA.append(1)
-    someIntsB.replaceRange(Range<Int>(0..<someIntsB.count), with: [1,3,4])
-    someIntsC.removeAtIndex(4)
-    someIntsC[1...4] = [1, 2, 3, 4, 5, 6]  //实际赋值量可以与下标Range量不等
-
-    printLine("Set")
-
-    // Set 只能存储能提供计算出hash value的类型
-    str.hashValue
-    3.1415926.hashValue
-    2005061325.hashValue
-    true.hashValue
-
-    //var SetA: Set<Int> = []
-    var SetB = Set<Character>()
-    var SetC: Set<String> = ["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<Int, String>()
-    //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 (file)
index 344f9ab..0000000
+++ /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
index 5da2641c9497c21d096087af6e8f77ce53d251f1..90f71901a3641f8118265400399eb6a0eb8d99a1 100644 (file)
@@ -1,4 +1,8 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<playground version='5.0' target-platform='ios'>
-    <timeline fileName='timeline.xctimeline'/>
+<playground version='6.0' target-platform='ios'>
+    <pages>
+        <page name='Functions'/>
+        <page name='Basics'/>
+        <page name='Closure'/>
+    </pages>
 </playground>
\ No newline at end of file
index 4665619d02c5e2c18e12d993b0cd6ba036aedea6..5f08ca2a96df821454713de6a53f5ff0e5314444 100644 (file)
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