Swift
Introduced in 2014 Replaces Objective-C as “recommended development language” “safer, succinct, readable” Emphasizes type safety
Resources iOS Programming: The Big Nerd Ranch Guide Swift Programming: The Big Nerd Ranch Guide The Swift Programming Language (Apple )
Types Structures, classes, enumerations All three can have properties, initializers, instance methods, class or static methods Types that are often primitive types are structures: – Numbers: Int, Float, Double – Boolean: Bool – Text: String, Character – Collections: Array, Dictionary, Set Optionals: value of a particular type or no value
Playgrounds Xcode: File New Playground… Type in code on the left Results show up in the sidebar on the right Watch out for errors. No results will show up after an error.
Variables and constants var var str = “I can change my value” let let constStr = “I can’t change my value” Notice there are no declared types. Swift does type inference based on initial values. Is that a good thing?
Numbers and boolean values Integers: Various types, but usually use Int var nextYear: Int Floating point: Float (32-bit), Double (64-bit), Float80 (80-bit) var bodyTemp: Float Boolean: Bool, has values true or false var hasPet: Bool
Arrays Ordered collection of elements Type is Array where T is the type of the elements All elements must be the same type var arrayOfInts: Array var arrayOfInts2: [Int] var arrayOfInts3 = [1, 2, 3]
Dictionaries Unordered collection of key-value pairs Values can be any type Keys must be hashable – Int, Float, Character, String are all hashable Can only contain keys and values of declared types var capitals: Dictionary var capitals: [String: String] var capitals = [“Germany”: “Berlin”, “Japan”: “Tokyo”, “UK”: “London”]
Sets Similar to an array but members must be unique and are unordered var lotteryNumbers: Set
Literals String literals: double quotes “All your base are belong to us” Number literals: 42, 91.1 Array literals: square brackets [“one”, “two”, “three”] Dictionary literals: square brackets with colons
Fun! with optionals? var y: Float // nil value might crash program var x: Float? // proper unwrapping prevents crashes y = x // compiler error y = x! // Don’t use the force, Luke! if let y = x { // handle non-nil case } else { // handle nil case }
Optionals aren’t optional Even if you never declare variables as optional, you will still have to deal with optionals. Subscripting a dictionary returns an optional.
for loops a = [1, 2, 3] for var i = 0; i < a.count; ++i { print(i); } for i in [1, 2, 3] { print(i) } Can use range, enumerate