Download presentation
Presentation is loading. Please wait.
Published byPierce Heath Modified over 9 years ago
1
Swift
2
Introduced in 2014 Replaces Objective-C as “recommended development language” “safer, succinct, readable” Emphasizes type safety
3
Resources iOS Programming: The Big Nerd Ranch Guide Swift Programming: The Big Nerd Ranch Guide https://developer.apple.com/swift/ https://developer.apple.com/swift/resources/ The Swift Programming Language (Apple )
4
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
5
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.
6
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?
7
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
8
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]
9
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”]
10
Sets Similar to an array but members must be unique and are unordered var lotteryNumbers: Set
11
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
12
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 }
13
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.
14
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.