varwelcomeMessgae:StringwelcomeMessgae="Hello"varred,green,blue:Double// Multiple variables defined
Naming Constants and Variables
123
letπ=3.14159let你好="你好世界"let🐶🐮="dogcow"
Integers
Integer Bounds
12
letminValue=UInt8.min// minValue is equal to 0, and is of type UInt8letmaxValue=UInt8.max// maxValue is equal to 255, and is of type UInt8
Int
On a 32-bit platform, Int is the same size as Int32.
On a 64-bit platform, Int is the same size as Int64.
UInt
On a 32-bit platform, UInt is the same size as UInt32.
On a 64-bit platform, UInt is the same size as UInt64.
Floating-Point Numbers
Double has a precision of at least 15 decimal digits, whereas the precision of Float can be as little as 6 decimal digits. T
Type Safety and Type Inference
Numeric Literals
123456789101112131415
letdecimalInteger=17letbinaryInteger=0b10001// 17 in binary notationletoctalInteger=0o21// 17 in octal notationlethexadecimalInteger=0x11// 17 in hexadecimal notation1.25e2// 125.01.25e-2// 0.01250xFp2// 60.0 = 15 x 2 x 20xFp-2// 3.75 = 15 x 0.5 x 0.5// Can have additional formatting literal (like Ruby)letpaddedDouble=000123.456letoneMillion=1_000_000letjustOverOneMillion=1_000_000.000_000_1
Integer Conversion
1234567891011
letcannotBeNegative:UInt8=-1// UInt8 cannot store negative numbers, and so this will report an errorlettooBig:Int8=Int8.max+1// Int8 cannot store a number larger than its maximum value,// and so this will also report an error// conversion must be explicitlettwoThousand:UInt16=2_000letone:UInt8=1lettwoThousandAndOne=twoThousand+UInt16(one)
Integer and Floating-Point Conversion
1234567
letthree=3letpointOneFourOneFiveNine=0.14159letpi=Double(three)+pointOneFourOneFiveNine// pi equals 3.14159, and is inferred to be of type DoubleletintegerPi=Int(pi)// integerPi equals 3, and is inferred to be of type Int
Type Aliases
123
typealiasAudioSample=UInt16varmaxAmplitudeFound=AudioSample.min// maxAmplitudeFound is now 0
Boolean
123456789
letorangesAreOrange=trueletturnipsAreDelicious=falseifturnipsAreDelicious{println("Mmm, tasty turnips!")}else{println("Eww, turnips are horrible.")}// prints "Eww, turnips are horrible."
Tuples
Sample
12
lethttp404Error=(404,"Not Found")// http404Error is of type (Int, String), and equals (404, "Not Found")
Decompose a tuple
12345
let(statusCode,statusMessage)=http404Errorprintln("The status code is \(statusCode)")// prints "The status code is 404"println("The status message is \(statusMessage)")// prints "The status message is Not Found"
Ignore some value when decomposing
123
let(justTheStatusCode,_)=http404Errorprintln("The status code is \(justTheStatusCode)")// prints "The status code is 404"
Access by index
1234
println("The status code is \(http404Error.0)")// prints "The status code is 404"println("The status message is \(http404Error.1)")// prints "The status message is Not Found"
Optionals
Sample
123
letpossibleNumber="123"letconvertedNumber=possibleNumber.toInt()// convertedNumber is inferred to be of type "Int?", or "optional Int"
nil
1234567
varserverResponseCode:Int?=404// serverResponseCode contains an actual Int value of 404serverResponseCode=nil// serverResponseCode now contains no valuevarsurveyAnswer:String?// surveyAnswer is automatically set to nil
If Statements and Forced Unwrapping
1234
ifconvertedNumber!=nil{println("convertedNumber has an integer value of \(convertedNumber!).")}// prints "convertedNumber has an integer value of 123."
Optional Binding
12345678910
ifletconstantName=someOptional{statements}ifletactualNumber=possibleNumber.toInt(){println("\(possibleNumber) has an integer value of \(actualNumber)")}else{println("\(possibleNumber) could not be converted to an integer")}// prints "123 has an integer value of 123"
Implicitly Unwrapping Optionals (Accessing an implicitly unwrapped optional when it does not contain a value will trigger a RTE)
123456789101112131415
letpossibleString:String?="An optional string."letforcedString:String=possibleString!// requires an exclamation markletassumedString:String!="An implicitly unwrapped optional string."letimplicitString:String=assumedString// no need for an exclamation markifassumedString!=nil{println(assumedString)}// prints "An implicitly unwrapped optional string."ifletdefiniteString=assumedString{println(definiteString)}// prints "An implicitly unwrapped optional string."
Assertions
Debugging with Assertions
123
letage=-3assert(age>=0,"A person's age cannot be less than zero")// this causes the assertion to trigger, because age is not >= 0