LS01 - Swift Intro part 1 PDF
Document Details
Uploaded by Deleted User
Phil Jimmieson
Tags
Summary
This is a lecture set on Swift programming. It introduces Swift 5.9, Swift basics, and covers classes, structures, method syntax, message passing, memory management, and the Foundation Framework. The document also includes information about Swift versions and their releases from 2017 to 2024.
Full Transcript
COMP228 App Development Session: 2024-2025 Lecture Set 1 - Swift Introduction Phil Jimmieson - Department of Computer Science [ last updated: 19th Sept 2024 ] 1 COMP228 App Development...
COMP228 App Development Session: 2024-2025 Lecture Set 1 - Swift Introduction Phil Jimmieson - Department of Computer Science [ last updated: 19th Sept 2024 ] 1 COMP228 App Development Session: 2024-2025 Lecture Set 1 - Swift Introduction - part 1 Phil Jimmieson - Department of Computer Science [ last updated: 19th Sept 2024 ] 2 In these Slides... We will cover: Introduction to Swift 5.9 Swift Basics / Language Intro Classes and Structures Method Syntax Message Passing Memory Management A quick look at the Foundation Framework An introduction to the framework 3 Swift Introduction 4 What is Swift? An object-oriented language “Objective C without the C” Developed originally by Chris Lattner at Apple Open Source as of Dec 2015 Employs modern language theory concepts Exploits a number of object oriented principles Inherits many principles (but not syntax) from Smalltalk Objective C Aim is to simplify iOS programming. Concatenating two Unicode strings NSString *str = @"hello,"; str = [str stringByAppendingString:@" world"]; Swift var str = "hello," equivalent str = str + " world" 5 Swift Basics Swift version 4.0 - released September 2017 some Swift 3 features deprecated and some earlier Swift features removed Swift version 4.2 - released September 2018 minor updates to version 4.1 Swift 5.0 - released February 2019 ABI Compatibility on Apple platforms (all subsequent releases can rely on OS Swift runtime and standard library) Swift 5.1- released September 2019 Module stability - developers can make changes to their libraries without necessarily breaking binary compatibility. Swift 5.2 - released March 2020 focused on “improving the developer experience” 6 Swift Basics Swift 5.3 - released September 2020 (in Xcode 12) (mostly) additional features to support SwiftUI Swift 5.4 - released April 2021 (in Xcode 12.1) faster build performance, faster code completion Swift 5.5 - released September 2021 (in Xcode 13) support for asynchronous code - async / await Swift 5.6 - released March 2022 Package manager improvements Swift 5.7 - September 2022 (in Xcode 14) Regex literals and a RegexBuilder library. If-let shorthand 7 Swift Basics Swift 5.8 - released March 2023 Adds a new StaticBigInt type and tidies up some inconsistencies in the language Swift 5.9 - 18th Septeber 2023 Macros. Non-copyable types. Swift 6 - Released in September 2024 Cross-platform APIs. C++ interoperability. Data race safety checks. Foundation framework rewritten in Swift 8 Swift Language Intro part 1 Standard Types Tuples Strings 9 Standard Types 10 Swift Language Intro - part 1 Constants and variables use standard naming scheme (start with lowercase letter and camel case) let myString = "The weather looks like rain” var coreTemperature = 36.9 //inferred by the compiler to be a Double var myInt: Int Constants declared with let, Variables with var types can be inferred from default values (else you’ll need to specify them). No “;” needed on the end of a line. 11 Swift Language Intro - part 1 Ints obviously Swift has an integer type: var myInt = 97 But as a convenience, when declared, large integers can include the “_” character inserted into them to aid readability var speedOfLight = 186_000 //miles per second var populationOfUK = 66_040_200 //in 2017 ( If you print these, the _ does not appear in the output ) 12 Swift Language Intro - part 1 Standard types: String, Double, Int (+ related e.g. UInt, UInt32, Int32, StaticBigInt, Float16) Bool = “true” or “false” 13 Swift Language Intro - part 1 Generating random Ints in Swift < 4.2 involved the use of a UInt32 via arc4random_uniform() let diceRoll = arc4random_uniform(6) + 1 //value between 1 and 6 Swift 4.2 added a cryptographically secure randomiser to Swift for use in the numeric types. let diceRoll = Int.random(in: 1...6) //value between 1 and 6 This is typical of how the aim of many of the improvements to Swift - to simplify and make your code clearer. 14 Tuples 15 Swift Language Intro - part 1 Tuples (multiple values grouped into a single value) let http404Error = (404, "Not Found") // http404Error is of type (Int, String), and equals (404, "Not Found") let (statusCode, statusMessage) = http404Error print("The status code is \(statusCode)") print("The status message is \(statusMessage)") let (justTheStatusCode, _) = http404Error print("The status code is \(justTheStatusCode)") print("The status code is \(justTheStatusCode)") 16 Swift Language Intro - part 1 More on Tuples: We can name the elements when we declare the tuple let http404Error: (code: Int, message: String, fatal: Bool) = (404, "Not Found", false) print("The status code is \(http404Error.code)") print("The status message is \(http404Error.message)") if (http404Error.fatal) { print("Error is fatal") } else { print("Error is non-fatal") } We can also refer to the components numerically. let http404Error: (code: Int, message: String, fatal: Bool) = (404, "Not Found", false) print("The status code is \(http404Error.0)") print("The status message is \(http404Error.1)") print("The status fatal value is \(http404Error.2)") 17 Swift Language Intro - part 1 More on Tuples: Excellent for returning more than 1 value from a function. func getHttpError() -> (code: Int, message: String, isFatal:Bool) { return (404, "Not Found",true) } let z = getHttpError() print("Code is \(z.code). Message is \"\(z.message)\"") if z.isFatal { print("Fatal error occurred") } Can decompose them to access individual element values 18 Swift Language Intro - part 1 Tuples aren’t found in Objective C Have to decompose them if you’re passing them to Objective C methods (still some of these around in iOS). var s1 = "hello" var s2 = "world" (s1, s2) = (s2, s1) // now s1 is "world" and s2 is "hello" print(s1,s2) // prints “world hello" Assigning variable values directly to one another through a Tuple is safe. 19 Strings 20 Strings in Swift Unicode vs ASCII in C and Obj C, strings are arrays of ASCII characters (byte 0-255), represented in double quotes; i.e. "Hello ASCII folk!" Unicode character sets can represent alphabets of many more than 256 characters and each character may be represented by a multi-byte sequence. Objective C prefixes such a string with an “@“ to indicate it is Unicode: @"A Unicode string" In Swift, strings are composed of Unicode characters. No special stuff needed: "Hello from ! Unicode people!" let saved" = UserDefaults.standard.string(forKey: "phoneNumber") if let " = saved" { let promptText = "Your phone number is: " + " let numberInputText = " } 21 Strings in Swift Unicode vs ASCII in C and Obj C, strings are arrays of ASCII characters (byte 0-255), represented in double quotes; i.e. "Hello ASCII folk!" Unicode character sets can represent alphabets of many more than 256 characters and each character may be represented by a multi-byte sequence. Objective C prefixes such a string with an “@“ to indicate it is Unicode: @"A Unicode string" In Swift, strings are composed of Unicode characters. No special stuff needed: "Hello from ! Unicode people!" let 𝜋 = 3.1415926 let circumference = 2 * 𝜋 * radius let radius = 17.2 print("The circumference of a circle of radius \(radius) is \(circumference)”) // outputs The circumference of a circle of radius 17.2 is 108.07078544 22 Strings in Swift A String is a series of character values Each character is a single extended grapheme cluster (a sequence of 1 or more Unicode scalars) let myString = "# came to Earth in a $" A single character can be composed of multiple bytes - can’t index a string by Int (i.e. size of char representation * array index integer - not useful here ) e.g. this doesn’t work in Swift: print(myString) //this isn’t valid Swift - but can use a Range Strings are value types. (Copied when passed to a method or function 23 Strings in Swift Multiline strings!! let quotation = """ The White Rabbit put on his spectacles. "Where shall I begin, please your Majesty?" he asked. in Swift 4 "Begin at the beginning," the King said gravely, "and go on till you come to the end; then stop." """ The string starts on the first line following the opening quotes and ends on the last line before the closing quotes. Each new line is a new line in your string. To prevent this in a multiline string, use a\ let softWrappedQuotation = """ The White Rabbit put on his spectacles. "Where shall I begin, \ please your Majesty?" he asked. "Begin at the beginning," the King said gravely, "and go on \ till you come to the end; then stop." """ 24 Strings in Swift Raw strings!! in Swift 5.0 can specify a custom delimiter using the # symbol (alt-3) let myRawString = #"Did you say "Help me"?"# print(myRawString) //prints Did you say "Help me"? Characters in the string are treated literally. If you need to insert values from variables (or escape sequences), use additional # let user = "Phil" let myRawString = #"Did you say "Help me" \(user)?"# print(myRawString) //prints Did you say "Help me" \(user)? let user = "Phil" let myRawString2 = #"Did you say "Help me" \#(user)?"# print(myRawString2) //prints Did you say "Help me" Phil? 25 Strings in Swift Index a String using a String.Index (not Int), or a Range let myString = "An # came to Earth in a $" let firstIndex = myString.startIndex let firstCharacter = myString[firstIndex] print(firstCharacter) //prints A startIndex is the position of the first character in the string endIndex is the position after the last character in the string We can create an index to access a specific character, based on those indexes let index1 = myString.index(myString.startIndex, offsetBy: 3) let index2 = myString.index(myString.endIndex, offsetBy: -1) let aCharacter = myString[index1] let bCharacter = myString[index2] print(aCharacter, bCharacter) //prints ?? A: space and $ B: # and $ C: # and error 26 Strings in Swift Access individual characters of a String by iterating over the String itself. for character in "Dog!%"{ print(character) } // D // o // g // ! // % determine string length via.count let myString = "The weather looks like rain &" print(myString.count) //prints 29 27 Strings in Swift String concatenation and modification may not actually increase the string’s character count! var word = "cafe" print("the number of characters in \(word) is \(word.count)") // Prints "the number of characters in cafe is 4" word += "\u{301}" // COMBINING ACUTE ACCENT, U+0301 print("the number of characters in \(word) is \(word.count)") // Prints "the number of characters in café is 4” due to Swift’s use of extended grapheme clusters for Character values 28 Strings in Swift Unicode character encodings ~ ñ 0xF1 n 0x6E + 0x303 # Ruby one = “\u{F1}” ñ two = “\u{6E}\u{303}” ñ String concatenation and modification may not actually increase the string’s character count! 29 Strings in Swift Unicode character encodings ~ ñ 0xF1 n 0x6E + 0x303 # Ruby one = “\u{F1}” ñ two = “\u{6E}\u{303}” ñ one.length 1 two.length 2 one == two false String concatenation and modification may not actually increase the string’s character count! 30 Strings in Swift Unicode character encodings ~ ñ 0xF1 n 0x6E + 0x303 // swift let one = "\u{F1}" ñ let two = "\u{6E}\u{303}" ñ print(one.count) 1 print(two.count) 1 if one == two { print("The same!") The same! } String concatenation and modification may not actually increase the string’s character count! 31 Strings in Swift This is also evident in complex Emoji in Swift strings e.g.: ( = )+ * + ' joined to +++ joined to +)+ , let twoWomenHoldingHands = "\u{1f469}\u{1f3fc}\u{200d}\u{1f91d}\u{200d}\u{1f469}\u{1f3fd}" print(twoWomenHoldingHands,twoWomenHoldingHands.count) - ' 32 Strings in Swift ( = )+ * + ' joined to +++ joined to +.+ , let santa = "\u{1f385}" let womanHoldingHandsWithSanta = "\u{1f469}\u{1f3fc}\u{200d}\u{1f91d}\u{200d}\u{1f385}\u{1f3fd}" print(santa, "\n", womanHoldingHandsWithSanta, womanHoldingHandsWithSanta.count). /+0 33