Professional Documents
Culture Documents
Language
CocoaChina
CocoaChina
2014-6-12
CocoaChina
CocoaChina github numbbbbb
github
@CocoaChina
CocoaChina
1. Swift .............................................................................................................. 8
1.1. Swift ............................................................................................................ 8
1.2. Swift ............................................................................................................ 9
............................................................................................................... 9
............................................................................................................. 11
...................................................................................................... 14
.......................................................................................................... 16
................................................................................................... 20
...................................................................................................... 23
................................................................................................................. 25
2. Swift .................................................................................................................. 26
2.1 ........................................................................................................... 26
...................................................................................................... 27
................................................................................................................. 30
................................................................................................................. 31
................................................................................................................. 31
............................................................................................................. 32
........................................................................................ 32
................................................................................................... 33
............................................................................................... 35
.......................................................................................................... 36
............................................................................................................. 37
................................................................................................................. 38
................................................................................................................. 40
................................................................................................................. 44
2.2. ...................................................................................................... 45
................................................................................................................. 46
...................................................................................................... 47
.......................................................................................................... 47
.......................................................................................................... 51
.......................................................................................................... 51
................................................................................................... 52
...................................................................................................... 53
.......................................................................................................... 54
2.3. ................................................................................................... 57
................................................................................................... 58
............................................................................................... 59
................................................................................................... 59
............................................................................................... 60
(Characters) ...................................................................................... 60
................................................................................................... 61
............................................................................................ 61
...................................................................................................... 62
...................................................................................................... 63
............................................................................................ 65
Unicode ........................................................................................................... 65
2.4. .......................................................................................................... 68
................................................................................................................. 68
................................................................................................................. 74
................................................................................................... 79
2.5. ............................................................................................................. 79
For .......................................................................................................... 80
While ...................................................................................................... 84
.......................................................................................................... 88
................................................................................................... 97
2.6. ................................................................................................................103
..............................................................................................104
.......................................................................................105
.....................................................................................................108
.........................................................................................................115
.........................................................................................................119
2.7. ................................................................................................................119
.....................................................................................................120
Trailing ...................................................................................................124
(Caputure) .............................................................................................127
..............................................................................................129
2.8. ................................................................................................................130
Enumeration Syntax ..................................................................130
Switch ...............................................................................132
Associated Values.........................................................................133
Raw Values...................................................................................135
2.9. .....................................................................................................137
..............................................................................................138
....................................................................................141
..................................................................................................143
...........................................................................................145
(Collection)...........................................................146
2.10. ..............................................................................................................151
.........................................................................................................152
.........................................................................................................155
.....................................................................................................158
.......................................................................................160
.........................................................................................................160
2.11. ..............................................................................................................165
(Instance Methods)...........................................................................165
(Type Methods) ................................................................................171
2.12. .......................................................................................................174
..................................................................................................174
..................................................................................................176
..................................................................................................176
2.13. ..............................................................................................................178
Base class..........................................................................179
Subclassing...............................................................................180
Overriding ........................................................................................182
.........................................................................................................186
2.14. .......................................................................................................187
....................................................................................187
..............................................................................................189
.....................................................................................................192
.......................................................................................193
.......................................................................................196
...............................................................207
2.15. .......................................................................................................209
.........................................................................................................209
..................................................................................................209
2.16. ................................................................................................212
ARC ................................................................................................213
ARC .......................................................................................................214
.......................................................................................215
....................................................................................218
................................................................................228
2.17. ...................................................................................................230
.............................................................................231
................................................................................233
................................................................................235
................................................................................235
.............................................................................236
..................................................................................................237
................................................................................238
2.18. .......................................................................................................239
................................................................................239
.........................................................................................................241
....................................................................................242
Any AnyObject ................................................................................243
2.19 ........................................................................................................246
..................................................................................................246
..............................................................................................248
2.20 ...............................................................................................................249
Extension Syntax ..........................................................................249
Computed Properties .............................................................250
Initializers......................................................................................251
Methods ...........................................................................................252
Subscripts ........................................................................................254
Nested Types ............................................................................255
2.21 ...............................................................................................................256
.....................................................................................................256
.........................................................................................................257
.........................................................................................................258
..................................................................................................259
.........................................................................................................261
() ...............................................................................................262
....................................................................................265
....................................................................................266
...........................................................................................267
.....................................................................................................267
.........................................................................................................269
...........................................................................................270
..................................................................................................271
2.22 ...............................................................................................................274
...........................................................................................274
.........................................................................................................276
.........................................................................................................277
..................................................................................................277
.........................................................................................................278
.........................................................................................................281
.........................................................................................................284
Where ....................................................................................................287
2.23 ....................................................................................................290
.........................................................................................................291
.....................................................................................................296
..............................................................................................299
.....................................................................................................300
..................................................................................................304
3 .............................................................................................................305
3.1 ...................................................................................................305
..................................................................................................306
3.2 .........................................................................................................307
.....................................................................................................307
............................................................................................................307
............................................................................................................309
............................................................................................................309
............................................................................................................313
3.3 ................................................................................................................314
.........................................................................................................315
.....................................................................................................316
.........................................................................................................316
.........................................................................................................317
.........................................................................................................319
.........................................................................................................319
...........................................................................................320
..................................................................................................321
............................................................................................................322
..................................................................................................323
.........................................................................................................323
3.4 .............................................................................................................324
Prefix Expressions.....................................................................325
Binary Expressions....................................................................325
Assignment Operator ................................................................328
Ternary Conditional Operator..............................................328
Type-Casting Operators ......................................................329
Primary Expressions..................................................................330
Postfix Expressions ...................................................................336
3.5 ................................................................................................................342
.........................................................................................................343
.........................................................................................................346
..................................................................................................350
3.6 ................................................................................................................354
.........................................................................................................355
............................................................................................................356
.........................................................................................................356
.........................................................................................................357
.........................................................................................................358
..............................................................................................362
.........................................................................................................363
.........................................................................................................367
.....................................................................................................369
.........................................................................................................372
.....................................................................................................376
.........................................................................................................377
.........................................................................................................378
..................................................................................................378
.....................................................................................................379
3.7 ................................................................................................................381
.........................................................................................................382
.........................................................................................................385
3.8 ................................................................................................................385
Wildcard Pattern ......................................................................386
Identifier Pattern......................................................................387
Value-Binding Pattern ...............................................................387
Tuple Pattern...............................................................................388
Enumeration Case Pattern......................................................389
Type-Casting Patterns ............................................................389
Expression Pattern....................................................................390
3.9 .........................................................................................................391
..................................................................................................391
..................................................................................................393
3.10 ........................................................................................................394
................................................................................................................395
.........................................................................................................396
................................................................................................................397
................................................................................................................402
................................................................................................................403
............................................................................................................403
.........................................................................................................406
................................................................................................................409
1. Swift
1.1. Swift
API
API
Swift
playgrounds Swift
Swift
Hello World
Swift Apple
Swift iOS OS X
Swift
1.2. Swift
@numbbbbbChildhoodAndy
Hello, world Swift
1. println("hello, world")
C Objective-C Swift
main
Swift
Xcode
let var
1. var myVariable = 42
2. myVariable = 50
3. let myConstant = 42
myVariable
integer
1. let implicitInteger = 70
2. let implicitDouble = 70.0
3. let explicitDouble: Double = 70
Float 4
String
1. let apples = 3
2. let oranges = 5
3. let appleSummary = "I have \(apples) apples."
4. let fruitSummary = "I have \(apples + oranges) pieces of fruit."
\()
[]key
1. var shoppingList = ["catfish", "water", "tulips", "blue paint"]
10
"Malcolm": "Captain",
6.
"Kaylee": "Mechanic",
7. ]
8. occupations["Jayne"] = "Public Relations"
[][:]
1. shoppingList = []
//
if score > 50 {
5.
6.
teamScore += 3
} else {
7.
8.
teamScore += 1
}
9. }
10. teamScore
if if score { ... }
if let
nil
11
1. var optionalString: String? = "Hello"
2. optionalString == nil
3.
4. var optionalName: String? = "John Appleseed"
5. var greeting = "Hello!"
6. if let name = optionalName {
7.
8. }
switch
1. let vegetable = "red pepper"
2. switch vegetable {
3. case "celery":
4.
9. default:
10.
11. }
default
switch switch
break
for-in
12
1. let interestingNumbers = [
2.
3.
4.
5. ]
6. var largest = 0
7. for (kind, numbers) in interestingNumbers {
8.
9.
10.
largest = number
11.
12.
}
}
13. }
14. largest
while
1. var n = 2
2. while n < 100 {
3.
n = n * 2
4. }
5. n
6.
7. var m = 2
8. do {
9.
m = m * 2
..
1. var firstForLoop = 0
2. for i in 0..3 {
3.
firstForLoop += i
4. }
5. firstForLoop
6.
7. var secondForLoop = 0
13
secondForLoop += 1
10. }
11. secondForLoop
.....
func ->
1. func greet(name: String, day: String) -> String {
2.
3. }
4. greet("Bob", "Tuesday")
day
3. }
4. getGasPrices()
var sum = 0
3.
4.
sum += number
5.
6.
return sum
7. }
8. sumOf()
9. sumOf(42, 597, 12)
14
var y = 10
3.
func add() {
4.
y += 5
5.
6.
add()
7.
return y
8. }
9. returnFifteen()
3.
return 1 + number
4.
5.
return addOne
6. }
7. var increment = makeIncrementer()
8. increment(7)
3.
if condition(item) {
4.
return true
5.
6.
7.
return false
8. }
9. func lessThanTen(number: Int) -> Bool {
10.
11. }
12. var numbers = [20, 19, 7, 12]
13. hasAnyMatches(numbers, lessThanTen)
15
{} in
1. numbers.map({
2.
3.
4.
return result
5.
})
class
1. class Shape {
2.
var numberOfSides = 0
3.
4.
5.
6. }
let
16
Shape init
1. class NamedShape {
2.
3.
4.
5.
init(name: String) {
6.
self.name = name
7.
8.
9.
10.
11.
12. }
self
numberOfSides
name
deinit
override override
override
1. class Square: NamedShape {
2.
3.
4.
5.
self.sideLength = sideLength
6.
super.init(name: name)
7.
numberOfSides = 4
8.
17
9.
10.
11.
Double {
12.
13.
14.
15.
16.
17. }
18. let test = Square(sideLength: 5.2, name: "my test square")
19. test.area()
20. test.simpleDescription()
NamedShape Circle
area describe
getter setter
1. class EquilateralTriangle: NamedShape {
2.
3.
4.
5.
self.sideLength = sideLength
6.
super.init(name: name)
7.
numberOfSides = 3
8.
9.
10.
11.
get {
12.
13.
14.
set {
15.
16.
17.
18.
19.
20.
21.
18
22. }
23. var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle"
)
24. triangle.perimeter
25. triangle.perimeter = 9.9
26. triangle.sideLength
EquilateralTriangle
1.
2.
3. getters setters
willSet didSet
1. class TriangleAndSquare {
2.
3.
willSet {
4.
square.sideLength = newValue.sideLength
5.
6.
7.
8.
willSet {
9.
triangle.sideLength = newValue.sideLength
10.
11.
12.
13.
14.
15.
16. }
17. var triangleAndSquare = TriangleAndSquare(size: 10, name: "another tes
t shape")
19
18. triangleAndSquare.square.sideLength
19. triangleAndSquare.triangle.sideLength
20. triangleAndSquare.square = Square(sideLength: 50, name: "larger square
")
21. triangleAndSquare.triangle.sideLength
1. class Counter {
2.
3.
4.
5.
6. }
7. var counter = Counter()
8. counter.incrementBy(2, numberOfTimes: 7)
??
nil? nil?
enum
1. enum Rank: Int {
2.
case Ace = 1
3.
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
4.
5.
6.
switch self {
7.
case .Ace:
8.
return "ace"
20
9.
case .Jack:
10.
return "jack"
11.
case .Queen:
12.
return "queen"
13.
case .King:
14.
return "king"
15.
default:
16.
return String(self.toRaw())
17.
18.
}
}
19. }
20. let ace = Rank.Ace
21. let aceRawValue = ace.toRaw()
Rank
Int
toRaw fromRaw
1. if let convertedRank = Rank.fromRaw(3) {
2.
3. }
1. enum Suit {
2.
3.
4.
switch self {
5.
case .Spades:
6.
7.
8.
9.
10.
11.
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
21
12.
return "clubs"
13.
14.
}
}
15.
16. }
17. let hearts = Suit.Hearts
18. let heartsDescription = hearts.simpleDescription()
struct
1. struct Card {
2.
3.
4.
5.
6.
(suit.simpleDescription())"
7.
8. }
9. let threeOfSpades = Card(rank: .Three, suit: .Spades)
10. let threeOfSpadesDescription = threeOfSpades.simpleDescription()
22
1. enum ServerResponse {
2.
3.
case Error(String)
4. }
5.
6. let success = ServerResponse.Result("6:00 am", "8:09 pm")
7. let failure = ServerResponse.Error("Out of cheese.")
8.
9. switch success {
10. case let .Result(sunrise, sunset):
11.
\(error)"
14. }
ServerResponse switch
ServerResponse
protocol
1. protocol ExampleProtocol {
2.
3.
4. }
3.
4.
func adjust() {
5.
6.
simpleDescription += "
7. }
23
8. var a = SimpleClass()
9. a.adjust()
10. let aDescription = a.simpleDescription
11.
12. struct SimpleStructure: ExampleProtocol {
13.
14.
15.
16.
17. }
18. var b = SimpleStructure()
19. b.adjust()
20. let bDescription = b.simpleDescription
SimpleStructure mutating
SimpleClass
extension
3.
4.
5.
6.
7.
self += 42
}
8. }
9.
10. 7.simpleDescription
Double absoluteValue
24
protocolValue simpleClass
ExampleProtocol
3.
for i in 0..times {
4.
result += item
5.
6.
return result
7. }
8. repeat("knock", 4)
case None
4.
case Some(T)
5. }
6. var possibleInteger: OptionalValue<Int> = .None
7. possibleInteger = .Some(100)
where
25
5.
return true
6.
7.
8.
9.
return false
10. }
11. anyCommonElements([1, 2, 3], [3])
anyCommonElements
2. Swift
2.1
numbbbbbGithub , lyukaGithub , JaySurplusGithub
C Swift Swift
C Swift
26
Swift Optional
x Objective-C nil
Objective-C nil
Swift
Swift Swift
String Int
maximumNumberOfLoginAttempts
welcomeMessage 10 "Hello"
let var
1. let maximumNumberOfLoginAttempts = 10
2. var currentLoginAttempt = 0
maximumNumberOfLoginAttempts 10
currentLoginAttempt 0.
27
1. var x = 0.0, y = 0.0, z = 0.0
let
(type annotation)
welcomeMessage String
...
String welcomeMessage
String String
welcomeMessage
1. welcomeMessage = "Hello"
Swift
welcomeMessage welcomeMessage
Unicode
1. let = 3.14159
28
2. let = ""
3. let ???????? = "dogcow"
Unicode
Swift
`
friendlyWelcome
"Hello!""Bonjour!":
1. var friendlyWelcome = "Hello!"
2. friendlyWelcome = "Bonjour!"
3. // friendlyWelcome "Bonjour!"
println :
1. println(friendlyWelcome)
2. // "Bonjour!"
println Xcodeprintln
console( print
)
println String
29
1. println("This is a string")
2. // "This is a string"
Swift
Swift C (//):
1. //
(/*)
(*/):
1. /* ,
2. */
C Swift
1. /*
2. /* */
3. */
30
Swift ;
42 -23
Swift 81632 64 C
8 UInt832 Int32
Swift
min max
1. let minValue = UInt8.min
// minValue 0 UInt8
Int
Swift Int
- 32 Int Int32
- 64 Int Int64
Int
32 Int 2147483648~2147483647
31
UInt
Swift UInt
- 32 UInt UInt32
- 64 UInt UInt64
UInt
Int Int
3.141590.1 -273.15
Int Swift
- Double 64
- Float 32
Double 15 Float 6
Swift
32
(type inference)
C Objective-C Swift
42 Swift
Int
1. let meaningOfLife = 42
2. // meaningOfLife Int
Swift Double
1. let pi = 3.14159
2. // pi Double
Double
1. let anotherPi = 3 + 0.14159
2. // anotherPi Double
3
Double
33
- 0b
- 0o
- 0x
17:
1. let decimalInteger = 17
2. let binaryInteger = 0b10001
// 17
// 17
// 17
0x
(exponent) e
p
exp$10^{exp}$
1.25e2 $1.25 10^{2}$ 125.0
1.25e-2 $1.25 10^{-2}$ 0.0125
exp$2^{exp}$
0xFp2 $15 2^{2}$ 60.0
0xFp-2 $15 2^{-2}$ 3.75
12.1875
1. let decimalDouble = 12.1875
2. let exponentDouble = 1.21875e1
3. let hexadecimalDouble = 0xC.3p0
34
Int
Int8
-128~127 UInt8 0~255
twoThousand UInt16
one Uint8 UInt16(one)
UInt16 one
1. let twoThousand: UInt16 = 2_000
2. let one: UInt8 = 1
3. let twoThousandAndOne = twoThousand + UInt16(one)
UInt16 twoThousandAndOne
UInt16 UInt16
35
SomeType(ofInitialValue) Swift
UInt16 UInt8
UInt8 UInt16 UInt16
1. let three = 3
2. let pointOneFourOneFiveNine = 0.14159
3. let pi = Double(three) + pointOneFourOneFiveNine
4. // pi 3.14159 Double
three Double
Double Float
1. let integerPi = Int(pi)
2. // integerPi 3 Int
4.75 43.9 -3
3
0.14159
36
if
1. if turnipsAreDelicious {
2.
3. } else {
4.
5. }
6. // "Eww, turnips are horrible."
if
Bool Swift
37
1. let i = 1
2. if i {
3.
//
4. }
1. let i = 1
2. if i == 1 {
3.
//
4. }
i == 1 Bool i == 1
Swift
tuples
38
decompose
_
1. let (justTheStatusCode, _) = http404Error
2. println("The status code is \(justTheStatusCode)")
3. // "The status code is 404"
(Int, String)
[
(06_Functions.html#Function_Parameters_and_Return_Values)
39
optionals
- x
C Objective-C Objective-C
nilnil
C
Objective-C NSNotFound
Swift
40
if
if true
false
(!)
forced
unwrapping
1. if convertedNumber {
2.
3. } else {
4.
5. }
6. // "123 has an integer value of 123"
if
!!
nil
optional binding
if while
if while
if
1. if let constantName = someOptional {
2.
statements
3. }
possibleNumber
41
3. } else {
4.
5. }
6. // "123 has an integer value of 123"
actualNumber if
!actualNumber
if
actualNumber if var actualNumber
nil
nil
1. var serverResponseCode: Int? = 404
2. // serverResponseCode Int 404
3. serverResponseCode = nil
4. // serverResponseCode
nil
nil
1. var surveyAnswer: String?
2. // surveyAnswer nil
42
if
Swift
String String
//
43
1. if assumedString {
2.
println(assumedString)
3. }
4. // "An implicitly unwrapped optional string."
println(definiteString)
3. }
4. // "An implicitly unwrapped optional string."
nil
nil
assertion
true
true false
Xcode
44
1. let age = -3
2. assert(age >= 0, "A person's age cannot be less than zero")
3. // age < 0
1. assert(age >= 0)
-
- nil nil
2.2.
stanzhaiGithub
45
, , . , + ( let i
= 1 + 2). &&( if enteredDoorCode && passedRetinaScan),
++i .
Swift C , . ,
= , == = Bug. ( + , -, *, /, %)
,
. Swift .
.
C , Swift ( % ), C
, ( a..b a...b ), .
Swift , ,
, .
, .
, -a.
, , !b,
, i++,
, 2 + 3. , .
, C , Swift ,
a ? b : c.
, 1 + 2 , + ,
1 2.
46
a = b, b a .
1. let b = 10
2. var a = 5
3. a = b
4. // a 10
,
1. let (x, y) = (1, 2)
2. // x 1, y 2
C Objective-C , Swift . :
1. if x = y {
2.
// , x = y
3. }
===, if x = y , Swift
.
Swift :
+
*
/
1. 1 + 2
// 3
2. 5 - 3
// 2
3. 2 * 3
// 6
4. 10.0 / 2.5
// 4.0
47
C Objective-C , Swift .
Swift , ( a &+ b ). : .
+ :
1. "hello, " + "world"
// "hello, world"
, :
1. let dog: Character = "d"
2. let cow: Character = "c"
3. let dogCow = dog + cow
4. // : , win os ,
5. // dogCow "dc"
,.
a % b b a , .
(%). ,
, .
, 9 % 4, 4 9 .
2 , , 1 ('*')
Swift
1. 9 % 4
// 1
a % b , %, :
48
1. a = (b ) +
, a .
9 4 , 1:
1. 9 = (4 2) + 1
, -9 % 4 :
1. -9 % 4
// -1
-9 4 , -2 :
1. -9 = (4 -2) + -1
-1.
-b , -b . a % b a % -b .
C Objective-C, Swift .
1. 8 % 2.5 // 0.5
C , Swift 1 1 ++ -- .
1. var i = 0
2. ++i
// i = 1
49
i . i ,
. ,
.
++ , .
++ , .
? :
1. var a = 0
2. let b = ++a // a b 1
3. let c = a++ // a 2, c a 1
, let b = ++a, a 1 a . a b 1.
let c = a++, a , a 1. c a 1, a
1 2.
- () :
1. let three = 3
2. let minusThree = -three
// minusThree -3
, .
+ .
1. let minusSix = -6
2. let alsoMinusSix = +minusSix
// alsoMinusSix -6
50
+ , ,
, .
C , Swift = ,
+= :
1. var a = 1
2. a += 2 // a 3
a += 2 a = a + 2 , .
, let b = a += 2 .
.
C Swift .
a == b
a != b
a > b
a < b
a >= b
a <= b
:
1. 1 == 1
// true, 1 1
51
2. 2 != 1
// true, 2 1
3. 2 > 1
// true, 2 1
4. 1 < 2
// true, 1 2
5. 1 >= 1
// true, 1 1
6. 2 <= 1
// false, 2 1
, if :
1. let name = "world"
2. if name == "world" {
3.
println("hello, world")
4. } else {
5.
6. }
7. // "hello, world", `name` "world"
if , .
, ? 1 : 2.
. , 1
; , 2 .
:
1. if question: {
2.
answer1
3. }
4. else {
5.
answer2
6. }
. , 50 ;
, 20 .
1. let contentHeight = 40
2. let hasHeader = true
52
:
1. let contentHeight = 40
2. let hasHeader = true
3. var rowHeight = contentHeight
4. if hasHeader {
5.
rowHeight = rowHeight + 50
6. } else {
7.
rowHeight = rowHeight + 20
8. }
9. // rowHeight 90
, .
, rowHeight , if .
. ,
.
.
Swift .
a...b a b ( a b).
, for-in :
1. for index in 1...5 {
2.
3. }
4. // 1 * 5 = 5
5. // 2 * 5 = 10
6. // 3 * 5 = 15
7. // 4 * 5 = 20
8. // 5 * 5 = 25
53
for-in, .
a..b a b b . ,
.
0 (), 0
.
1. let names = ["Anna", "Alex", "Brian", "Jack"]
2. let count = names.count
3. for i in 0..count {
4.
5. }
6. // 1 Anna
7. // 2 Alex
8. // 3 Brian
9. // 4 Jack
: 4 , 0..count 3 (), .
, .
. Swift C .
!a
a && b
a || b
, , . a,
:
54
println("ACCESS DENIED")
4. }
5. // prints "ACCESS DENIED"
, ,
, .
, :
1. let enteredDoorCode = true
2. let passedRetinaScan = false
3. if enteredDoorCode && passedRetinaScan {
4.
println("Welcome!")
5. } else {
6.
println("ACCESS DENIED")
7. }
8. // "ACCESS DENIED
a || b | .
true, true.
, "", true ,
, .
55
hasDoorKey
false,
println("Welcome!")
5. } else {
6.
println("ACCESS DENIED")
7. }
8. // "Welcome!"
:
1. if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverrideP
assword {
2.
println("Welcome!")
3. } else {
4.
println("ACCESS DENIED")
5. }
6. // "Welcome!"
&& || . , && || .
. :
; ;
, .
, , false,
, true.
, ,
. , ,
.
56
println("Welcome!")
3. } else {
4.
println("ACCESS DENIED")
5. }
6. // prints "Welcome!"
.
, .
, !
2.3.
wh1100717Github
String "hello, world", "albatross"Swift String
Character
String
Unicode Unicode
String
57
// $,
// ,
58
String
1. var emptyString = ""
// initializer syntax
3. //
Boolean isEmpty
1. if emptyString.isEmpty {
2.
3. }
4. // "Nothing to see here"
59
Swift String
/
Structures and Enumerations Are Value
Types
Swift /
Swift
(Characters)
println(character)
3. }
4. // D
5. // o
6. // g
7. // !
8. // ????
60
Character
countElements
1. Unicode Unicode
Swift
countElements
2. countElements
NSString length NSString length UTF-16
code units Unicode
NSString length
Swift String utf16count
(+)
61
//
"hello!"
7. let stringPlusString = string1 + string2
//
"hello there"
8. let characterPlusString = character1 + string1
//
"!hello"
9. let characterPlusCharacter
= character1 + character2
// "!?"
(+=)
1. let multiplier = 3
2. let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
3. // message is "3 times 2.5 is 7.5"
62
multiplier \(multiplier)
multiplier
(") (\)
Swift
5. }
6. // prints "These two strings are considered equal"
/
hasPrefix/hasSuffix /
Boolean /
63
1. let romeoAndJuliet = [
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13. ]
hasPrefix romeoAndJuliet
1. var act1SceneCount = 0
2. for scene in romeoAndJuliet {
3.
if scene.hasPrefix("Act 1 ") {
4.
5.
++act1SceneCount
}
6. }
7. println("There are \(act1SceneCount) scenes in Act 1")
8. // prints "There are 5 scenes in Act 1"
1. var mansionCount = 0
2. var cellCount = 0
3. for scene in romeoAndJuliet {
4.
if scene.hasSuffix("Capulet's mansion") {
5.
6.
++mansionCount
} else if scene.hasSuffix("Friar Lawrence's cell") {
7.
8.
++cellCount
}
9. }
10. println("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
11. // prints "6 mansion scenes; 2 cell scenes"
64
uppercaseString lowercaseString
/
1. let normal = "Could you help me, please?"
2. let shouty = normal.uppercaseString
3. // shouty "COULD YOU HELP ME, PLEASE?"
4. let whispered = normal.lowercaseString
5. // whispered "could you help me, please?"
Unicode
Unicode
Swift Unicode
Unicode
Unicode (Terminology)
Unicode unicode unicode
21 () U+0061 A ("a")U+1F425
("????")
Unicode unicode
Unicode -code units
UTF-8 ( 8 ) UTF-16 ( 16
)
Unicode
Swift Unicode
65
for-in Unicode
Working with Characters
Unicode
1.UTF-8 ( utf8 )
2.UTF-16 ( utf16 )
3.21 Unicode ( unicodeScalars )
D,o,g !
UTF-8
utf8 UTF-8 UTF8View
UTF8View 8 (UInt8) UIn8 UTF-8
print("\(codeUnit) ")
3. }
4. print("\n")
5. // 68 111 103 33 240 159 144 182
UTF-16
utf16 UTF-16 UTF16View
UTF16View 16 (UInt16) UInt16
66
UTF-16
1. for codeUnit in dogString.utf16 {
2.
print("\(codeUnit) ")
3. }
4. print("\n")
5. // 68 111 103 33 55357 56374
UnicodeScalar 21 UInt32
1. for scalar in dogString.unicodeScalars {
2.
print("\(scalar.value) ")
3. }
4. print("\n")
5. // 68 111 103 33 128054
UnicodeScalar
println("\(scalar) ")
3. }
67
4. // D
5. // o
6. // g
7. // !
8. // ????
2.4.
bzsyGithub
Swift
Swift
Swift
Swift
see Mutability of Collections and Assignment
and Copy Behavior for Collection Types
class Int
68
Int Swift
[value 1, value 2, value 3]
shoppingList
1. var shoppingList: String[] = ["Eggs", "Milk"]
2. // shoppingList
shoppingList String[]
String String shoppinglist
String "Eggs" "Milk"
String String
shoppinglist
Swift
shoppinglist
69
count
1. println("The shopping list contains \(shoppingList.count) items.")
2. // "The shopping list contains 2 items." 2
isEmpty count 0
1. if shoppingList.isEmpty {
2.
3. } else {
4.
5. }
6. // "The shopping list is not empty."shoppinglist
append
1. shoppingList.append("Flour")
2. // shoppingList 3
+=
1. shoppingList += "Baking Powder"
2. // shoppingList
+=
1. shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
2. // shoppingList 7
70
1. var firstItem = shoppingList[0]
2. // "Eggs"
0 1 Swift
count count 0
count - 1
insert(atIndex:)
1. shoppingList.insert("Maple Syrup", atIndex: 0)
2. // shoppingList 7
3. // "Maple Syrup"
removeAtIndex
:
1. let mapleSyrup = shoppingList.removeAtIndex(0)
71
2. // 0
3. // shoppingList 6 Maple Syrup
4. // mapleSyrup "Maple Syrup"
0
"Six eggs":
1. firstItem = shoppingList[0]
2. // firstItem "Six eggs"
removeLast removeAtIndex
count
apples "Apples"
for-in
1. for item in shoppingList {
2.
println(item)
3. }
4. // Six eggs
5. // Milk
6. // Flour
7. // Baking Powder
8. // Bananas
enumerate
enumerate
72
3. }
4. // Item 1: Six eggs
5. // Item 2: Milk
6. // Item 3: Flour
7. // Item 4: Baking Powder
8. // Item 5: Bananas
for-in for
[]
1. someInts.append(3)
2. // someInts INT
3. someInts = []
4. // someInts Int[]
Swift Array
countrepeatedValue
73
valuekey
Swift
Objective-C
NSDictionary NSMutableDictionary
Swift
KeyType Swift
StringInt Double Bool
74
key value
airports
Swift
75
count
1. println("The dictionary of airports contains \(airports.count) items."
)
2. // "The dictionary of airports contains 2 items."
key
1. airports["LHR"] = "London"
2. // airports
updateValue(forKey:)
updateValue(forKey:)
updateValue(forKey:) String
String? String
nil
1. if let oldValue = airports.updateValue("Dublin Internation", forKey: "
DUB") {
2.
3. }
4. // "The old value for DUB was Dublin."dub dublin
nil
1. if let airportName = airports["DUB"] {
2.
3. } else {
4.
76
5. }
6. // "The name of the airport is Dublin INTernation."
nil
1. airports["APL"] = "Apple Internation"
2. // "Apple Internation" APL ,
3. airports["APL"] = nil
4. // APL
removeValueForKey
value nil
1. if let removedValue = airports.removeValueForKey("DUB") {
2.
3. } else {
4.
5. }
6. // "The removed airport's name is Dublin International."
for-in (key,
value)
1. for (airportCode, airportName) in airports {
2.
prINTln("\(airportCode): \(airportName)")
3. }
4. // TYO: Tokyo
5. // LHR: London Heathrow
for-in For
keys values
77
3. }
4. // Airport code: TYO
5. // Airport code: LHR
6.
7. for airportName in airports.values {
8.
9. }
10. // Airport name: Tokyo
11. // Airport name: London Heathrow
Array API
keys values
1. let airportCodes = Array(airports.keys)
2. // airportCodes is ["TYO", "LHR"]
3.
4. let airportNames = Array(airports.values)
5. // airportNames is ["Tokyo", "London Heathrow"]
Swift
[:]
1. namesOfIntegers[16] = "sixteen"
78
2. // namesOfIntegers
3. namesOfIntegers = [:]
4. // namesOfIntegers Int, String
Swift
Swift
Swift
Assignment and Copy Behavior for Collection Types
Swift
2.5.
numbbbbbGithub
Swift C for while
if switch
break continue
79
For
for Swift for
for-in (range)(sequence)(collection)(progression)
for (for-condition-increment)
For-In
for-in
5
1. for index in 1...5 {
2.
3. }
4. // 1 times 5 is 5
5. // 2 times 5 is 10
6. // 3 times 5 is 15
7. // 4 times 5 is 20
8. // 5 times 5 is 25
80
(...) 1 5
index 1
index 5
index 2 println
index index
let
index index
index
1. let base = 3
2. let power = 10
3. var answer = 1
4. for _ in 1...power {
5.
answer *= base
6. }
7. println("\(base) to the power of \(power) is \(answer)")
8. // prints "3 to the power of 10 is 59049
base power 3 10 1 3 0
3 10 0 9
_
for-in
1. let names = ["Anna", "Alex", "Brian", "Jack"]
2. for name in names {
3.
println("Hello, \(name)!")
81
4. }
5. // Hello, Anna!
6. // Hello, Alex!
7. // Hello, Brian!
8. // Hello, Jack!
(key-value pairs)
key, value for-in
key, value(key) animalName
legCount
1. let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
2. for (animalName, legCount) in numberOfLegs {
3.
4. }
5. // spiders have 8 legs
6. // ants have 6 legs
7. // cats have 4 legs
for-in
1. for character in "Hello" {
2.
println(character)
3. }
4. // H
5. // e
6. // l
7. // l
8. // o
For for-condition-increment
for-in Swift C for :
1. for var index = 0; index < 3; ++index {
82
2.
println("index is \(index)")
3. }
4. // index is 0
5. // index is 1
6. // index is 2
statements
3. }
C 3 Swift
initialization; condition; increment
1initialization expression
1. initialization
2. while condition {
3.
statements
4.
increment
5. }
83
println("index is \(index)")
4. }
5. // index is 0
6. // index is 1
7. // index is 2
8. println("The loop statements were executed \(index) times")
9. // prints "The loop statements were executed 3 times
index 3 2 ++index
index 3 index < 3 false
While
While false
Swift while
- while
- do-while
While
While true
false
while
1. while condition {
2.
statements
3. }
84
- 25 25
- 6
-
-
Int finalSquare
26 Int 0 25 0
25 26
1. let finalSquare = 25
2. var board = Int[](count: finalSquare + 1, repeatedValue: 0)
3 11 board[03] +08
11 3 +i-i
10 0
85
0
1. var square = 0
2. var diceRoll = 0
3. while square < finalSquare {
4.
5.
if ++diceRoll == 7 { diceRoll = 1 }
6.
7.
square += diceRoll
8.
9.
10.
11.
square += board[square]
}
12. }
13. println("Game over!")
diceRoll 0
while diceRoll (++i) 1
++diceRoll diceRoll
diceRoll 7 1 diceRoll
1, 2, 3, 4, 5, 6, 1, 2
diceRoll 25
square board[square]
square board count
while
25 false
while while
86
Do-While
while do-while while
false
do-while
1. do {
2.
statements
3. } while condition
do-while
25
0 board[0] 0
1. do {
2.
3.
square += board[square]
4.
5.
if ++diceRoll == 7 { diceRoll = 1 }
6.
7.
square += diceRoll
87
diceRoll
Swift if switch
if switch
(pattern-matching)
If
if
1. var temperatureInFahrenheit = 30
2. if temperatureInFahrenheit <= 32 {
3.
4. }
5. // prints "It's very cold. Consider wearing a scarf."
32
if
if else
1. temperatureInFahrenheit = 40
2. if temperatureInFahrenheit <= 32 {
88
3.
4. } else {
5.
6. }
7. // prints "It's not that cold. Wear a t-shirt."
40
else
if
1. temperatureInFahrenheit = 90
2. if temperatureInFahrenheit <= 32 {
3.
6. } else {
7.
8. }
9. // prints "It's really warm. Don't forget to wear sunscreen."
if else
else
1. temperatureInFahrenheit = 72
2. if temperatureInFahrenheit <= 32 {
3.
6. }
if else if
89
Switch
switch (pattern)
switch switch if
switch
`respond to value 1`
`respond to value 2 or 3`
7. default:
8.
9. }
case if switch
switch case
(default)
switch
switch someCharacter
1. let someCharacter: Character = "e"
2. switch someCharacter {
3. case "a", "e", "i", "o", "u":
4.
println("\(someCharacter) is a vowel")
5. case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
6. "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
7.
println("\(someCharacter) is a consonant")
8. default:
90
9.
10. }
11. // prints "e is a vowel"
case case
case
switch
(Fallthrough)
C Objective-C switch Swift case
switch case
case break switch
break
case case
6. default:
7.
8. }
9. // this will report a compile-time error
91
case
1. switch `some value to consider` {
2. case `value 1`,
3. `value 2`:
4.
`statements`
5. }
case fallthrough
(Fallthrough)
case
naturalCount = "no"
7. case 1...3:
8.
9. case 4...9:
10.
naturalCount = "several"
17. default:
18.
19. }
20. println("There are \(naturalCount) \(countedThings).")
92
21. // prints "There are millions and millions of stars in the Milky Way."
(Tuple)
switch
(_)
(Int, Int)(x, y)
1. let somePoint = (1, 1)
2. switch somePoint {
3. case (0, 0):
4.
11. default:
12.
13. }
14. // prints "(1, 1) is inside the box"
93
switch (0, 0) x
y 4x4
(Value Bindings)
case case
(Int, Int)(x, y)
1. let anotherPoint = (2, 0)
2. switch anotherPoint {
3. case (let x, 0):
4.
94
9. }
10. // prints "on the x-axis with an x value of 2"
switch x y
case x y anotherPoint
casecase (let x, 0) 0
x casecase (0, let y) 0
y
case
println
x y case
case
95
Where
case where
(x, y)
1. let yetAnotherPoint = (1, -1)
2. switch yetAnotherPoint {
3. case let (x, y) where x == y:
4.
9. }
10. // prints "(1, -1) is on the line x == -y"
switch x == y
x == -y
case x y yetAnotherPoint
where (filter) where
case
96
case switch
Swift
- continue
- break
- fallthrough
- return
continue ,break, fallthrough
return
Continue
continue
switch character {
5.
6.
continue
7.
default:
8.
puzzleOutput += character
9.
97
10. }
11. println(puzzleOutput)
12. // prints "grtmndsthnklk"
continue
switch
Break
break switch
break
Break
break
(})
Switch Break
switch break switch
switch (})
Swift switch
break
break switch
NOTE switch
switch break
switch Character
98
2. possibleIntegerValue: Int?
3. switch numberSymbol {
4. case "1", "?", "", "?":
5.
possibleIntegerValue = 1
possibleIntegerValue = 2
possibleIntegerValue = 3
possibleIntegerValue = 4
12. default:
13.
break
14. }
15. if let integerValue = possibleIntegerValue {
16.
17. } else {
18.
19. }
20. // prints "The integer value of is 3."
numberSymbol 1...4
switch Int? possibleIntegerValue
switch 'possibleIntegerValue'
'possibleIntegerValue' nil
possibleIntegerValue switch
Character
default default
break default break
, if let
99
Fallthrough
Swift switch case case
case switch
C break switch
case
Swift switch
C case
C (fallthrough) case
fallthrough fallthrough
1. let integerToDescribe = 5
2. var description = "The number \(integerToDescribe) is"
3. switch integerToDescribe {
4. case 2, 3, 5, 7, 11, 13, 17, 19:
5.
6.
fallthrough
7. default:
8.
9. }
10. println(description)
11. // prints "The number 5 is a prime number, and also an integer."
String description
switch integerToDescribe integerToDescribe
description
fallthrough "" default default
description , switch
integerToDescribe switch
integerToDescribe default
switch println 5
100
NOTEfallthrough case
fallthrough case C
switch
Labeled Statements
Swift switch switch
switch break
break switch ,
continue
switch break
continue
while
switch
1. label name: while condition {
2.
statements
3. }
- 25
25
25
101
finalSquare,board,square diceRoll
1. let finalSquare = 25
2. var board = Int[](count: finalSquare + 1, repeatedValue: 0)
3. board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
4. board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
5. var square = 0
6. var diceRoll = 0
if ++diceRoll == 7 { diceRoll = 1 }
3.
4.
case finalSquare:
5.
6.
break gameLoop
7.
8.
9.
10.
continue gameLoop
default:
102
11.
12.
square += diceRoll
13.
square += board[square]
14.
15. }
16. println("Game over!")
switch
- break gameLoop
while
-
continue gameLoop while
-
while
2.6.
Da
103
Swift
Objective-C
/
Swift Swift
,,
--argument
argumentsparameter
greetingForPerson --
-- personName String
3.
return greeting
4. }
func ->
104
1. println(sayHello("Anna"))
2. // prints "Hello, Anna!"
3. println(sayHello("Brian"))
4. // prints "Hello, Brian!"
sayHello "Anna"
"Brian"
return
1. func sayHello(personName: String) -> String {
2.
3. }
4. println(sayHello("Anna"))
5. // prints "Hello again, Anna!"
swift
105
3. }
4. println(halfOpenRangeLength(1, 10))
5. // prints "9"
String
1. func sayHelloWorld() -> String {
2.
3. }
4. println(sayHelloWorld())
5. // prints "hello, world"
sayHello waveGoodbye
String
1. func sayGoodbye(personName: String) {
2.
println("Goodbye, \(personName)!")
3. }
4. sayGoodbye("Dave")
5. // prints "Goodbye, Dave!"
- >
106
sayGoodbye
Void
()
println(stringToPrint)
3.
return countElements(stringToPrint)
4. }
5. func printWithoutCounting(stringToPrint: String) {
6.
printAndCount(stringToPrint)
7. }
8. printAndCount("hello, world")
9. // prints "hello, world" and returns a value of 12
10. printWithoutCounting("hello, world")
11. // prints "hello, world" but does not return a value
printAndCount Int
printWithoutCounting
count
3.
4.
switch String(character).lowercaseString {
107
5.
6.
++vowels
7.
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
8.
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
9.
++consonants
10.
default:
11.
++others
12.
13.
14.
15. }
Int
3.
4. }
108
,
:
1. func someFunction(externalParameterName localParameterName: Int) {
2.
3.
4. }
"joiner"
return s1 + joiner + s2
3. }
, join :
1. func join(string s1: String, toString s2: String, withJoiner joiner: S
tring)
2.
-> String {
3.
return s1 + joiner + s2
4. }
109
1. join(string: "hello", toString: "world", withJoiner: ", ")
2. // returns "hello, world"
join , sentencelike ,
hash
Swift
containsCharacter , hash
(#)
1. func containsCharacter(#string: String, #characterToFind: Character) > Bool {
2.
3.
if character == characterToFind {
4.
return true
5.
6.
7.
return false
8. }
110
join joiner
1. func join(string s1: String, toString s2: String,
2.
3.
4. }
join joiner
,()
Swift
hash
#
111
join joiner
1. func join(s1: String, s2: String, joiner: String = " ") -> String {
2.
return s1 + joiner + s2
3. }
Swift
(_)
--
...
,
numbers Double... numbers Double[]
3.
4.
total += number
5.
6.
7. }
8. arithmeticMean(1, 2, 3, 4, 5)
9. // returns 3.0, which is the arithmetic mean of these five numbers
112
var
1. func alignRight(var string: String, count: Int, pad: Character) -> Str
ing {
2.
3.
for _ in 1...amountToPad {
4.
5.
6.
return string
7. }
8. let originalString = "hello"
9. let paddedString = alignRight(originalString, 10, "-")
10. // paddedString is equal to "-----hello"
11. // originalString is still equal to "hello"
alignRight,
"hello"
"-----hello"
113
alignRight
amountToPad amountToPad
In-Out
in-out
in-out
in out
&
in-out inout
inout var let
swapTwoInts a b in-out
1. func swapTwoInts(inout a: Int, inout b: Int) {
2.
let temporaryA = a
3.
a = b
4.
b = temporaryA
5. }
swapTwoInts ab temporaryA
b a temporaryA b
114
Int swapTwoInts
swapTwoInts someInt anotherInt
&
1. var someInt = 3
2. var anotherInt = 107
3. swapTwoInts(&someInt, &anotherInt)
4. println("someInt is now \(someInt), and anotherInt is now \(anotherInt
)")
5. // prints "someInt is now 107, and anotherInt is now 3"
In-out swapTwoInts
someInt anotherInt In-out
return a + b
3. }
4. func multiplyTwoInts(a: Int, b: Int) -> Int {
5.
return a * b
6. }
addTwoInts multiplyTwoInts
int int
115
1. func printHelloWorld() {
2.
println("hello, world")
3. }
->" void"
void swift
swift
mathFunction
1. println("Result: \(mathFunction(2, 3))")
2. // prints "Result: 5"
1. mathFunction = multiplyTwoInts
2. println("Result: \(mathFunction(2, 3))")
3. // prints "Result: 6"
, Swift
116
(Int, Int)->Int
3. }
4. printMathResult(addTwoInts, 3, 5)
5. // prints "Result: 8"
printMathResult
mathFunction(Int, Int)->Int
ab int
printMathResult addTwoInt 3 5 3 5
8
printMathResult
-- printMathResult
(->)
stepForward stepBackwardstepForward
+1 stepBackward -1
(Int) -> Int
117
return input + 1
3. }
4. func stepBackward(input: Int) -> Int {
5.
return input - 1
6. }
3. }
chooseStepFunction ,:
1. var currentValue = 3
2. let moveNearerToZero = chooseStepFunction(currentValue > 0)
3. // moveNearerToZero now refers to the stepBackward() function
currentValue
currentValue 3 currentValue > 0
chooseStepFunction stepBackward
moveNearerToZero
moveNearerToZero
1. println("Counting to zero:")
2. // Counting to zero:
3. while currentValue != 0 {
4.
println("\(currentValue)... ")
5.
currentValue = moveNearerToZero(currentValue)
6. }
7. println("zero!")
8. // 3...
9. // 2...
10. // 1...
11. // zero!
118
enclosing
function
chooseStepFunction
1. func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
2.
3.
4.
5. }
6. var currentValue = -4
7. let moveNearerToZero = chooseStepFunction(currentValue > 0)
8. // moveNearerToZero now refers to the nested stepForward() function
9. while currentValue != 0 {
10.
println("\(currentValue)... ")
11.
currentValue = moveNearerToZero(currentValue)
12. }
13. println("zero!")
14. // -4...
15. // -3...
16. // -2...
17. // -1...
18. // zero!
2.7.
Da
119
Swift C
Objective-C blocks lambdas
Swift
(capturing)
1.
2.
3.
Swift
*
* single-expression return
*
* Trailing
sort
120
sort
Swift sort
sort String
1.
2.
true false
sort
return s1 > s2
3. }
4. var reversed = sort(names, backwards)
5. // reversed is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
(a > b)
121
statements
3. }
inout
backwards
1. reversed = sort(names, { (s1: String, s2: String) -> Bool in
2.
return s1 > s2
3. })
backwards
(s1: String, s2: String) -> Bool
in
sort
( backwards )
122
Swift sort
(String, String) -> Bool String, String
Bool
(->)
1. reversed = sort(names, { s1, s2 in return s1 > s2 } )
return
return
sort Bool
(s1 > s2) Bool
return
Swift $0,$1,$2
123
in
$0 $1 String
Swift String
(>) String
Bool sort
Swift
1. reversed = sort(names, >)
Operator Functions
Trailing
trailing
Trailing ()
//
3. }
4.
5. // trailing
6.
7. someFunctionThatTakesAClosure({
8.
//
9. })
10.
124
11. // trailing
12.
13. someFunctionThatTakesAClosure() {
14.
//
15. }
trailing
()
sort
1. reversed = sort(names) { $0 > $1 }
Trailing
Swift Array map
()
map
3: "Three", 4: "Four",
3.
4. ]
5. let numbers = [16, 58, 510]
125
2.
3.
4.
5.
6.
number /= 10
7.
8.
return output
9. }
10. // strings String[]
11. // ["OneSix", "FiveEight", "FiveOneZero"]
map number
String String
(number %
10) digitNames
digitNames
( number % 10 number 16 658 8510 0)
number 10 16
158 5510 51
number /= 10 0 map
126
trailing
map
(Caputure)
Swift
makeIncrementor incrementor
incrementor runningTotal amount
makeIncrementor incrementor incrementor
amount runningTotal
1. func makeIncrementor(forIncrement amount: Int) -> () -> Int {
2.
var runningTotal = 0
3.
4.
runningTotal += amount
5.
return runningTotal
6.
7.
return incrementor
8. }
makeIncrementor runningTotal ( 0)
incrementor
127
runningTotal += amount
3.
return runningTotal
4. }
amount incrementor
incrementor
runningTotal incrementor
runningTotal
makeIncrementor incrementor
runningTotal
makeIncrementor
1. let incrementByTen = makeIncrementor(forIncrement: 10)
incrementByTen 10
incrementor
1. incrementByTen()
128
2. // 10
3. incrementByTen()
4. // 20
5. incrementByTen()
6. // 30
incrementor runningTotal
incrementBySevne runningTotal
incrementByTen
1. let incrementBySeven = makeIncrementor(forIncrement: 7)
2. incrementBySeven()
3. // 7
4. incrementByTen()
5. // 40
Swift
Strong Reference Cycles for Closures
incrementBySeven incrementByTen
//
/ incrementByTen
/
1. let alsoIncrementByTen = incrementByTen
2. alsoIncrementByTen()
129
3. // 50
2.8.
yankuangshiGithub
C C Swift
enumeration member
unionsvariants
Swift first-class
computed properties)
instance methods
initializers
protocols
Enumeration Syntax
enum
1. enum SomeEumeration {
2.
3. }
130
1. enum CompassPoint {
2.
case North
3.
case South
4.
case East
5.
case West
6. }
NorthSouthEast West
case
C Objective-C Swift
CompassPoints NorthSouthEast West
012 3 CompassPoint
1. enum Planet {
2.
3. }
Swift
CompassPoint Planet
directionToHead CompassPoint
directionToHead CompassPoint.
CompassPoint
1. directionToHead = .East
directionToHead
131
Switch
switch
1. directionToHead = .South
2. switch directionToHead {
3. case .North:
4.
5. case .South:
6.
7. case .East:
8.
9. case .West:
10.
11. }
12. // prints "Watch out for penguins
switch
.West CompassPoint
default
132
4.
println("Mostly harmless")
5. default:
6.
7. }
8. // prints "Mostly harmless
Associated Values
Planet.Earth
Swift
discriminated unions
tagged unionsvariants
UPC-A 0 9.
10
QR ISO8859-1
2,953 :
133
UPC-A QR
Swift
1. enum Barcode {
2.
3.
case QRCode(String)
4. }
productBarcode Barcode.UPCA
(8, 8590951226, 3)
134
1. productBarcode = .QRCode("ABCDEFGHIJKLMNOP")
Barcode.UPCA Barcode.QRCode
.UPCA .QRCode
switch
switch switch case
let var
1. switch productBarcode {
2. case .UPCA(let numberSystem, let identifier, let check):
3.
6. }
7. // prints "QR code with value of ABCDEFGHIJKLMNOP.
var let
1. switch productBarcode {
2. case let .UPCA(numberSystem, identifier, check):
3.
6. }
7. // prints "QR code with value of ABCDEFGHIJKLMNOP."
Raw Values
135
ASCII
1. enum ASCIIControlCharacter: Character {
2.
3.
4.
5. }
ASCIIControlCharacter Character
ASCII
ASCII
Planet planet
3. }
Planet.Venus 2
toRaw
1. let earthsOrder = Planet.Earth.toRaw()
2. // earthsOrder is 3
fromRaw 7
136
Uranus
1. let possiblePlanet = Planet.fromRaw(7)
2. // possiblePlanet is of type Planet? and equals Planet.Uranus
Int fromRaw
possiblePlanet Planet?
Planet
switch somePlanet {
4.
case .Earth:
5.
6.
println("Mostly harmless")
default:
7.
8.
9. } else {
10.
11. }
12. // prints "There isn't a planet at position 9
2.9.
JaySurplusGithub
137
Swift
Swift
Swift
138
class struct
1. class SomeClass {
2.
3. }
4. struct SomeStructure {
5.
6. }
1. struct Resolution {
2.
var width = 0
3.
var heigth = 0
4. }
5. class VideoMode {
6.
7.
8.
9.
10. }
Resolution
width height
139
0 Int
VideoMode
Resolution() VideoMode()
dot syntax,
(.)
1. println("The width of someResolution is \(someResolution.width)")
2. // "The width of someResolution is 0"
140
1. someVideoMode.resolution.width = 12880
2. println("The width of someVideoMode is now \(someVideoMode.resolution.
width)")
3. // "The width of someVideoMode is now 1280"
Objective-C Swift
someVideoMode resolution width
resolution
141
Swift
(Integer)(floating-point)(Booleans)(string)(array)
(dictionaries)
Swift
Resolution
1. let hd = Resolution(width: 1920, height: 1080)
2. var cinema = hd
hd (1920
1080 ) Resolution
cinema hd Resolution
cinema hd hd hd
cinema (width)(height)
1. cinema.width = 2048
hd width 1920
1. println("hd is still \(hd.width ) pixels wide")
2. // "hd is still 1920 pixels wide"
142
hd cinema hd (values)
cinema
cinema width 2048 hd
(width)
1. enum CompassPoint {
2.
3. }
4. var currentDirection = CompassPoint.West
5. let rememberedDirection = currentDirection
6. currentDirection = .East
7. if rememberDirection == .West {
8.
9. }
10. // "The remembered direction is still .West"
VideoMode
1. let tenEighty = VideoMode()
2. tenEighty.resolution = hd
3. tenEighty.interlaced = true
4. tenEighty.name = "1080i"
5. tenEighty.frameRate = 25.0
143
tenEighty VideoMode
(video mode) HD (1920*1080)
(hd)(interlaced),1080i 25.0
tenEighty frameRate
VideoMode 30.0
1. println("The frameRate property of tenEighty is now \(tenEighty.frameR
ate)")
2. // "The frameRate property of theEighty is now 30.0"
Swift
( === )
144
( !== )
3. }
4. //
"tenEighty and alsoTenEighty refer to the same Resolution instance.
"
(===) (==)
(class type)
(Operator Functions)
CC++ Objective-C
Swift C
(*)
Swift
145
(Collection)
Swift (Array)(Dictionary)
NSArray NSDictionary
NSArray NSDictionary
,
Swift
(actual)Swift
()
146
(keys)/(values)()
(keys)/(values)
ages ages
copiedAges ages
ages copiedAges
1. var ages = ["Peter": 23, "Wei": 35, "Anish": 65, "Katya": 19]
2. var copiedAges = ages
(keys)(String)(values)(Int) Swift
(value types)
(age value)
ages copiedAges Peter 24
ages 23
1. copiedAges["Peter"] = 24
2. println(ages["Peter"])
3. // "23"
Swift (Arrays)(Dictionary)
(Array) C
147
(Array)
(appending),(inserting),(removing)(ranged subscript)
[collection
](#assignment_and_copy_behavior_for_collection_types
(Int) a b c
1. var a = [1, 2, 3]
2. var b = a
3. var c = a
a,b,c
1. println(a[0])
2. // 1
3. println(b[0])
4. // 1
5. println(c[0])
6. // 1
a,b,c
1. a[0] = 42
2. println(a[0])
3. // 42
4. println(b[0])
5. // 42
6. println(c[0])
7. // 42
148
a Swift
a
a a bc
1. a.append(4)
2. a[0] = 777
3. println(a[0])
4. // 777
5. println(b[0])
6. // 42
7. println(c[0])
8. // 42
unshare (
unshare )
unshare
b c b unshare
b
1. b.unshare()
unshare b (a,b,c)
1. b[0] = -105
2. println(a[0])
3. // 77
4. println(b[0])
5. // -105
149
6. println(c[0])
7. // 42
1. if b === c {
2.
3. } else {
4.
5. }
6.
7. // "b and c now refer totwo independent sets of array elements."
b
1. if b[0...1] === b[0...1] {
2.
3. } else {
4.
5. }
6. // "These two subarrays share the same elements."
copy (shallow
copy),
150
names
copiedNames names copy
1. var names = ["Mohsen", "Hilary", "Justyn", "Amy", "Rich", "Graham", "V
ic"]
2. var copiedNames = names.copy
unshare copy
unshare copy
2.10.
shinyzhu
151
var let
FixedLengthRange
1. struct FixedLengthRange {
2.
3.
4. }
5. var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)
6. // 012
7. rangeOfThreeItems.firstValue = 6
8. // 678
152
struct
class
@lazy
var
DataImporter DataManager
1. class DataImporter {
2.
/*
3.
DataImporter
4.
5.
*/
6.
7.
//
8. }
9.
10. class DataManager {
11.
12.
13.
//
14. }
153
15.
16. let manager = DataManager()
17. manager.data += "Some data"
18. manager.data += "Some more data"
19. // DataImporter importer
DataManager DataImporter
DataImporter
DataManager DataManager
DataImporter DataImporter
@lazyimporter
fileName
1. println(manager.importer.fileName)
2. // DataImporter importer
3. // "data.txt
Objective-C
Swift Swift
154
getter setter
1. struct Point {
2.
3. }
4. struct Size {
5.
6. }
7. struct Rect {
8.
9.
10.
11.
get {
12.
13.
14.
15.
16.
set(newCenter) {
17.
18.
19.
20.
21. }
22. var square = Rect(origin: Point(x: 0.0, y: 0.0),
23.
Point (x, y)
Size width height
155
Rect
Rect center
Point
Rect center getter
setter
getter Point
square (5, 5)
156
setter
setter newValue
setter Rect
1. struct AlternativeRect {
2.
3.
4.
5.
get {
6.
7.
8.
9.
10.
set {
11.
12.
13.
14.
15. }
getter setter
var
let
get
1. struct Cuboid {
2.
3.
4.
157
5.
6. }
7. let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)
8. println("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)")
9. // "the volume of fourByFiveByTwo is 40.0"
Cuboid widthheight
depth volume volume
widthheight depth volumeCuboid
setter
willSet
didSet
willSet willSet
newValue
didSet
oldValue
willSet didSet
158
1. class StepCounter {
2.
3.
willSet(newTotalSteps) {
4.
5.
6.
didSet {
7.
8.
9.
10.
11.
12. }
13. let stepCounter = StepCounter()
14. stepCounter.totalSteps = 200
15. // About to set totalSteps to 200
16. // Added 200 steps
17. stepCounter.totalSteps = 360
18. // About to set totalSteps to 360
19. // Added 160 steps
20. stepCounter.totalSteps = 896
21. // About to set totalSteps to 896
22. // Added 536 steps
willSet newTotalSteps
didSet totalSteps
159
didSet
oldValue
didSet
@lazy
C
C
class
160
C Objective-C global
Swift
1. struct SomeStructure {
2.
3.
4.
// Int
5.
6. }
7. enum SomeEnumeration {
8.
9.
10.
// Int
11.
12. }
13. class SomeClass {
14.
15.
// Int
16.
17. }
161
1. println(SomeClass.computedTypeProperty)
2. // "42"
3.
4. println(SomeStructure.storedTypeProperty)
5. // "Some value."
6. SomeStructure.storedTypeProperty = "Another value."
7. println(SomeStructure.storedTypeProperty)
8. // "Another value.
0 10
0 10 9
7
162
AudioChannel
1. struct AudioChannel {
2.
3.
4.
5.
didSet {
6.
7.
//
8.
currentLevel = AudioChannel.thresholdLevel
9.
10.
11.
//
12.
AudioChannel.maxInputLevelForAllChannels = currentLevel
13.
14.
15.
16. }
AudioChannel 2 thresholdLevel
163
10
10 10
maxInputLevelForAllChannels
AudioChannel 0
AudioChannel currentLevel
0 10
currentLevel didSet
didSet currentLevel
AudioChannel leftChannel
rightChannel
1. var leftChannel = AudioChannel()
2. var rightChannel = AudioChannel()
7 maxInputLevelForAllChannels 7
1. leftChannel.currentLevel = 7
2. println(leftChannel.currentLevel)
3. // "7"
4. println(AudioChannel.maxInputLevelForAllChannels)
5. // "7"
11 currentLevel 10
maxInputLevelForAllChannels 10
164
1. rightChannel.currentLevel = 11
2. println(rightChannel.currentLevel)
3. // "10"
4. println(AudioChannel.maxInputLevelForAllChannels)
5. // "10"
2.11.
pp-progGithub
(Instance Methods)
CounterCounter
165
1. class Counter {
2.
var count = 0
3.
func increment() {
4.
count++
5.
6.
7.
count += amount
8.
9.
func reset() {
10.
count = 0
11.
12. }
Counter
increment
incrementBy(amount: Int)
reset 0
Counter count
dot syntax
1. let counter = Counter()
2. // 0
3. counter.increment()
4. // 1
5. counter.incrementBy(5)
6. // 6
7. counter.reset()
8. // 0
166
Swift ;
Objective-C
Counter incrementBy
1. class Counter {
2.
3.
4.
5.
6. }
incrementBy
method, numberOfTimes
#
1. func incrementBy(amount: Int, #numberOfTimes: Int) {
167
2.
3. }
Swift Objective-C
increment
1. func increment() {
2.
self.count++
3. }
self
selfSwift
Counter Counter count
self.count
self
self x x
168
1. struct Point {
2.
3.
4.
5.
6. }
7. let somePoint = Point(x: 4.0, y: 5.0)
8. if somePoint.isToTheRightOfX(1.0) {
9.
10. }
11. // "This point is to the right of the line where x == 1.0"
x 1.0
self Swift x x
(mutating)
self
mutating func
1. struct Point {
2.
3.
4.
x += deltaX
5.
y += deltaY
6.
7. }
8. var somePoint = Point(x: 1.0, y: 1.0)
9. somePoint.moveByX(2.0, y: 3.0)
10. println("The point is now at (\(somePoint.x), \(somePoint.y))")
11. // "The point is now at (3.0, 4.0)"
169
moveByX
mutating ,
1. struct Point {
2.
3.
4.
5.
6. }
moveByX x y
self
1. enum TriStateSwitch {
2.
3.
4.
switch self {
5.
case Off:
6.
self = Low
7.
case Low:
8.
self = High
9.
case High:
10.
self = Off
11.
12.
}
}
170
13. }
14. var ovenLight = TriStateSwitch.Low
15. ovenLight.next()
16. // ovenLight .High
17. ovenLight.next()
18. // ovenLight .Off
next
OffLowHigh
(Type Methods)
func class
func static
SomeClass
1. class SomeClass {
2.
3.
4.
5. }
6. SomeClass.someTypeMethod()
bodyself
self
171
LevelTracker
1
LevelTracker
1. struct LevelTracker {
2.
3.
4.
5.
6.
7.
8.
9.
var currentLevel = 1
10.
11.
if LevelTracker.levelIsUnlocked(level) {
12.
currentLevel = level
13.
return true
14.
} else {
15.
return false
16.
17.
}
}
18. }
LevelTracker
highestUnlockedLevel
LevelTracker highestUnlockedLevel
unlockLevel highestUnlockedLevel
levelIsUnlocked true
LevelTracker.highestUnlockedLevel
172
highestUnlockedLevel
LevelTracker currentLevel
Player LevelTracker
1. class Player {
2.
3.
4.
5.
LevelTracker.unlockLevel(level + 1)
6.
tracker.advanceToLevel(level + 1)
7.
8.
init(name: String) {
9.
playerName = name
10.
11. }
Player LevelTracker
completedLevel
advanceToLevel
LevelTracker.unlockLevel
Player
173
2.12.
siemenliuGithub
Classstructureenumeration
(Array) someArray[index]
(Dictionary) someDictionary[key]
subscript
getter setter
1. subscript(index: Int) -> Int {
2.
get {
174
// Int
3.
4.
5.
6.
set(newValue) {
//
7.
8.
9. }
newValue set
newValue set newValue
get subscript
1. subscript(index: Int) -> Int {
2.
// Int
3. }
TimesTable
n
1. struct TimesTable {
2.
3.
4.
5.
6. }
7. let threeTimesTable = TimesTable(multiplier: 3)
8. println("3 6 \(threeTimesTable[6])")
9. // "3 6 18"
TimesTable 3
multiplier
threeTimesTable[6]
threeTimesTable 18 6 3
TimesTable
threeTimesTable[someIndex]
175
collection
listsequence
Swift Dictionary
numberOfLegs
numberOfLegs Dictionary<String, Int>
2 bird
Dictionary
in-out
176
1. struct Matrix {
2.
3.
4.
5.
self.rows = rows
6.
self.columns = columns
7.
8.
9.
10.
return row >= 0 && row < rows && column >= 0 && column < colum
ns
11.
12.
13.
get {
14.
15.
16.
17.
set {
18.
19.
20.
21.
}
}
22. }
Matrix Matrix
177
grid
1. //
2. grid = [0.0, 0.0, 0.0, 0.0]
3.
4.
col0
col1
5. row0
[0.0,
0.0,
6. row1
0.0,
0.0]
1. matrix[0, 1] = 1.5
2. matrix[1, 0] = 3.2
3.2, 0.0]
return row >= 0 && row < rows && column >= 0 && column < columns
3. }
2.13.
HawsteinGithub
178
inheritmethodsproperty
subclasssuperclass
Swift
Swift subscripts
overrideSwift
property observer
stored propertycomputed property
Base class
base calss
Swift
Vehicle
numberOfWheels maxPassengers description
String
1. class Vehicle {
2.
3.
4.
5.
6.
7.
init() {
8.
numberOfWheels = 0
9.
maxPassengers = 1
10.
11. }
179
Vehicle initializer
init
1. init() {
2.
//
3. }
Vehicle
Vehicle numberOfWheels = 0
maxPassengers = 1
Vehicle
Subclassing
Subclassing
//
3. }
Bicycle Vehicle
Vehicle Bicycle
180
Bicycle Vehicle
1. class Bicycle: Vehicle {
2.
init() {
3.
super.init()
4.
numberOfWheels = 2
5.
6. }
Bicycle 2 Bicycle
Vehicle super.init() Bicycle
Vehicle
Objective-C Swift
181
init() {
3.
super.init()
4.
maxPassengers = 2
5.
6. }
Tandem
1. let tandem = Tandem()
2. println("Tandem: \(tandem.description())")
3. // Tandem: 2 wheels; up to 2 passengers
Tandem description
Overriding
instance method class method
instance propertysubscriptimplementation
overriding
override
override
override Swift
182
super
someMethod super.someMethod()
someMethod
someProperty getter setter super.someProperty
someProperty
super[someIndex]
3.
init() {
4.
super.init()
5.
maxPassengers = 5
6.
numberOfWheels = 4
7.
8.
9.
10.
11.
12. }
183
Car description
getter setter
Getters Setters
getter setter
getter setter
setter getter
getter super.someProperty
SpeedLimitedCar
184
3.
get {
4.
return super.speed
5.
6.
set {
7.
8.
9.
10. }
Property Observer
185
willSet didSet
setter
setter setter
var gear = 1
3.
4.
didSet {
5.
6.
7.
8.
9.
10.
11. }
final
@final @final var, @final func, @final class func, @final
186
subscript
final
final
2.14.
lifedim
Initializers
Objective-C Swift
deinitializer
property observers
187
init
Fahrenheit Double
temperature
1. struct Fahrenheit {
2.
3.
init() {
4.
5.
temperature = 32.0
}
6. }
7.
8. var f = Fahrenheit()
9. println("The default temperature is \(f.temperature) Fahrenheit")
10. // "The default temperature is 32.0 Fahrenheit
init temperature
32.0
Fahrenheit temperature
188
1. struct Fahrenheit {
2.
3. }
Celsius
init(fromFahrenheit:) init(fromKelvin:)
1. struct Celsius {
2.
3.
4.
5.
6.
7.
8.
9. }
10.
11. let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
12. // boilingPointOfWater.temperatureInCelsius
100.0
0.0
fromFahrenheit
fahrenheit fromKelvin
189
kelvin
temperatureInCelsius
Swift
Colorredgreen blue
0.0 1.0
Color Double
1. struct Color {
2.
3.
4.
self.red
5.
self.green = green
6.
self.blue
7.
= red
= blue
8. }
Color
190
--
--
optional type nil
SurveyQuestion response
1. class SurveyQuestion {
2.
3.
4.
init(text: String) {
5.
self.text = text
6.
7.
func ask() {
8.
9.
println(text)
}
10. }
11. let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
12. cheeseQuestion.ask()
13. // "Do you like cheese?"
14. cheeseQuestion.response = "Yes, I do like cheese.
response
String? optional String SurveyQuestion
nil
191
SurveyQuestion text
text text
1. class SurveyQuestion {
2.
3.
4.
init(text: String) {
5.
self.text = text
6.
7.
func ask() {
8.
9.
println(text)
}
10. }
11. let beetsQuestion = SurveyQuestion(text: "How about beets?")
12. beetsQuestion.ask()
13. // "How about beets?"
14. beetsQuestion.response = "I also like beets. (But not with cheese.)
Swift
ShoppingListItem
namequantity purchase state
1. class ShoppingListItem {
192
2.
3.
var quantity = 1
4.
5. }
6. var item = ShoppingListItem()
ShoppingListItem
name
name nil
ShoppingListItem ShoppingListItem()
item
Size
init(width:height:) Size
1. struct Size {
2.
3. }
4. let twoByTwo = Size(width: 2.0, height: 2.0)
193
self.init
self.init
extension
Rect
Size Point 0.0
1. struct Size {
2.
3. }
4. struct Point {
5.
6. }
3.
4.
init() {}
194
5.
6.
self.origin = origin
7.
self.size = size
8.
9.
10.
11.
12.
13.
14. }
Rect init()
{}
Rect origin size
Point(x: 0.0, y: 0.0) Size(width: 0.0, height: 0.0)
1. let basicRect = Rect()
2. // basicRect (0.0, 0.0) (0.0, 0.0)
Rect init(origin:size:)
origin size
let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0)) //
centerRect (2.5, 2.5) (3.0, 3.0)
195
init() init(origin:size:)
----
Swift
Swift
196
2
3 1
2 3
1
197
Swift
Swift Objective-C
1Objective-C 0 0 nilSwift
0 nil
198
Swift 4
self
199
self
self
200
--
--
override
201
2
-- 1
--
1. init(parameters) {
2.
statements
3. }
init convenience
1. convenience init(parameters) {
2.
statements
3. }
202
FoodRecipeIngredient ShoppingListItem
FoodFood
name String Food
1. class Food {
2.
3.
init(name: String) {
4.
self.name = name
5.
6.
convenience init() {
7.
8.
self.init(name: "[Unnamed]")
}
9. }
Food
Food name
Food
1. let namedMeat = Food(name: "Bacon")
2. // namedMeat "Bacon
203
Food RecipeIngredientRecipeIngredient
Int quantity Food name
RecipeIngredient
1. class RecipeIngredient: Food {
2.
3.
4.
self.quantity = quantity
5.
super.init(name: name)
6.
7.
8.
9.
10. }
RecipeIngredient
204
RecipeIngredient
1. let oneMysteryItem = RecipeIngredient()
2. let oneBacon = RecipeIngredient(name: "Bacon")
3. let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6)
RecipeIngredient ShoppingListItem
unpurchased
ShoppingListItem purchased false
ShoppingListItem description ShoppingListItem
3.
4.
5.
6.
return output
205
7.
8. }
ShoppingListItem purchased
ShoppingListItem
ShoppingListItem
1. var breakfastList = [
2.
ShoppingListItem(),
3.
ShoppingListItem(name: "Bacon"),
4.
5. ]
6. breakfastList[0].name = "Orange juice"
7. breakfastList[0].purchased = true
8. for item in breakfastList {
9.
println(item.description)
206
10. }
11. // 1 x orange juice ?
12. // 1 x bacon ?
13. // 6 x eggs ?
breakfastList
ShoppingListItem ShoppingListItem[]
ShoppingListItem [Unnamed] Orange juice
1. class SomeClass {
2.
3.
// someProperty
4.
// someValue SomeType
5.
return someValue
6.
}()
7. }
Swift
207
self
Checkerboard
10x10
Checkerboard boardColors 100
true false
boardColor
1. struct Checkerboard {
2.
3.
4.
5.
for i in 1...10 {
6.
for j in 1...10 {
7.
temporaryBoard.append(isBlack)
8.
isBlack = !isBlack
9.
10.
isBlack = !isBlack
208
11.
12.
return temporaryBoard
13.
}()
14.
15.
16.
17. }
Checkerboard
boardColors
temporaryBoard
boardColors
squareIsBlackAtRow
1. let board = Checkerboard()
2. println(board.squareIsBlackAtRow(0, column: 1))
3. // "true"
4. println(board.squareIsBlackAtRow(9, column: 9))
5. // "false"
2.15.
bruce0505 Github ChildhoodAndy
deinit
init
Swift Swift
ARC
209
:
1. deinit {
//
2.
3.
(
)
Bank PlayerBank Bank
10,000 Bank Bank
1. struct Bank {
2.
3.
4.
5.
coinsInBank -= numberOfCoinsToVend
6.
return numberOfCoinsToVend
7.
8.
9.
coinsInBank += coins
10.
11.
}
}
Bank coinsInBank
210
vendCoins receiveCoins
vendCoins bank
bank ( bank 0)vendCoins
numberOfCoinsToVend
vendCoins
Player player
player coinsInPurse :
1. class Player {
2.
3.
init(coins: Int) {
4.
coinsInPurse = Bank.vendCoins(coins)
5.
6.
7.
coinsInPurse += Bank.vendCoins(coins)
8.
9.
deinit {
10.
Bank.receiveCoins(coinsInPurse)
11.
12.
}
}
Player bank
Player
coins"
211
in the bank")
(playerOne!.coinsInPu
rse) coins")
3. // "PlayerOne won 2000 coins & now has 2100 coins"
4. println("The bank now only has \(Bank.coinsInBank) coins left")
5. // "The bank now only has 7900 coins left"
1. playerOne = nil
2. println("PlayerOne has left the game")
3. // "PlayerOne has left the game"
4. println("The bank now has \(Bank.coinsInBank) coins")
5. // "The bank now has 10000 coins"
2.16.
aquaporcusGithub ChildhoodAndy
212
Swift (ARC)
Swift ""
ARC
ARC
ARC
(Structure)
ARC
ARC
ARC
ARC
ARC
ARC
(strong reference)
213
ARC
ARC Person
name
1. class Person {
2.
3.
init(name: String) {
4.
self.name = name
5.
6.
7.
8.
deinit {
9.
10.
11. }
Person?
Person Person?
Person nil Person
1. var reference1: Person?
2. var reference2: Person?
3. var reference3: Person?
Person
1. reference1 = Person(name: "John Appleseed")
2. // prints "Jonh Appleseed is being initialized"
214
Person
1. reference2 = reference1
2. reference3 = reference2
Person
nil
Person
1. reference1 = nil
2. reference2 = nil
ARC Person
Person
1. referenece3 = nil
2. // John Appleseed is being deinitialized
ARC Person
215
Person Apartment
1. class Person {
2.
3.
4.
5.
6. }
7.
8. class Apartment {
9.
10.
11.
12.
13. }
Person Apartment
john number73
Apartment Person nil
1. var john: Person?
2. var number73: Apartment?
john Person
number73 Apartment :
216
!
1. john!.apartment = number73
2. number73!.tenant = john
Person Apartment
john number73
0 ARC
1. john = nil
2. nuber73 = nil
217
Person Apartment
Swift
nil
nil
ARC
weak
Apartment Apartment
Swift
ARC
218
nil
Person Apartment
Apartment tenant
1. class Person {
2.
3.
4.
5.
6. }
7.
8. class Apartment {
9.
10.
11.
12.
13. }
(john number73)
1. var john: Person?
2. var number73: Apartment?
3.
4. john = Person(name: "John Appleseed")
5. number73 = Apartment(nunber: 73)
6.
7. john!.apartment = number73
8. number73!.tenant = john
219
Person
1. john = nil
2. //
number73 Apartment
Apartment
Apartment
1. number73 = nil
2. // "Apartment #73 is being deinitialized"
220
nilARC nil
Customer CreditCard
CustomerCreditCard ApartmentPerson
customer
1. class Customer {
2.
3.
221
4.
init(name: String) {
5.
self.name = name
6.
7.
8.
9. }
10.
11. class CreditCard {
12.
13.
14.
15.
self.number = number
16.
self.customer = customer
17.
18.
19.
20. }
john Customer
nil
1. var john: Customer?
Customer CreditCard
CreditCard Customer card
1. john = Customer(name: "John Appleseed")
2. john!.card = CreditCard(number: 1234_5678_9012_3456, customer:john!)
222
1. john = nil
2. // "John Appleseed is being deinitialized"
3. // "Card #1234567890123456 is being deinitialized"
nil
223
Country City
Country
capitalCity City country
1. class Country {
2.
3.
4.
5.
self.name = name
6.
7.
8. }
9.
10. class City {
11.
12.
13.
14.
self.name = name
15.
self.country = country
16.
17. }
224
City
Country City
capitalCity
1. var country = Country(name: "Canada", capitalName: "Ottawa")
2. println("\(country.name)'s captial city is called \(country.capitalCit
y.name)")
3. // "Canada's capital city is called Ottawa"
capitalCity
self.someProperty
self.someMethod self
self
HTMLElement HTML
1. class HTMLElement {
2.
3.
225
4.
5.
6.
7.
8.
return "<\(self.name)>\(text)</\(self.name)>"
9.
} else {
10.
11.
12.
}
}
13.
14.
15.
self.name = name
16.
self.text = text
17.
18.
19.
deinit {
20.
21.
22.
23. }
asHTML asHTML
HTML
226
self lazy
HTMLElement
1. var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, wor
ld")
2. println(paragraph!.asHTML())
3. // "<p>hello, world</p>"
HTMLElement asHTML
asHTML
self HTMLElement
227
1. paragraph = nil
HTMLElementdeinitializer HTMLElement
3.
4. }
in
1. @lazy var someClosure: () -> String = {
2.
[unowned self] in
3.
4.
5. }
228
nil
nil
nil
HTMLElement
HTMLElement
1. class HTMLElement {
2.
3.
4.
5.
6.
7.
[unowned self] in
8.
9.
return "<\(self.name)>\(text)</\(self.name)>"
10.
} else {
11.
12.
13.
}
}
14.
15.
16.
self.name = name
17.
self.text = text
18.
19.
20.
deinit {
21.
22.
23.
24. }
229
HTMLElement
[unowned self] self
HTMLElement
1. var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, wor
ld")
2. println(paragraph!.asTHML())
3. // "<p>hello, world</p>"
self HTMLElement
paragraph nilHTMLElement deinitializer
1. paragraph = nil
2. // "p is being deinitialized"
2.17.
JasonbrokerGithub ChildhoodAndy
Optional Chaining
nil
nilnil
230
nil
optional value
nil
nil
Int Int
Person Residence
1. class Person {
2. var residence: Residence?
3. }
4.
5. class Residence {
6. var numberOfRooms = 1
7. }
Person residence
231
residence numberOfRooms
residence
1. let roomCount = john.residence!.numberOfRooms
2. // this triggers a runtime error
3. //
numberOfRooms
3. } else {
4.
5. }
6. // "Unable to retrieve the number of rooms.
numberOfRooms Int
Int residence Int
numberOfRooms
numberOfRooms IntInt
numberOfRooms Int Int
Residence john.residence
1. john.residence = Residence()
2. john.residence nil
numberOfRoooms 1 Int
232
3.
4. if let roomCount = john.residence?.numberOfRooms {
5. println("John's residence has \(roomCount) room(s).")
6. } else {
7.
8. }
9. // "John's residence has 1 room(s)"
Person
1. class Person {
2. var residence: Residence?
3. }
1. class Residence {
2.
3.
4.
return rooms.count
5.
6.
7.
return rooms[i]
8.
9.
func printNumberOfRooms() {
10.
11.
12.
13. }
233
rooms Residence
Residence printNumberOfRooms
Residence addressaddressAddress
rooms Room name
room
1. class Room {
2.
3.
4. }
Address String
buildingName buildingNumber
street
1. class Address {
2.
3.
4.
5.
6.
if buildingName {
7.
return buildingName
8.
} else if buildingNumber {
9.
return buildingNumber
10.
} else {
11.
return nil
12.
13.
}
}
14. }
234
numberOfRooms
1. let john = Person()
2. if let roomCount = john.residence?.numberOfRooms {
3.
4. } else {
5.
6. }
7. // "Unable to retrieve the number of rooms
john.residence
3. }
Void
Function Without Return Values
Void Void
235
optional type
if printNumberOfRooms
printNumberOfRooms Void
nil
1. if john.residence?.printNumberOfRooms() {
2.
3. } else {
4.
5. }
6. // "It was not possible to print the number of rooms."
Residence john.residence
john.residence nil
1. if let firstRoomName = john.residence?[0].name {
2.
3. } else {
4.
5. }
6. // "Unable to retrieve the first room name."
john.residence
john.residence
236
8. } else {
9.
10. }
11. // "The first room name is Living Room."
Int Int
Int Int
3. } else {
4.
5. }
6. // "Unable to retrieve the address.
street String
john.residence?.address?.street
237
String
8. } else {
9.
10. }
11. // "John's street name is Laurel Street."
! address john.residence.address
john.residence address
Address buildingIdentifier
String?
String
1. if let buildingIdentifier = john.residence?.address?.buildingIdentifie
r() {
2.
3. }
4. // "John's building identifier is The Larches."
238
3. }
4. // "John's uppercase building identifier is THE LARCHES."
buildingIdentifier buildingIdentifier
2.18.
xiehurricaneGithub ChildhoodAndy
Swift is as
Protocols
array
MediaItem
String name init name
239
1. class MediaItem {
2.
3.
init(name: String) {
4.
self.name = name
5.
6. }
MediaItem Movie
director
artist
1. class Movie: MediaItem {
2.
3.
4.
self.director = director
5.
super.init(name: name)
6.
7. }
8.
9. class Song: MediaItem {
10.
11.
12.
self.artist = artist
13.
super.init(name: name)
14.
15. }
240
7. ]
8. // the type of "library" is inferred to be MediaItem[]
(is) true
false
if item is Movie {
6.
++movieCount
7.
8.
++songCount
9.
10. }
11.
12. println("Media library contains \(movieCount) movies and \(songCount)
songs")
13. // prints "Media library contains 2 movies and 3 songs"
241
(as)
optional form
as? optional value as
force-unwraps
(as?)
optional value nil
runtime error
3.
4.
5.
6.
7. }
8.
9. // Movie: 'Casablanca', dir. Michael Curtiz
10. // Song: 'Blue Suede Shoes', by Elvis Presley
11. // Movie: 'Citizen Kane', dir. Orson Welles
12. // Song: 'The One And Only', by Chesney Hawkes
242
Song Movie
optional binding optional Movie
if let movie = item as? Movie,
item Movie movie
optional Movie
movie Movie
director Song Song
Any AnyObject
Swift
1. AnyObject class
2. Any function types
Any AnyObject
AnyObject
Cocoa APIs AnyObject[]
OC
API
243
(as)
AnyObject optional unwrapping
AnyObject[] Movie
1. let someObjects: AnyObject[] = [
2.
3.
4.
5. ]
3.
4. }
5. // Movie: '2001: A Space Odyssey', dir. Stanley Kubrick
6. // Movie: 'Moon', dir. Duncan Jones
7. // Movie: 'Alien', dir. Ridley Scott
someObjects Movie[]
1. for movie in someObjects as Movie[] {
2.
3. }
4. // Movie: '2001: A Space Odyssey', dir. Stanley Kubrick
5. // Movie: 'Moon', dir. Duncan Jones
6. // Movie: 'Alien', dir. Ridley Scott
Any
Any class
Any things
1. var things = Any[]()
2. things.append(0)
3. things.append(0.0)
244
4. things.append(42)
5. things.append(3.14159)
6. things.append("hello")
7. things.append((3.0, 5.0))
8. things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman"))
things Int
2 Double
1 String (Double, Double)
Ivan Reitman Ghostbusters
switch thing {
3.
case 0 as Int:
4.
println("zero as an Int")
5.
case 0 as Double:
6.
println("zero as a Double")
7.
8.
9.
10.
11.
case is Double:
12.
13.
14.
15.
16.
17.
18.
19.
default:
20.
21.
println("something else")
}
22. }
23. // zero as an Int
24. // zero as a Double
245
2.19
LIN-HGithub
Swift
{}
BlackjackCard BlackjackCard(
)BlackjackCard 2 Suit
Rank
// Suit
4.
5.
246
6.
7.
8.
// Rank
9.
10.
case Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten
11.
12.
struct Values {
13.
14.
15.
16.
17.
switch self {
18.
case .Ace:
19.
20.
21.
22.
default:
23.
24.
25.
26.
}
}
27.
28.
// BlackjackCard
29.
30.
31.
32.
33.
34.
35.
36.
return output
37.
38. }
Suit Character
247
Rank Values
Ace Values
first, Int
second, Int?, optional Int
Rank values
Values values J,Q,K,Ace
Int
initializer theAceOfSpades:
1. let theAceOfSpades = BlackjackCard(rank: .Ace, suit: .Spades)
2. println("theAceOfSpades: \(theAceOfSpades.description)")
3. // "theAceOfSpades: suit is , value is 1 or 11"
248
2.20
lyukaGithub
functionality
Objective-C
categories Objective-C Swift
Swift
1.
2.
3.
4.
5.
6.
Extension Syntax
extension
1. extension SomeType {
2.
// SomeType
3. }
protocol
249
//
3. }
protocol conformance
Computed Properties
Swift
Double 5
1. extension Double {
2.
3.
4.
5.
6.
7. }
8. let oneInch = 25.4.mm
9. println("One inch is \(oneInch) meters")
10. // "One inch is 0.0254 meters"
11. let threeFeet = 3.ft
12. println("Three feet is \(threeFeet) meters")
13. // "Three feet is 0.914399970739201 meters"
Double
dot
Double 1.0 1 m
self 1.m 1.0 Double
1 1,000 km
1_000.00 1 3.28024 ft
Double 3.28024
250
get
Double Double
1. let aMarathon = 42.km + 195.m
2. println("A marathon is \(aMarathon) meters long")
3. // "A marathon is 42495.0 meters long"
(property observers)
Initializers
custom initializers
(default initializers) (memberwise
initializers)
Rect
Size Point 0.0
1. struct Size {
2.
3. }
4. struct Point {
5.
6. }
7. struct Rect {
8.
9.
10. }
Rect
Rect
251
Rect
1. extension Rect {
2.
3.
4.
5.
6.
7. }
center size
init(origin:size:)
1. let centerRect = Rect(center: Point(x: 4.0, y: 4.0),
2.
Methods
Int
repetitions
1. extension Int {
2.
3.
for i in 0..self {
4.
task()
5.
6.
}
}
7. }
252
repetitions ,
1. 3.repetitions({
2.
println("Hello!")
3.
})
4. // Hello!
5. // Hello!
6. // Hello!
trailing
1. 3.repetitions{
2.
println("Goodbye!")
3. }
4. // Goodbye!
5. // Goodbye!
6. // Goodbye!
1. extension Int {
2.
3.
4.
5. }
6. var someInt = 3
7. someInt.square()
8. // someInt 9
253
Subscripts
Swift Int
[n] n
1. 123456789[0] 9
2. 123456789[1] 8
...
1. extension Int {
2.
3.
var decimalBase = 1
4.
for _ in 1...digitIndex {
5.
decimalBase *= 10
6.
7.
8.
9. }
10. 746381295[0]
11. // returns 5
12. 746381295[1]
13. // returns 9
14. 746381295[2]
15. // returns 2
16. 746381295[8]
17. // returns 7
Int 0
0
1. 746381295[9]
2. //returns 0,
1. 0746381295[9]
254
Nested Types
1. extension Character {
2.
enum Kind {
3.
4.
5.
6.
switch String(self).lowercaseString {
7.
8.
return .Vowel
9.
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
10.
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
11.
return .Consonant
12.
default:
13.
return .Other
14.
15.
16. }
Character Kind
Character
1. func printLetterKinds(word: String) {
2.
3.
4.
switch character.kind {
5.
case .Vowel:
6.
7.
print("vowel ")
case .Consonant:
255
8.
print("consonant ")
9.
case .Other:
10.
print("other ")
11.
12.
13.
print("\n")
14. }
15. printLetterKinds("Hello")
16. // 'Hello' is made up of the following kinds of letters:
17. // consonant vowel consonant consonant vowel
printLetterKinds String
kind printLetterKinds
"hello"
2.21
geek5nanGithub
Protocol()
1. protocol SomeProtocol {
2.
//
3. }
256
:
,
1. struct SomeStructure: FirstProtocol, AnotherProtocol {
2.
//
3. }
//
3. }
(instance property)
(type property)()settable ()gettable
(stored property)(calculate property)
3.
4. }
class
static
1. protocol AnotherProtocol {
2.
3. }
4.
5. protocol FullyNamed {
6.
7. }
257
3. }
4. let john = Person(fullName: "John Appleseed")
5. //john.fullName "John Appleseed"
Person fullName (
)
Startship FullyNamed
1. class Starship: FullyNamed {
2.
3.
4.
5.
self.anme = name
6.
self.prefix = prefix
7.
8.
9.
10.
11. }
12. var ncc1701 = Starship(name: "Enterprise", prefix: "USS")
13. // ncc1701.fullName == "USS Enterprise"
258
class
static
1. protocol SomeProtocol {
2.
3. }
4.
5. protocol RandomNumberGenerator {
6.
7. }
RandomNumberGenerator random
Double ([01])
LinearCongruentialGenerator RandomNumberGenerator
(linear congruential generator)
1. class LinearCongruentialGenerator: RandomNumberGenerator {
2.
3.
let m = 139968.0
4.
let a = 3877.0
5.
let c = 29573.0
6.
7.
lastRandom = ((lastRandom * a + c) % m)
8.
return lastRandom / m
9.
10. }
11. let generator = LinearCongruentialGenerator()
12. println("Here's a random number: \(generator.random())")
13. // : "Here's a random number: 0.37464991998171"
14. println("And another one: \(generator.random())")
15. // : "And another one: 0.729023776863283"
(Value Type)(
259
) mutating
(Instance Methods)
((Reference Type)
(Value Type)
Swift mutating
)
3. }
case Off, On
3.
4.
switch self {
5.
case Off:
6.
self = On
7.
case On:
8.
self = Off
9.
10.
}
}
11. }
12. var lightSwitch = OnOffSwitch.Off
13. lightSwitch.toggle()
14. //lightSwitch .On
260
1.
2.
3.
(IntDoubleString)
1. class Dice {
2.
3.
4.
5.
self.sides = sides
6.
self.generator = generator
7.
8.
9.
10.
11. }
Dice N
RandomNumberGenerator
261
LinearCongruentialGenerator Dice
1. var d6 = Dice(sides: 6,generator: LinearCongruentialGenerator())
2. for _ in 1...5 {
3.
4. }
5. //
6. //Random dice roll is 3
7. //Random dice roll is 5
8. //Random dice roll is 4
9. //Random dice roll is 5
10. //Random dice roll is 4
()
()
1. protocol DiceGame {
2.
3.
func play()
4. }
5. protocol DiceGameDelegate {
6.
7.
8.
9. }
262
DiceGame DiceGameDelegate
DiceGame
let finalSquare = 25
3.
4.
var square = 0
5.
6.
init() {
7.
8.
9.
10.
11.
12.
func play() {
13.
square = 0
14.
delegate?.gameDidStart(self)
15.
16.
17.
delegate?.game(self,didStartNewTurnWithDiceRoll: diceRoll)
18.
19.
case finalSquare:
20.
break gameLoop
21.
22.
continue gameLoop
23.
default:
24.
square += diceRoll
25.
square += board[square]
26.
27.
28.
delegate?.gameDIdEnd(self)
263
29.
30. }
DicegameDelegate
play()
DiceGameTracker DiceGameDelegate
1. class DiceGameTracker: DiceGameDelegate {
2.
var numberOfTurns = 0
3.
4.
numberOfTurns = 0
5.
if game is SnakesAndLadders {
6.
7.
8.
9.
10.
11.
++numberOfTurns
12.
println("Rolled a \(diceRoll)")
13.
14.
15.
16.
17. }
DiceGameTracker DiceGameDelegate
264
numberOfTurns 0
DiceGameTracker
1. let tracker = DiceGameTracker()
2. let game = SnakesAndLadders()
3. game.delegate = tracker
4. game.play()
5. // Started a new game of Snakes and Ladders
6. // The game is using a 6-sided dice
7. // Rolled a 3
8. // Rolled a 5
9. // Rolled a 4
10. // Rolled a 5
11. // The game lasted for 4 turns
(Extension)(
)
TextRepresentable asText
1. protocol TextRepresentable {
2.
3. }
Dice TextRepresentable
265
3.
4.
5. }
Dice TextRepresentable
1. let d12 = Dice(sides: 12,generator: LinearCongruentialGenerator())
2. println(d12.asText())
3. // "A 12sided dice"let d12 = Dice(sides: 12,generator: LinearCongruentialGener
ator())
4. println(d12.asText())
5. // "A 12sided dice"let d12 = Dice(sides: 12,generator: LinearCongruentialGener
ator())
6. println(d12.asText())
7. // "A 12-sided dice"
SnakesAndLadders
1. extension SnakeAndLadders: TextRepresentable {
2.
3.
4.
5. }
6. println(game.asText())
7. // "A game of Snakes and Ladders with 25 squares"
1. struct Hamster {
2.
3.
4.
266
5.
6. }
7. extension Hamster: TextRepresentabl {}
Hamster TextRepresentable
1. let simonTheHamster = Hamster(name: "Simon")
2. let somethingTextRepresentable: TextRepresentabl = simonTheHamester
3. println(somethingTextRepresentable.asText())
4. // "A hamster named Simon"
things asText()
1. for thing in things {
2.
println(thing.asText())
3. }
4. // A game of Snakes and Ladders with 25 squares
5. // A 12-sided dice
6. // A hamster named Simon
,
1. protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
2.
//
267
3. }
4. PrettyTextRepresentable TextRepresentable
5.
6. protocol PrettyTextRepresentable: TextRepresentable {
7.
8. }
PrettyTextRepresentable TextRepresentable`
SnakesAndLadders PrettyTextRepresentable
1. extension SnakesAndLadders: PrettyTextRepresentable {
2.
3.
4.
5.
switch board[index] {
6.
7.
8.
9.
10.
default:
11.
12.
13.
14.
return output
15.
16. }
for in board
0
0
0
SankesAndLadders asPrettyText()
1. println(game.asPrettyText())
2. // A game of Snakes and Ladders with 25 squares:
3. //
268
protocol<SomeProtocol, AnotherProtocol>
(protocol composition)
1. protocol Named {
2.
3. }
4. protocol Aged {
5.
6. }
7. struct Person: Named, Aged {
8.
9.
10. }
11. func wishHappyBirthday(celebrator: protocol<Named, Aged>) {
12.
13. }
14. let birthdayPerson = Person(name: "Malcolm", age: 21)
15. wishHappyBirthday(birthdayPerson)
16. // "Happy birthday Malcolm - you're 21!
269
is as (downcast)
()
1. is
2. as? nil
3. as
1. @objc protocol HasArea {
2.
3. }
@objc Objective-C
@objc Using Siwft
with Cocoa and Objectivei-C
1. class Circle: HasArea {
2.
let pi = 3.1415927
3.
4.
var area:radius }
5.
6. }
7. class Country: HasArea {
8.
9.
10. }
Animal
1. class Animal {
2.
3.
4. }
270
Circle,Country,Animal AnyObject
Circle(radius: 2.0),
3.
Country(area: 243_610),
4.
Animal(legs: 4)
5. ]
object HasArea
1. for object in objects {
2.
3.
4.
println("Area is \(objectWithArea.area)")
} else {
5.
6.
7. }
8. // Area is 12.5663708
9. // Area is 243610.0
10. // Something that doesn't have an area
objects objectWithArea
HasArea area
@optional
someOptionalMethod?(someArgument)?
(optional value)
271
? nil
@objc @objc
3.
4. }
CounterDataSource
var count = 0
3.
4.
func increment() {
5.
6.
count += amount
7.
8.
count += amount
9.
10.
}
}
11. }
increment count
272
dataSource incrementForCount
incrementForCount ?
incrementForCount Int (optional binding)
amount
incrementForCount fixedIncrement
ThreeSource CounterDataSource
1. class ThreeSource: CounterDataSource {
2.
let fixedIncrement = 3
3. }
ThreeSource Counter
1. var counter = Counter()
2. counter.dataSource = ThreeSource()
3. for _ in 1...4 {
4.
counter.increment()
5.
println(counter.count)
6. }
7. // 3
8. // 6
9. // 9
10. // 12
if count == 0 {
4.
return 0
5.
6.
return 1
7.
} else {
8.
return -1
9.
10.
}
}
273
11. }
1. counter.count = -4
2. counter.dataSource = TowardsZeroSource()
3. for _ in 1...5 {
4.
counter.increment()
5.
println(counter.count)
6. }
7. // -3
8. // -2
9. // -1
10. // 0
11. // 0
2.22
takalard
Swift Swift
Swift
Int String
Swift
dictionary
swapTwoInts, Int
1. func swapTwoInts(inout a: Int, inout b: Int)
2.
let temporaryA = a
3.
a = b
274
4.
b = temporaryA
5. }
in-out a b
swapTwoInts b a a b
Int
1. var someInt = 3
2. var anotherInt = 107
3. swapTwoInts(&someInt, &anotherInt)
4. println("someInt is now \(someInt), and anotherInt is now \(anotherInt
)")
5. // "someInt is now 107, and anotherInt is now 3"
let temporaryA = a
3.
a = b
4.
b = temporaryA
5. }
6.
7. func swapTwoDoubles(inout a: Double, inout b: Double) {
8.
let temporaryA = a
9.
a = b
10.
b = temporaryA
11. }
275
a b a b
Swift String
Double Swift
swapTwoInts
let temporaryA = a
3.
a = b
4.
b = temporaryA
5. }
swapTwoValues swapTwoInts
swapTwoInts
1. func swapTwoInts(inout a: Int, inout b: Int)
2. func swapTwoValues<T>(inout a: T, inout b: T)
T
InString Doubl T
a b T T swapTwoValues
T
T
Swift T swapTwoValues
T Swift T
swapTwoValues
swapTwoInts swapTwoValues T
,T Int String
276
1. var someInt = 3
2. var anotherInt = 107
3. swapTwoValues(&someInt, &anotherInt)
4. // someInt is now 107, and anotherInt is now 3
5.
6. var someString = "hello"
7. var anotherString = "world"
8. swapTwoValues(&someString, &anotherString)
9. // someString is now "world", and anotherString is now "hello"
swapTwoValues T
swapTwoValues a b
swapTwoValues T Int
String
swapTwoValues
T
Swift Dictionary
277
KeyType ValueType
T KeyType
Swift
Array Dictionary
--Stack
Array Swift Array
/ push
pop
UINavigationController
UINavigationController pushViewController:animated:
add popViewControllerAnimated:
pop
(push)/(pop)
1
2pushed
3
278
4popped
5
Int
1. struct IntStack {
2.
3.
4.
items.append(item)
5.
6.
7.
8.
return items.removeLast()
}
9. }
1. struct Stack<T> {
2.
3.
4.
items.append(item)
5.
6.
7.
8.
return items.removeLast()
}
9. }
Stack T
Int <T>
279
T T
TT
- items T
- item push T
- pop T
Stack Array Dictionary
1. var stackOfStrings = Stack<String>()
2. stackOfStrings.push("uno")
3. stackOfStrings.push("dos")
4. stackOfStrings.push("tres")
5. stackOfStrings.push("cuatro")
6. // 4 string
stackOfStrings push
pop "cuatro"
1. let fromTheTop = stackOfStrings.pop()
2. // fromTheTop is equal to "cuatro", and the stack now contains 3 strin
gs
pop
280
Stack Swift
Array Dictionary
swapTwoValues Stack
Swift Dictionary
Dictionary
Dictionary
Dictionary
Hashable Swift Swift
StringInt Double Bool
281
3. }
T T SomeClass
U U SomeProtocol
findStringIndex String
findStringIndex
Int nil
1. func findStringIndex(array: String[], valueToFind: String) -> Int? {
2.
3.
if value == valueToFind {
4.
return index
5.
6.
7.
return nil
8. }
findStringIndex :
1. let strings = ["cat", "dog", "llama", "parakeet", "terrapin"]
2. if let foundIndex = findStringIndex(strings, "llama") {
3.
4. }
5. // "The index of llama is 2"
282
findIndex T
findStringIndex findIndex
Int?
3.
if value == valueToFind {
4.
return index
5.
6.
7.
return nil
8. }
if value == valueToFind
Swift ==
Swift
T
Swift Equatable
==!=
Swift Equatable
Equatable findIndex
Equatable
4.
5.
return index
}
283
6.
7.
return nil
8. }
findIndex T: Equatable T
Equatable
findIndex Equatable
Double String:
1. let doubleIndex = findIndex([3.14159, 0.1, 0.25], 9.3)
2. // doubleIndex is an optional Int with no value, because 9.3 is not in
the array
3. let stringIndex = findIndex(["Mike", "Malcolm", "Andrea"], "Andrea")
4. // stringIndex is an optional Int containing a value of 2
typealias
Container ItemType
1. protocol Container {
2.
typealias ItemType
3.
4.
5.
6. }
Container
284
append item
count items Int
Int item
item
Container
Container
items item
Container
Container append
IntStack Container
1. struct IntStack: Container {
2.
3.
4.
5.
items.append(item)
6.
7.
8.
return items.removeLast()
9.
10.
285
11.
12.
13.
self.push(item)
14.
15.
16.
return items.count
17.
18.
19.
20.
return items[i]
}
21. }
Container Stack
1. struct Stack<T>: Container {
2.
3.
4.
5.
items.append(item)
6.
7.
8.
return items.removeLast()
9.
10.
11.
286
12.
self.push(item)
13.
14.
15.
return items.count
16.
17.
18.
19.
return items[i]
}
20. }
Where
where
where
where
287
where
allItemsMatch Container
true Boolean
where
1. func allItemsMatch<
2.
3.
4.
5.
6.
7.
if someContainer.count != anotherContainer.count {
8.
9.
return false
}
10.
11.
12.
for i in 0..someContainer.count {
13.
if someContainer[i] != anotherContainer[i] {
14.
return false
15.
16.
}
}
17.
18.
19.
return true
20.
21. }
someContainer anotherContainersomeContainer
C1anotherContainer C2C1 C2
288
where where
someContainer C1 anotherContainer C2
someContainer anotherContainer someContainer
(!=)
anotherContainer !=
someContainer
allItemsMatch
allItemsMatch items
false
for-in .. someContainer
someContainer
anotherContainer false
true
allItemsMatch
1. var stackOfStrings = Stack<String>()
2. stackOfStrings.push("uno")
3. stackOfStrings.push("dos")
4. stackOfStrings.push("tres")
289
5.
6. var arrayOfStrings = ["uno", "dos", "tres"]
7.
8. if allItemsMatch(stackOfStrings, arrayOfStrings) {
9.
10. } else {
11.
12. }
13. // "All items match."
Stack String
Array
Container
allItemsMatch allItemsMatch
items
2.23
xielingwangGithub
Swift C
Objective-C
C Swift
Swift
&+&
Swift
290
Swift C
// 0b11110000
UInt8 8 0~255
00001111( 4 0 4 1) 15
~ initialBits invertedBits
initialBits 1 00 1 11110000
240
1 1
291
firstSixBits lastSixBits 4 1
00111100 60
1. let firstSixBits: UInt8 = 0b11111100
2. let lastSixBits: UInt8
= 0b00111111
// 00111100
| 1
0( 1 1)
// 11111110
292
^ 1
0
firstBits otherBits 1
1 0
1. let firstBits: UInt8 = 0b00010100
2. let otherBits: UInt8 = 0b00000101
3. let outputBits = firstBits ^ otherBits
// 00010001
/
<<>>
2
2 2
293
// 00000100
2. shiftBits << 1
// 00001000
3. shiftBits << 2
// 00010000
4. shiftBits << 5
// 10000000
5. shiftBits << 6
// 00000000
6. shiftBits >> 2
// 00000001
// redComponent 0xCC,
204
3. let greenComponent = (pink & 0x00FF00) >> 8
// greenComponent 0x6
6, 102
4. let blueComponent = pink & 0x0000FF
// blueComponent 0x99
, 153
16 >> 16 8 16
0xCC0000 0x0000CC 0xCC 204
294
(
8 )
1 ()0 1
()
+4
0 7 4
2 n n
8 7 2 7 128
-4
17 124 128 - 4
295
8 () -1 + -4
8
1 2 1 2
( 0 1)
0
0
Swift
296
Swfit
5 &
&+
& &*
&/
&%
&+
1. var willOverflow = UInt8.max
2. // willOverflow UInt8 255
3. willOverflow = willOverflow &+ 1
4. // willOverflow 0
297
UInt8 0( 00000000)&- 1
11111111 255
Swift :
1. var willUnderflow = UInt8.min
2. // willUnderflow UInt8 0
3. willUnderflow = willUnderflow &- 1
4. // willUnderflow 255
"/" -128
10000000 1 01111111 UInt8
127
Swift
1. var signedUnderflow = Int8.min
2. // signedUnderflow -128
3. signedUnderflow = signedUnderflow &- 1
4. // signedUnderflow 127
298
0 i / 0 0 i % 0
1. let x = 1
2. let y = x / 0
&/&% 0 0
1. let x = 1
2. let y = x &/ 0
3. // y 0
4
1. 2 + 3 * 4 % 5
2. // 4
2 plus 3 equals 5;
2 +3= 5
5 times 4 equals 20;
5 * 4 = 20
20 remainder 5 equals 0
20 / 5 = 4 0
299
4 0 Swift C
1. 2 + ((3 * 4) % 5)
Swift
Swift C Objective-C C
Swift
++
Vector2D (xy)
Vector2D
1. struct Vector2D {
2.
300
3. }
4. @infix func + (left: Vector2D, right: Vector2D) -> Vector2D {
5.
6. }
+ Vector2D
Vector2D func
@infix
Vector2D Vector2D
301
-a;
i++
func @prefix
@postfix
1. @prefix func - (vector: Vector2D) -> Vector2D {
2.
3. }
Vector2D -a@prefix
Vector2D
x y
1. let positive = Vector2D(x: 3.0, y: 4.0)
2. let negative = -positive
3. // negative (-3.0, -4.0)
4. let alsoPositive = -negative
5. // alsoPositive (3.0, 4.0)
+=
@assignment
inout
1. @assignment func += (inout left: Vector2D, right: Vector2D) {
2.
3. }
302
3.
return vector
4. }
(1.01.0)
abc
Swift
==!=
3. }
4.
5. @infix func != (left: Vector2D, right: Vector2D) -> Bool {
6.
7. }
303
== Vector2D
x y ==
!=
Vector2D
1. let twoThree = Vector2D(x: 2.0, y: 3.0)
2. let anotherTwoThree = Vector2D(x: 2.0, y: 3.0)
3. if twoThree == anotherTwoThree {
4.
println(".")
5. }
6. // prints "."
/ = - + * % < >& | ^~
operator
1. operator prefix +++ {}
+++ Swift
+++ Vector2D
vector += vector
3.
return vector
4. }
Vector2D +++ ++ , ,
(1.0, 1.0) .
1. var toBeDoubled = Vector2D(x: 1.0, y: 4.0)
2. let afterDoubling = +++toBeDoubled
3. // toBeDoubled (2.0, 8.0)
304
+- left 140
1. operator infix +- { associativity left precedence 140 }
2. func +- (left: Vector2D, right: Vector2D) -> Vector2D {
3.
4. }
5. let firstVector = Vector2D(x: 1.0, y: 2.0)
6. let secondVector = Vector2D(x: 3.0, y: 4.0)
7. let plusMinusVector = firstVector +- secondVector
8. // plusMinusVector (4.0, -2.0)
x y
(left 140) Swift
;
3
3.1
ChildhoodAndy
305
Swift
Swift Swift
Swift Swift
Swift
1.
2.
3.
4.|
5.
6. opt
getter-setter
GRAMMAR OF A GETTER-SETTER BLOCK
getter-setter-block {- getter-clause -setter-clause-opt -}- | {- setter-clause -getter-clause-} getter-setter ?? getter setter
setter getter
306
3.2
superkamgit
Swift lexical structure
Swift
longest matchmaximal munch
whitespace
space
U+0020
line feed
U+000Acarriage return
U+000D tabhorizontal
tabU+0009 tabvertical tabU+000Bform feedU+000C
nullU+0000
comments //
/* */
identifiers A Z _
Basic Multilingual Plane Unicode
Private Use Area Unicode
307
closure $0$1$2...
identifier identifier-headidentifier-charactersopt
identifier ` identifier-headidentifier-charactersopt`
identifier implicit-parameter-name
identifier-list identifier identifier, identifier-list
identifier-head Upper- or lowercase letter A through Z
identifier-head U+00A8, U+00AA, U+00AD, U+00AF, U+00B2U+00B5,
or U+00B7
U+00BA
identifier-head U+00BCU+00BE,
U+00C0U+00D6,
U+00D8U+00F6,
or
U+00F8
U+00FF
identifier-head U+0100U+02FF, U+0370U+167F, U+1681U+180D, or U+180FU+1DB F
identifier-head U+1E00U+1FFF
identifier-head U+200BU+200D,
U+202AU+202E,
U+203FU+2040,
U+2054,
or
U+2060U+206F
identifier-head U+2070U+20CF, U+2100U+218F, U+2460U+24FF, or U+2776U+2793
identifier-head U+2C00U+2DFF or U+2E80U+2FFF
identifier-head U+3004U+3007, U+3021U+302F, U+3031U+303F, or U+3040U+D7FF
identifier-head U+F900U+FD3D,
U+FD40U+FDCF,
U+FDF0U+FE1F,
or U+FE30
U+FE44
identifier-head U+FE47U+FFFD
identifier-head U+10000U+1FFFD,
U+20000U+2FFFD,
U+30000U+3FFFD,
or
U+60000U+6FFFD,
U+70000U+7FFFD,
or
U+A0000U+AFFFD,
U+B0000U+BFFFD,
or
U+40000U+4FFFD
identifier-head U+50000U+5FFFD,
U+80000U+8FFFD
identifier-head U+90000U+9FFFD,
U+C0000U+CFFFD
identifier-head U+D0000U+DFFFD or U+E0000U+EFFFD
identifier-character Digit 0 through 9
identifier-character U+0300U+036F, U+1DC0U+1DFF, U+20D0U+20FF, or U+FE20
U+FE2F
identifier-character identifier-head
identifier-characters identifier-characteridentifier-charactersopt
implicit-parameter-name $decimal-digits
308
keywords
1. classdeinitenumextensionfuncimportinitletprotocol
staticstructsubscripttypealiasvar
2. breakcasecontinuedefaultdoelsefallthroughifin
forreturnswitchwherewhile
3. asdynamicTypeisnewsuperselfSelfType
__COLUMN____FILE____FUNCTION____LINE__
4. associativitydidSetgetinfixinoutleftmutating
nonenonmutatingoperatoroverridepostfixprecedenceprefixrightsetunowned
unowned(safe)unowned(unsafe)weakwillSet
1. 42
//
2. 3.14159
//
3. "Hello, world!"
//
integer literals
0b 0o
0x
0 9 0 1 0
7 0 9 A F
309
- -42
_
0
1. 1000_000
// 1000000
2. 005
// 5
Swift IntSwift
integer-literal binary-literal
integer-literal octal-literal
integer-literal decimal-literal
integer-literal hexadecimal-literal
binary-literal 0b binary-digitbinary-literal-charactersopt
binary-digit Digit 0 or 1
binary-literal-character binary-digit
binary-literal-characters binary-literal-characterbinary-literal-charactersopt
octal-literal 0o octal-digitoctal-literal-characters opt
octal-digit Digit 0 through 7
octal-literal-character octal-digit
octal-literal-characters octal-literal-characteroctal-literal-charactersopt
decimal-literal decimal-digitdecimal-literal-charactersopt
decimal-digit Digit 0 through 9
decimal-digits decimal-digitdecimal-digitsopt
decimal-literal-character decimal-digit
decimal-literal-characters decimal-literal-characterdecimal-literal-charactersopt
hexadecimal-literal 0x hexadecimal-digithexadecimal-literal-charactersopt
hexadecimal-digit Digit 0 through 9, a through f, or A through F
hexadecimal-literal-character hexadecimal-digit
hexadecimal-literal-characters hexadecimal-literal-characterhexadecimal-literal-charactersopt
floating-point literals
310
0x
p p
2 0xFp2 15 ? 2^2 600xFp-2 15 ? 2^2 3.75
- 42.0
_
0
1. 10_000.56
// 10000.56
2. 005000.76
// 5000.76
Swift Double 64
Swift Float 32
floating-point-literal decimal-literaldecimal-fractionoptdecimal-exponentopt
floating-point-literal hexadecimal-literalhexadecimal-fractionopthexadecimal-exponent
decimal-fraction . decimal-literal
decimal-exponent floating-point-esignoptdecimal-literal
hexadecimal-fraction . hexadecimal-literal opt
hexadecimal-exponent floating-point-psignopthexadecimal-literal
floating-point-e e E
floating-point-p p P
sign + -
311
string literal
1. "characters"
"\carriage return
line feed
1.Null Character\0
2.Backslash\\
3. Tab Horizontal Tab\t
4.Line Feed\n
5.Carriage Return\r
6.Double Quote\"
7.Single Quote\'
1.\x
2.\u
3.\U
Unicode
\() interpolated
expression " \
String
1. "1 2 3"
2. "1 2 \(3)"
3. "1 2 \(1 + 2)"
4. var x = 3; "1 2 \(x)"
312
Swift
/=-+!*%<>&|^~.
=, ->///**/. &
prefix operator
postfix operatorbinary operator
1.a+b a + b
+
2. a ++b ++
3. a++ b ++
313
4. . a++.b ++
a++ . b ++ a ++ .b ++
.
([ { )] } ,; :
! ?
? optional type
? :
< >
Dictionary<String, Array<Int>>
> >
>>
operator operator-characteroperatoropt
operator-character / = - + ! * % < > & | ^ ~ .
binary-operator operator
prefix-operator operator
postfix-operator operator
3.3
lyukagit numbbbbbgit
314
Swift
MyClass
MyClassSwift
Data types
Swift
Swift Swift
type attributes
315
type-annotation
:attributes opttype
Int
Int Dictionary<String, Int> Dictionary<String,
Int>
/
Point (Int,
Int)
1. typealias Point = (Int, Int)
2. let origin: Point = (0, 0)
dot(.)modules
ExampleModule
MyType
1. var someValue: ExampleModule.MyType
type-name identifier
316
void ()
(Int) Int (Int)
tuple-type ( tuple-type-bodyopt)
tuple-type-body tuple-type-element-list... opt
tuple-type-element-li st tuple-type-element tuple-type-element, tuple-type-element-list
tuple-type-element attributes optinout opttype inout optelement-nametype-annotation
element-name identifier
->
1. parameter type -> return type
() auto_closure
auto_closure assert
1. func simpleAssert(condition: @auto_closure () -> Bool, message: String
){
2.
if !condition(){
3.
4.
println(message)
}
5. }
6. let testNumber = 5
317
... Int...
Int... Int[]
in-out inout
inout In-Out In-Out
curried function
addTwoNumber()() Int -> Int -> Int
1. func addTwoNumbers(a: Int)(b: Int) -> Int{
2.
return a + b
3. }
4. addTwoNumbers(4)(5)
// returns 9
3.
return a + b
4.
5.
return addTheSecondNumber
6. }
7. addTwoNumbers(4)(5)
// Returns 9
318
Swift [] Array<T>
someArray []
someArray[0] 0 Alex
[][]
[][]
1. var array3D: Int[][][] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
Swift ? Optional<T>
319
optionalInteger ?
Optional<T>None Some(T)
?
(Int[])? Int[]?
nil
LogicValue T?
T Optional.Some(T)
true false
1. optionalInteger = 42
2. optionalInteger!
// 42
nil
optional-type type?
Swift ! ImplicitlyUnwrappedOptional<T>
320
implicitlyUnwrappedString
!
nil
!
nil
nil
implicitly-unwrapped-optional-type type!
protocol<Protocol
A, Protocol B, Protocol C> Protocol AProtocol B Protocol C
Protocol D
321
.Type
.Protocol SomeClass
SomeClass.Type SomeProtocol
SomeProtocal.Protocol
3.
4.
println("SomeBaseClass")
}
5. }
6. class SomeSubClass: SomeBaseClass {
7.
8.
9.
println("SomeSubClass")
}
10. }
11. let someInstance: SomeBaseClass = SomeSubClass()
12. // someInstance is of type SomeBaseClass at compile time, but
13. // someInstance is of type SomeSubClass at runtime
322
14. someInstance.dynamicType.printClassName()
15. // prints "SomeSubClass
:,
type-inheritance-clause : type-inheritance-list
type-inheritance-list type-identifier type-identifier , type-inheritance-list
Swift
var x: Int = 0 var x = 0
x Int
323
expression tree
var x: Int = 0 x 0
x
Swift
eFloat :Float 2.71828 Float
Double
1. let e = 2.71828 // The type of e is inferred to be Double.
2. let eFloat: Float = 2.71828 // The type of eFloat is Float.
Swift
3.4
sg552Github
Swift prefixbinary
primarypostfix
causes a side effect
operators
expression prefix-expressionbinary-expressionsopt
expression-list expression expression , expression-list
324
Prefix Expressions
Swift
++ 1 increment
-- 1 decrement
! Logical NOT
~ Bitwise NOT
+ Unary plus
- Unary minus
'&'
"In-Out parameters".
prefix-expression prefix-operatoroptpostfix-expression
prefix-expression in-out-expression
in-out-expression & identifier
Binary Expressions
Swift
160
<< Bitwise left shift
>> Bitwise right shift
325
150
*
/
%
&* Multiply, ignoring overflow
&/ Divide, ignoring overflow
&% , Remainder, ignoring overflow
& Bitwise AND
, 140
+
-
&+ Add with overflow
&- Subtract with overflow
| Bitwise OR
^ Bitwise XOR
Range , 135
.. Half-closed range
... Closed range
, 132
is type check
as type cast
Comparative , 130
<
<=
>
>=
==
!=
326
===
!==
~= Pattern match
Conjunctive , 120
&& Logical AND
Disjunctive , 110
|| Logical OR
Assignment , 90
= Assign
*= Multiply and assign
/= Divide and assign
%= Remainder and assign
+= Add and assign
-= Subtract and assign
<<= Left bit shift and assign
= Right bit shift and assign
&= Bitwise AND and assign
^= Bitwise XOR and assign
|= Bitwise OR and assign
&&= Logical AND and assign
||= Logical OR and assign
operatorsBasic Operators Advanced Operators .
327
binary-expression binary-operatorprefix-expression
binary-expression assignment-operatorprefix-expression
binary-expression conditional-operatorprefix-expression
binary-expression type-casting-operator
binary-expressions binary-expressionbinary-expressionsopt
Assignment Operator
assignment-operator =
condition true,
328
conditional-operator ? expression
Type-Casting Operators
as is.
as specified type
1. instance.
subclasssuperclass.
2. compile-time error
3.
optional. is an optional of the specified type
optional
nil. superclass subclass.
1. class SomeSuperType {}
2. class SomeType: SomeSuperType {}
3. class SomeChildType: SomeType {}
4. let s = SomeType()
5.
6. let x = s as SomeSuperType
meSuperType
// known to fail; compile-
7. let y = s as Int
time error
8. let z = s as SomeChildType
is SomeChildType?
'as'
1. let y1 = x as SomeType
329
tion
'is' runtime true, false
compile time
1. "hello" is String
2. "hello" is Int
Type Casting .
type-casting-operator istype
as? opttype
Primary Expressions
primary-expression identifiergeneric-argument-clauseopt
primary-expression literal-expression
primary-expression self-expression
primary-expression superclass-expression
primary-expression closure-expression
primary-expression parenthesized-expression
primary-expression implicit-member-expression
primary-expression wildcard-expression
Literal Expression
string, number ,
330
function__FUNCTION__ method
property getter/setter
init/subscript member keyword
the top level of a file module
array literal
literal-expression literal
literal-expression array-literal dictionary-literal
literal-expression __FILE__ __LINE__ __COLUMN__ __FUNCTION__
array-literal [ array-literal-items opt]
array-literal-items array-literal-item , opt array-literal-item, array-literal-items
array-literal-item expression
331
member self .
self.greeting var greeting: String, initgreeting: String
1. class SomeClass {
2.
3.
init(greeting: String) {
4.
5.
self.greeting = greeting
}
6. }
3.
4.
5.
6. }
332
self
self-expression self
self-expression self. identifier
self-expression self[ expression ]
self-expression self.init
Superclass Expression
class .
1 member. 2 subscript
3 initializer.
Closure Expression
closure lambda,
anonymous function. function closure
statement capture
333
, Function Declaration .
,
1. type type.
'in' type inferred
2.statement 0,1, $2
3.
'type inference '
1. myFunction {
2.
3.
return x + y
4. }
5.
6. myFunction {
7.
(x, y) in
8.
return x + y
9. }
10.
11. myFunction { return $0 + $1 }
12.
13. myFunction { $0 + $1 }
capture list
[] ',''in'
type,
334
// strong cap
ture
2. myFunction { [weak self] in print(self!.title) }
// weak captu
re
3. myFunction { [unowned self] in print(self.title) }
// unowned ca
pture
.
1.
Closure Expressions.
1. var x = MyEnumeration.SomeValue
335
2. x = .AnotherValue
implicit-member-expression .identifier
Parenthesized Expression
',' identifier x:
tuples function.
type type 1 type
Int, Int
parenthesized-expression ( expression-element-listopt)
expression-element-list expression-element | expression-element, expression-element-list
expression-element expression | identifier: expression
Wildcard Expression
10 x, 20
// x is 10, 20 is ignored
wildcard-expression _
Postfix Expressions
primary
336
expression
Swift
++ Increment
-- Decrement
Basic Operators Advanced Operators
postfix-expression primary-expression
postfix-expression postfix-expressionpostfix-operator
postfix-expression function-call-expression
postfix-expression initializer-expression
postfix-expression explicit-member-expression
postfix-expression postfix-self-expression
postfix-expression dynamic-type-expression
postfix-expression subscript-expression
postfix-expression forced-value-expression
postfix-expression optional-chaining-expression
function .
closure
1.
337
1.
function-call-expression postfix-expressionparenthesized-expression
function-call-expression postfix-expressionparenthesized-expression opttrailing-closure
trailing-closure closure-expression
Initializer Expression
Initializer Type
1. var x = SomeClass.someClassFunction
2. var y = SomeClass.init
// ok
// error
initializer
1. class SomeSubClass: SomeSuperClass {
2.
init() {
3.
4.
super.init()
5.
6. }
338
var someProperty = 42
3. }
4. let c = SomeClass()
5. let y = c.someProperty
// Member access
tuple, 0, 1, 2...:
1. var t = (10, 20, 30)
2. t.0 = t.1
3.
1 expression x.self x
339
expression type
"" instance type,
1. class SomeBaseClass {
2.
3.
4.
println("SomeBaseClass")
}
5. }
6. class SomeSubClass: SomeBaseClass {
7.
8.
9.
println("SomeSubClass")
}
10. }
11. let someInstance: SomeBaseClass = SomeSubClass()
12. //
prints "SomeSubClass"
Subscript Expression
getter/setter
getter setter .
340
Forced-Value Expression
nil
Optional-Chaining Expression
+ '?'
'?'
nil, nil, nil,
optional typeIn either case, the value of the postfix expression is still of an
optional type
""""""
optional type. c nil,
c?.property.performAction c property
performAction "c?.property.performAction"
341
optional type.
1. var c: SomeClass?
2. var result: Bool? = c?.property.performAction()
1. if let unwrappedC = c {
2.
result = unwrappedC.property.performAction()
3. }
optional-chaining-expression postfix-expression
3.5
coverxitGithub
Swift
Swift
GRAMMAR OF A STATEMENT
342
Swift
for for-in while do-while
break continue
Break Continue
loop-statement while-statement
loop-statement do-while-statement
For
for
for
1. for `initialzation`; `condition`; `increment` {
343
2.
`statements`
3. }
for
1
initialzation
2 condition truestatements 3
falsestatements increment for
3 increment 2
for-in Sequence
for-in
1. for `item` in `collection` {
2.
`statements`
3. }
344
While
while
while
1. while `condition` {
2.
`statements`
3. }
while
2 statements 1
345
Do-While
do-while
do-while
1. do {
2.
`statements`
3. } while `condition`
do-while
1 statements 2
2 condition true 1 falsedo-while
Swift if
346
switch
If
if
if
1. if `condition` {
2.
`statements`
3. }
else else
1. if `condition` {
2.
3. } else {
4.
5. }
else if
1. if `condition 1` {
2.
3. } else if `condition 2` {
347
4.
5. }
6. else {
7.
8. }
if LogicValue
GRAMMAR OF AN IF STATEMENT
if-statement if if-condition code-block else-clause opt
Switch
switch control expressionswitch
switch
1. switch `control expression` {
2.
3.
4.
5.
6.
7.
8.
9.
10.
`statements`
default:
`statements`
11. }
348
(guard expression)
where
case case
statements
(1, 1)
1. case let (x, y) where x == y:
let var
case
case
Swift
switch
case
Switch
Swift switch case
Int
(fall through)
349
case switch
case case case
fallthrough fallthrough Fallthrough
default-label default :
guard-clause where guard-expression
guard-expression expression
switch (:)
break continue switch
Break
Continue
350
label-name identifier
control-transfer-statement break-statement
control-transfer-statement continue-statement
control-transfer-statement fallthrough-statement
control-transfer-statement return-statement
Break
break switch break break
break label name
351
1. break
2. break `label name`
break switch
switch
break Break
Continue
continue continue
continue continue label name
1. continue
2. continue `label name`
continue
break continue
352
continue Continue
Fallthrough
fallthrough switch fallthrough switch
case case case
switch
switch fallthrough
continue-statement fallthrough
Return
return
1. return
2. return `expression`
return
Swift
353
return
Void ()
3.6
marsprinceGithub
swift
swift
GRAMMAR OF A DECLARATION
declaration import-declaration
declaration constant-declaration
declaration variable-declaration
declaration typealias-declaration
354
declaration function-declaration
declaration enum-declaration
declaration struct-declaration
declaration class-declaration
declaration protocol-declaration
declaration initializer-declaration
declaration deinitializer-declaration
declaration extension-declaration
declaration subscript-declaration
declaration operator-declaration
declarations declarationdeclarationsopt
declaration-specifiers declaration-specifierdeclaration-specifiersopt
swift
355
1. {
2.
`statements`
3. }
import
1. import
module
356
let :
1. let constant name: type = expression
getters settersgetters setters
firstNumber 10 secnodeName 42
1. 1
2. 2
3. 3
4. 4
:typetype inference
statictype propetries
constants
and variables, stored properties
357
var
(context)
358
statements
4. }
5. set(setter name) {
6.
statements
7. }
8. }
(computed properties)
willset didset
359
1. var variable name: type = expression {
2. willSet(setter name) {
3.
statements
4. }
5. didSet(setter name {
6.
statements
7. }
8. }
()(overriding
properyt observers)
(type annotation)
willset didset
willset willset
willset didset
willset
didset didiset
willset
360
(prpperty observers)
class static
(type properties)
variable-declaration variable-declaration-headpattern-initializer-list
variable-declaration variable-declaration-head variable-name type-annotation codeblock
361
typealias
1. typealias name = existing type
362
func
1. func function name(parameters) -> return type {
2.
statements
3. }
statements
3. }
var inout
in-out in-out (in-out
parameters)
nested nested
nestde functions
363
1. parameter name: parameter type
return y + String(x)
3. }
4. f(7, "hello")
5.
6. class C {
7.
8.
9.
return y + String(x)
}
10. }
11. let c = C()
12. c.f(7, y: "hello")
// x y
(second name)
(#)
364
(_)
1. _ : <#parameter type#.
2. parameter name: parameter type...
3. parameter name: parameter type = default argument value
(_)
(...)
int... int[]
(variadic parameters)
(=)
. f() f(x:7) x
f(7)
self mutating
override override
override
static
class
365
1. func function name(parameters)(parameters) -> return type {
2.
statements
3. }
:
1. func addTwoNumbers(a: Int)(b: Int) -> Int {
2.
return a + b
3. }
4. func addTwoNumbers(a: Int) -> (Int -> Int) {
5.
6.
return a + b
7.
8.
return addTheSecondNumber
9. }
10.
11. addTwoNumbers(4)(5) // Returns 9
function-declaration function-head function-name generic-parameter-clause optfunction-signature function-body function-head attributes opt declaration-specifiers opt
func function-name identifier operator function-signature parameter-clauses functionresult opt function-result ->attributes opt type function-body code-block parameterclauses parameter-clause parameter-clauses opt parameter-clause () (parameterlist...opt) parameter-list parameter parameter,parameter-list parameter inout opt let
opt#optparameter-name local-parameter-name opt type-annotation default-argumentclause opt parameter inoutoptvar#optparameter-namelocal-parameter-name opt typeannotationdefault-argument-clause opt parameter attributes opt type parameter-name
identifier
local-parameter-name identifier
default-argument-clause =-
expression
366
enum
(Structures and
Enumerations Are Value Types)
(Extension Declaration)
3.
4. }
(discrinminated)
case
(associated values)
367
3.
4. }
case
(raw value)(raw value type)
int
0,1,2 Int
case A, B, C = 5, D
3. }
ExampleEnum.A 0 ExampleEnum.B
ExampleEnum.C 5 ExampleEnum.D 6.
roRaw ExampleEnum.B.toRaw()
fromRaw
(raw values)
(.) EnumerationType.EnumerationCase
(.)(Enumeration Syntax)
(Implicit Member Expression).
368
enum-namegeneric-parameter-clauseopt{union-style-enum-
raw-value-style-enum-
members raw-value-style-enum-memberraw-value-style-enum-membersopt raw-valuestyle-enum-member declaration raw-value-style-enum-case-clause raw-value-styleenum-case-clause attributesoptcaseraw-value-style-enum-case-list raw-value-styleenum-case-list raw-value-style-enum-case raw-value-style-enum-case,raw-value-styleenum-case-list raw-value-style-enum-case enum-case-nameraw-value-assignmentopt
raw-value-assignment =literal
struct
declarations
3. }
369
-(initializers)
Memberwise Initializers for
Structure Types.
(Default Initializers).
(initiaization)
(.)(Accessing Properties)
(Extension Declaration).
struct-declaration
attributesoptstructstruct-namegeneric-parameter-clauseopttype-
class
370
declarations
3. }
typeinheritance-clause
(Initializer Declaration)
requierd
override
Swift
-(initializers)
-
(default initializers).
(.)(Accessing Properties)
371
(Extension Declaration).
class-declaration
attributesoptclassclass-namegeneric-parameter-clauseopttype-
protocol
3. }
optional
372
optional objc
optional
class_protocol
class_protocol
object class_protocol
class_protocol
()
protocol-declaration attributesoptprotocolprotocol-nametype-
protocol-method-declaration
protocol-member-
protocol-member-declaration
protocol-member-declarations
protocol-associated-type-
protocol-member-declarationprotocol-
member-declarationsopt
373
getter setter
getter setter
protocol-property-declaration variable-declaration-headvariablenametype-annotationgetter-setter-keyword-block
.
.
class
class static
class static
374
protocol-initializer-declaration initializer-headgeneric-parameter-clauseoptparameterclause
subscript-headsubscript-resultgetter-setter-keyword-
block
typealias
self
self
typealias-headtype-inheritance-clauseopt-
typealias-assignmentopt
375
Init
1. init(parameters) {
2.
statements
3. }
convenience
1. convenience init(parameters) {
2.
statements
3. }
requierd
376
()
overrride
initializer-declaration
initializer-headgeneric-parameter-clauseoptparameter-clause-
1. deinit {
2.
statements
3. }
deinitializer-declaration attributesoptdeinitcode-block
377
extension
declarations
3. }
type-inheritance-clause
extension-declaration
extensiontype-identifiertype-inheritance-clauseoptextension-
subscript
subscript (parameter) -> (return type){ get{ statements } set(setter name){ statements } }
378
(parameters)
object[i] i
(return type)
getter setter
setter getter
setter getter
(parameters)
(return type) override
()
Subscripts
attributesoptsubscript-
operator
operator
379
infixprefix postfix
Operators
() 2 + 3 * 5
associativity (associativity)
leftright none
(-) 4 - 5 - 6 (4 - 5) - 6
-7 none
1 < 2 < 3
100
none
380
(++)
Custom Operators
precedence-clause
precedenceprecedence-level
3.7
HawsteinGithub
Swift
required
noreturn
381
noreturn
assignment
inout assignment
class_protocol
[adopted]
objc class_protocol
class_protocol
exported
final
382
lazy
lazy
noreturn
T@noreturn T
noreturn (override)
noreturn
comforming
NSCopying
setter
copyWithZone NSCopying
NSManaged
NSManagedObject
Core Data
objc
Objective-C
getter setterobjc
Objective-C
objc
objc objc objc
objc
383
objc objc
Objective-C
getterssetters ExampleClass enabled
getter Objective-C isEnabled
1. @objc
2. class ExampleClass {
3.
4.
@objc(isEnabled) get {
5.
6.
7.
8. }
optional
conforming type
required
Interface Builder
Interface Builder Interface Builder Xcode Swift
Interface Builder IBActionIBDesignableIBInspectable IBOutlet
Objective-C
384
noreturn
auto_closure
auto_closure
noreturn
T@noreturn T
3.8
honghaozGithub
385
pattern(1, 2)
(x, y)(1, 2)
pattern wildcard-patterntype-annotationopt
pattern identifier-patterntype-annotationopt
pattern value-binding-pattern
pattern tuple-patterntype-annotationopt
pattern enum-case-pattern
pattern type-casting-pattern
pattern expression-pattern
Wildcard Pattern
_
386
1...3
1. for _ in 1...3 {
2.
3.
wildcard-pattern _
Identifier Pattern
someValue Int 42
1. let someValue = 42
42 someValue
value-binding pattern
identifier-pattern identifier
Value-Binding Pattern
let,
var
6. }
387
Tuple Pattern
for-in
(x, 0) 0
1. let points = [(0, 0), (1, 0), (1, 1), (2, 0), (2, 1)]
2.
3.
4.
5.
/* ... */
}
1. let a = 2
// a: Int = 2
2. let (a) = 2
// a: Int = 2
388
tuple-pattern-element pattern
switch
Associated Values.
Type-Casting Patterns
is as switch case
is as
1. is type
2. pattern as type
is runtime is
is is
as runtime as
as
389
is-pattern istype
as-pattern patternastype
Expression Pattern
switch case
Swift ~=
~= true~===
Range
7. default:
8.
9. }
10. // prints "(1, 2) is near the origin.
~=
point
390
4. }
5. switch point {
6. case ("0", "0"):
7.
10. default:
11.
12. }
13. // prints "(1, 2) is near the origin.
expression-pattern expression
3.9
fd5788Github
Swift ( 22 )
<>
391
T
UVKeyTypeValueType
T: Comparable T
Comparable
1. func simpleMin<T: Comparable>(x: T, y: T) -> T {
2.
if x < y {
3.
return y
4.
5.
return x
6. }
Where
where
where where
where
where T: Comparable T where T:
Comparable
<T where T: C, T: P> T C P
392
==T U
Generator <T: Generator, U:
Generator where T.Element == U.Element>
GRA M M A R OF A GE NE RIC P A RA M E T E R CL A US E
<>
393
Swift
/* ... */
3. }
Array<Int> Array<T> T
1. let arrayOfArrays: Array<Array<Int>> = [[1, 2, 3], [4, 5, 6], [7, 8, 9
]]
3.10
StanZhaiGithub
394
loop-statement for-statement
loop-statement for-in-statement
loop-statement while-statement
loop-statement do-while-statement
For
for-statement for for-init opt ; expression opt ; expression opt code-b lock
for-statement for ( for-init opt ; expression opt ; expression opt ) code-b lock
for-init variab le-declaration | expression-list
For-In
for-in-statement for pattern in expression code-b lock
While
while-statement while while-condition code-b lock
while-condition expression | declaration
Do-While
do-while-statement do code-b lock while while-condition
branch-statement if-statement
branch-statement switch-statement
If
if-statement if if-condition code-b lock else-clause opt
if-condition expression | declaration
395
control-transfer-statement b reak-statement
control-transfer-statement continue-statement
control-transfer-statement fallthrough-statement
control-transfer-statement return-statement
Break
break-statement break lab el-name opt
Continue
continue-statement continue lab el-name opt
Fallthrough
fallthrough-statement fallthrough
Return
return-statement return expression opt
396
declaration import-declaration
declaration constant-declaration
declaration variab le-declaration
declaration typealias-declaration
declaration function-declaration
declaration enum-declaration
declaration struct-declaration
declaration class-declaration
declaration protocol-declaration
declaration initializer-declaration
declaration deinitializer-declaration
declaration extension-declaration
declaration sub script-declaration
declaration operator-declaration
declarations declaration declarations opt
397
keyword-b lock
variable-declaration
398
function-declaration
signaturefunction-body
parameter
399
raw-value-style-enum-members
raw-value-style-enum-member raw-value-style-enum-
members opt
struct-declaration
struct-name identifier
struct-body { declarations opt }
class-declaration
inheritance-clause optclass-body
class-name identifier
class-body { declarations opt }
protocol-declaration
400
protocol-name identifier
protocol-body { protocol-member-declarations opt }
protocol-member-declaration protocol-property-declaration
protocol-member-declaration protocol-method-declaration
protocol-member-declaration protocol-initializer-declaration
protocol-member-declaration protocol-sub script-declaration
protocol-member-declaration protocol-associated-type-declaration
protocol-member-declarations protocol-member-declaration protocol-member-declarations opt
protocol-method-declaration
protocol-initializer-declaration
clause
401
wildcard-pattern _
identifier-pattern identifier
402
tuple-pattern ( tuple-pattern-element-list opt )
tuple-pattern-element-list tuple-pattern-element | tuple-pattern-element , tuple-pattern-elementlist
tuple-pattern-element pattern
expression-pattern expression
403
assignment-operator =
conditional-operator ? expression :
literal-expression literal
literal-expression array-literal | dictionary-literal
literal-expression __FILE__ | __LINE__ | __COLUMN__ | __FUNCT ION__
array-literal [ array-literal-items opt ]
array-literal-items array-literal-item , opt | array-literal-item , array-literal-items
array-literal-item expression
404
dictionary-literal [ dictionary-literal-items ] | [ : ]
dictionary-literal-items
items
superclass-expression
superclass-method-expression | superclass-subscript-
expression | superclass-initializer-expression
implicit-member-expression . identifier
wildcard-expression _
405
postfix-expression primary-expression
postfix-expression postfix-expression postfix-operator
postfix-expression function-call-expression
postfix-expression initializer-expression
postfix-expression explicit-member-expression
postfix-expression postfix-self-expression
postfix-expression dynamic-type-expression
postfix-expression sub script-expression
postfix-expression forced-value-expression
postfix-expression optional-chaining-expression
optional-chaining-expression postfix-expression ?
406
U+FDF0U+FE1F,
or
U+FE30U+FE44
identifier-head U+FE47U+FFFD
identifier-head U+10000U+1FFFD, U+20000U+2FFFD, U+30000U+3FFFD, or
U+40000U+4FFFD
identifier-head U+50000U+5FFFD, U+60000U+6FFFD, U+70000U+7FFFD, or
U+80000U+8FFFD
identifier-head U+90000U+9FFFD, U+A0000U+AFFFD, U+B0000U+BFFFD,
or U+C0000U+CFFFD
identifier-head U+D0000U+DFFFD or U+E0000U+EFFFD
identifier-character Digit 0 through 9
identifier-character U+0300U+036F, U+1DC0U+1DFF, U+20D0U+20FF, or
U+FE20U+FE2F
identifier-character identifier-head
407
integer-literal b inary-literal
integer-literal octal-literal
integer-literal decimal-literal
integer-literal hexadecimal-literal
binary-literal 0b b inary-digit b inary-literal-characters opt
binary-digit Digit 0 or 1
binary-literal-character b inary-digit | _
binary-literal-characters b inary-literal-character b inary-literal-characters opt
octal-literal 0o octal-digit octal-literal-characters opt
octal-digit Digit 0 through 7
octal-literal-character octal-digit | _
octal-literal-characters octal-literal-character octal-literal-characters opt
decimal-literal decimal-digit decimal-literal-characters opt
decimal-digit Digit 0 through 9
decimal-digits decimal-digit decimal-digits opt
decimal-literal-character decimal-digit | _
decimal-literal-characters decimal-literal-character decimal-literal-characters opt
hexadecimal-literal 0x hexadecimal-digit hexadecimal-literal-characters opt
hexadecimal-digit Digit 0 through 9, a through f, or A through F
hexadecimal-literal-character hexadecimal-digit | _
hexadecimal-literal-characters
hexadecimal-literal-character hexadecimal-literal-
characters opt
408
type-identifier
409
type-name identifier
optional-type type ?
implicitly-unwrapped-optional-type type !
type-inheritance-clause : type-inheritance-list
type-inheritance-list type-identifier | type-identifier , type-inheritance-list
410