3. Swift combines the best of C and Objective-C.
Semi-colon (;) following each statement is not required
Multiline comments can be nested within other multiline
comments
Introduction
11/2/2016 3
4. Basic types and Collection types.
Key words: var, let
Constants are used more often.
Other customize types: Int8, UInt16, Int32, UInt64, 0b..., 0o....,
0x....
1_000_000.000_000_1 = 1000000.0000001
typealias <alias> = <ExistedType>
Swift is a type-safe language
Constants and variables
11/2/2016 4
5. Define variable and constant type to make code clear.
Unnecessary: Swift would define the type of variables and
constants by their init values.
Type antonation
11/2/2016 5
6. Values of optional variables or constants may be absent (= nil):
<type> ?
Must be unwrapped “!” when getting the value.
Implicitly Unwrapped Optionals: unnecessary to unwrap
Optional
11/2/2016 6
7. Swift has almost basic operators in C/C++, even ternary a ? b :
c
Modulo (%) also operate with floating-point numbers.
Range operators: a...b, a..<b
‘=‘: not return value
‘===‘: test whether two object references both refer to the
same object instance.
Basic operators
11/2/2016 7
8. A group of mixed types.
Each element can be named and we can access elements by
these names.
Tuples are compared by comparing each element respectively.
Tuple
11/2/2016 8
15. Elements: same type + ordered
Define: Array<type>() or [type]()
Array(repeating: <default value>, count: <size>)
“+”: combine two arrays
“[]”: to make array empty
Access element: [<index>]
Properties: count, isEmpty
Methods: append(<element>), insert(at:), remove(at:),
removeLast()
Array
11/2/2016 15
16. Elements: distinct values of the same type (hashable type) + no
ordered
Define: Set<type>() or [type]()
“[]”: to make set empty
Properties: count, isEmpty
Methods: insert(<element>), remove(<element>), removeAll(),
sorted(), contains(<element>),
Set
11/2/2016 16
17. Fundamental Set Operators:
==
intersection(<set>),
symmetricDifference(<set>),
union(<set>),
subtracting(<set>),
isSubset(of: <set>),
isSuperset(of:<set>),
isStrictSubset(of:<set>),
isStrictSuperset(of:<set>),
isDisjoint(with:<set>)
Set
11/2/2016 17
18. Like dictionary in Python
Define: Dictionary<keyType, valueType>() or
[keyType:valueType]()
Properties: isEmpty, keys, values
Methods: updateValue( <new value>, forKey: <key>),
removeValue(forKey: <key>)
Dictionary
11/2/2016 18
20. for <item> in <range or list>{}
(like Python)
for var index = <init value>; <stopping condition>; <index increasement>{}
(like C/C++)
For-In
11/2/2016 20
21. while: check the condition at the start of each through the loop.
repeat – while: check the condition at the end of each pass
through the loop.
While; repeat-while
11/2/2016 21
23. break: unnecessary
Each case must contain at least one
executable statement.
Compound case: combine several values
to a single case.
Each case can receive range.
Tuple: we use “_” to match any possible
value in switch-case
Switch case can bind the value or values it matches to
temporary constants or variables.
where :to check for additional conditions.
Switch
11/2/2016 23
24. continue, break
fallthrough
Labeled Statement
guard
Control transfer statements
11/2/2016 24
28. Default argument labels and “_” labels
Default value for parameter
Variadic parameter: same-type parameters
inout and &
Argument labels and parameter names
11/2/2016 28
29. (<type of parameter 1>, <type of parameter 2>,…) -> <return type>
Ex: ()-> Void
Can be used as parameter type or return type
Function types
11/2/2016 29
30. Define functions inside the bodies of other functions
Nested functions
11/2/2016 30
32. Shorter version of function:
{ (parameters) -> return type in
statements
}
Single-expression closure:
{ <parameter>,… in <return value> }
Shorthand argument names: $0, $1, $2...
Ex: sorted(by: { $0 > $1 }) // ~ { s1, s2 in s1 > s2}
Closure expressions
11/2/2016 32
33. When assigning a function or a closure to a constant or a variable, that
constant or variable is a reference to the function or closure.
Reference types
11/2/2016 33
34. When the closure is passed as an argument to the function, but
is called after the function returns.
Adding @escaping before argument name
Escaping closures
11/2/2016 34
35. Adding @autoclosure before closure parameter
The codes inside the closures (as parameters of function) will not be really
executed until it's called again in the body of the function
Autoclosures
11/2/2016 35
41. Structure have an automatically-generated memberwise
initializer.
Struct is value ype
Class is reference type
To compare the references: === or !==
Structure types in Swift: String, Array, Dictionary
Classes types in Swift: NSString, NSArray, NSDictionary
Compare with C/C++
11/2/2016 41
43. The property whose initial value is not calculated until the first
time it is used.
Global constants and variables are always computed lazily.
Keyword: lazy
Lazy stored properties
11/2/2016 43
46. willSet: is called just before the value is stored, with newValue
(a default parameter)
didSet: is called imediately after the new value is stored, with
oldValue (a default parameter)
Property observers
11/2/2016 46
53. like C++’s inheritance
override methods and properties (get and set)
super: excute superclass’s methods or properties
final: preventing a method, property or subscript from being
overriden
11/2/2016 53
55. Init is a mutating function.
Swift also provides a default initializer.
Write required before the definition of a class initializer to
indicate that every subclass of the class must implement that
initializer.
11/2/2016 55
57. 1: If your subclass doesn’t define any designated initializers, it
automatically inherits all of its superclass designated initializers.
2: If your subclass provides an implementation of all of its
superclass designated initializers—either by inheriting them as
per rule 1, or by providing a custom implementation as part of
its definition—then it automatically inherits all of the superclass
convenience initializers.
Automatic initializer inheritance
11/2/2016 57
58. init? which can return nil if the init is unsuccessful.
This can be override in subclass (and also can be override to a subclass
nonfailable initializer).
Failable initializers
11/2/2016 58
61. ARC automatically frees up the memory used by class instances
when those instances are no longer needed
Create a new instance --> allocate a chunk of memory to store
information.
Destruct instance --> frees up the memory used by that instance to
used for other purposes.
ARC will not deallocate an instance as long as at least one active
reference to that instance still exists.
Concept
11/2/2016 61
65. The closures capture self, which means that it holds a strong
reference
Strong reference cycles for closures
11/2/2016 65
66. Strong reference cycles for closures
(Solving)
11/2/2016 66
defines the rules to use when capturing one or more reference
types within the closure’s body.
72. Disabling error propagation: using try!
defer: execute a set of statements just before code execution
leaves the current block of code.
11/2/2016 72
74. is: check whether an instance is of a certain subclass type
as? and as! : used to downcast to the subclass. Using as?
When you not sure if the downcast will succeed and as! only
when you are sure that the downcast will always succeed.
Any:an instance of any type at all, including function types.
AnyObject: an instance of any class type.
11/2/2016 74
75. Add new functionality (even init) to an existing class, structure, enumeration,
or protocol type
EXTENSIONS
11/2/2016 75
78. list of methods and properties to define an interface
11/2/2016 78
associatedtype: a placeholder name to a type that is used as
part of the protocol.
79. To make the connection between 2 classes.
Ex: when the profile view controller need to update after we edit
some details.
Create a delegate protocol that defines the responsibilities of
the delegate.
Add a delegate property in the delegating class to keep track
of the delegate.
Adopt and implement the delegate methods in the delegate
class.
Call the delegate from the delegating object.
Delegate pattern design
11/2/2016 79
nil cannot be used with non-optional constants and variables.
isEmpty: test the string whether or not is empty.
characters: get a collection of characters in the string.
characters.count: get the number of characters in string.
startIndex: get the starting index.
endIndex: get the ending index.
characters.indices: get a collection of indexes of individual characters in a string.
var <newString> = String(<anotherString>): declare and copy a value of an existed string to a new string.
append(<character>): add a character to the end of string.
+=, +: are used to multate a string.
index(before:) and index(after:): access the indices before and after a given index.
index(_,offsetBy:): access an index farther away from the given index.
insert(_,at:): insert a single character into a string at a specified index.
insert(contentsOf:, at: ): insert the contents of another string at a specified index.
remove(at:): remove a single character from a string at a specified index.
removeSubrange(<range>): remove a substring at a specified range.
hasPrefix(<string>) and hasSuffix(<string>): check whether a string has a particular string prefix or suffix. They return a Boolean value.
Use the intersection(_:) method to create a new set with only the values common to both sets.
Use the symmetricDifference(_:) method to create a new set with values in either set, but not both.
Use the union(_:) method to create a new set with all of the values in both sets.
Use the subtracting(_:) method to create a new set with values not in the specified set.
Use the “is equal” operator (==) to determine whether two sets contain all of the same values.
Use the isSubset(of:) method to determine whether all of the values of a set are contained in the specified set.
Use the isSuperset(of:) method to determine whether a set contains all of the values in a specified set.
Use the isStrictSubset(of:) or isStrictSuperset(of:) methods to determine whether a set is a subset or superset, but not equal to, a specified set.
Use the isDisjoint(with:) method to determine whether two sets have any values in common.
Fallthrough: jump to the statement in the next case in switch-case, noting that the condition of the next case is not checked.
Labeled Statement: is used to name a statement and called after continue or break to continue or end the execution of the labeled statement.
Guard:
The combination of assert and if statement: checking for the condition you want. If the condition is not met, guard's else statement is run: checking for bad cases early, making your function more readable and easier to maintain.
ERROR TYPE: In Swift, errors are represented by values of types that conform to the Error protocol, Swift enumerations are particularly well suited to modeling a group of related error conditions, with associated values allowing for additional information about the nature of an error to be communicated
THROWING AN ERROR: Throwing an error lets you indicate that something unexpected happened and the normal flow of execution can’t continue. You use a throw statement to throw an error.
THROWING FUNCTIONS: To indicate that a function, method, or initializer can throw an error, you write the throws keyword in the function’s declaration after its parameters.
HANDLING ERRORS: