-
Types
Int, Double, Float, Bool (true/false), String
Array, Set, Dictionary
Tuples, Optionals -
Type Annotation
let message: String = "Hello"
var count: Int = 10 -
String Interpolation
var message = "Good"
print("The food tastes (message).") -
Int
Int is preferred.
signed/unsigned
Int8(-128~127)/Int16/Int32/Int64
UInt8(0~255)/UInt16/UInt32/UInt64 -
Floating Point
Double is preferred.
Float: 32bit
Double: 64bit - Type Inference
Swift is a type safe language.
let pi = 3.14 //Double
- Type Conversion
Conversions between integer and floating-point numeric types must be made explicit
var a: Int8 = 3
var b: Int64 = Int64(a) //Using initializer
Literals:
let a: Int = 1
let b: Double = 3.14
var c: Double = a + b //error
var d: Double = (Double)a + b //right
let e: Double = 1 + 3.14 //right, literals can be added directly
Type Alias
typealias MyType = Int-
Tuples
let status: (Int, String) = (200, "Ok")
let statusCode = status.0
let statusMsg = status.1var (code, msg) = status print(code) //200 print(msg) //OK let status2 = (code: 200, msg: "OK") print(status2.code) print(status2.msg)
-
Optionals
var s: String = "Hello"
var number: Int? = Int(s) //number may be nilvar str: String? //str is automatically set to nil str = "World" print("The String is \(str!).") // Forced unwrapping
Optional Binding
var numString: String = "123abc"
if let num = Int(numString) {
print("Can convert.")
}
else {
print("Can not convert.")
}
Multiple binding:
if let var1 = opt1, var2 = opt2 {
//TODO
}-
Implicitly Unwrapping Optionals
let str1: String? = "Optional string."
print((str1!)) //forced unwrapping, requires an exclamation marklet str2: String! = "Another optional string." print(str2) //No need for exclamation mark
-
Error Handling
func mayThrow() throws {
//logic
}do { try mayThrow() } catch SomeError1 { //error handling 1 } catch SomeError2{ //error handling 2 }
Assertions
let age: Int = 17
assert(age>=18, "The age must be at least 18 years old.") // app will be terminated.