lecture 07 swift
TRANSCRIPT
![Page 1: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/1.jpg)
Lecture 07. SwiftLviv Polytechnic National University
M.V.Davydov
![Page 2: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/2.jpg)
Swift history
• Development of Swift started on July 2010 by Chris Lattner
• Swift reached the 1.0 milestone on September 9, 2014, with the Gold Master of Xcode 6.0 for iOS.
• Swift 2.0 was announced at WWDC 2015, and was made available for publishing apps in the App Store in September 21, 2015.
• Swift 3.0 was released on September 13, 2016.[27]
Ω
![Page 3: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/3.jpg)
![Page 4: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/4.jpg)
Swift features
Swift is a powerful and intuitive programming language for macOS, iOS, watchOS and tvOS. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and Swift includes modern features developers love. Swift code is safe by design, yet also produces software that runs lightning-fast.
![Page 5: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/5.jpg)
Swift features• Open Source• Closures unified with function pointers• Tuples and multiple return values• Generics• Automatic memory management• Fast and concise iteration over a range or collection• Structs that support methods, extensions, and protocols• Native error handling using try / catch / throw • Functional programming patterns, e.g., map and filter• Playgrounds are available
Most examples are from developer.apple.com
![Page 6: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/6.jpg)
Вирази треба відділяти крапкою з комою, але в кінці рядка крапка з комою
не обов’язкова
Hello world! Hello world! Hello world! Hello world! Hello world!
let x : String = "Hello world!" print(x); print(x,x) print(x); print(x)
![Page 7: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/7.jpg)
var вводить змінну let — константу
![Page 8: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/8.jpg)
Тип змінної або задається явно, або визначається автоматично
![Page 9: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/9.jpg)
Swift підтримує Unicode не лише всередині стрічок
![Page 10: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/10.jpg)
Коментарі у Swift// This is a single-line comment.
/* This is also a comment but is written over multiple lines. */
Багатострічкові коментарі можути бути вкладені
/* This is the start of the first multiline comment. /* This is the second, nested multiline comment. */ This is the end of the first multiline comment. */
![Page 11: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/11.jpg)
Підтримка запису чисел у десятковій, двійковій, вісімковій і шістнадцятковій
системах числення
let decimalInteger = 17
// 17 in binary notation let binaryInteger = 0b10001
// 17 in octal notation let octalInteger = 0o21
// 17 in hexadecimal notation let hexadecimalInteger = 0x11
![Page 12: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/12.jpg)
Тип виразу можна взнати командою type(of:вираз)
var a = 10 let c = Int("12") print(type(of:a)) print(type(of:c))
Результат:
Int Optional<Int>
![Page 13: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/13.jpg)
Змінна, яка може набувати значення nil, має тип Optional. Такий тип створюється
додаванням до типу символа «?»
let nickName: String? = nil print(nickName) let s:String = nickName // помилка компіляції
Результат: Optional<String> nil error: value of optional type 'String?' not unwrapped;
![Page 14: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/14.jpg)
При роботі з Optional можна використовувати оператор ??, щоб задати значення за замовченням
let nickName: String? = nil let fullName: String = "John Appleseed" let informalGreeting = "Hi \(nickName ?? fullName)" print(informalGreeting)
Результат: Hi John Appleseed
![Page 15: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/15.jpg)
Приведення типу, яке не завжди дає результат, має тип Optional<Тип>.
Для приведення Optional до звичайного типу використовується оператор !або конструкціяif let <назва> = <вираз>
let c = Int("12") print(type(of:c)) print(c) // warning is here! print(c!) print(type(of:c!)) if let q=c { print(q, " ", type(of:q)) }
Результат: Optional<Int> Optional(12) 12 Int 12 Int
![Page 16: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/16.jpg)
Декілька змінних одного типу без ініціалізації можна означити в одному рядку
var red, green, blue: Double print(type(of:red)) print(type(of:green)) print(type(of:blue))
Результат:
Double Double Double
![Page 17: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/17.jpg)
Для приведення типу використовується конструкція тип(вираз)
![Page 18: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/18.jpg)
Є зручна форма для форматування стрічки \(вираз)
![Page 19: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/19.jpg)
При створенні звичайних і асоціативних масивів тип може визначатися автоматично
![Page 20: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/20.jpg)
let arr = ["Hello", "World"] print(arr) print(type(of:arr))
Результат:
["Hello", "World"] Array<String>
При створенні звичайних і асоціативних масивів тип може визначатися автоматично
![Page 21: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/21.jpg)
Якщо тип змінних у масиві відрізняється, то тип масиву не можна визначити
автоматично
let arr = ["Hello", 1]
Результат: Помилка компіляції!!!
![Page 22: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/22.jpg)
Але є масив типу Any
let arr : Array <Any> = ["Hello", 1, "2"] print(arr)
Результат: ["Hello", 1, "2"]
![Page 23: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/23.jpg)
Отримати значення зі зміної типу Any можна за допомогою конструкції
as! або as?let arr : Array <Any> = ["Hello", 1, "2"] print( arr[0] as! String ) print( arr[1] as! Int ) print( arr[0] as? Int ) // попередження компілятора print( "\(arr[2])" ) print( String(describing:arr[2]) ) print( arr[2] as! Int ) // помилка на етапі виконання print( arr[1] as! String ) // помилка на етапі виконання
Результат: Hello 1 nil 2 2 Could not cast value of type 'Swift.String' (0x10b63e858) to 'Swift.Int' (0x10b63a408).
![Page 24: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/24.jpg)
Означення порожніх звичайних і асоціативних масивів
var a : Array<String> = [] var b = Array<String>() var c : Dictionary<String, Float> = [:] var d = Dictionary<String, Float>() print(type(of:a)) print(type(of:b)) print(type(of:c)) print(type(of:d))
Результат: Array<String> Array<String> Dictionary<String, Float> Dictionary<String, Float>
![Page 25: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/25.jpg)
Перебір елементів масиву
![Page 26: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/26.jpg)
Перебір елементів асоціативного масивуvar c : Dictionary<String, Float> = [:]
c["7"] = 1.0; c["1"] = 2.0; c["3"] = 3.0; c["4"] = 3.0;
for w in c { print(w.key, "->", w.value) }
Результат: 4 -> 3.0 7 -> 1.0 1 -> 2.0 3 -> 3.0
![Page 27: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/27.jpg)
Альтернативний метод перебору елементів асоціативного масиву
var c : Dictionary<String, Float> = [:]
c["7"] = 1.0; c["1"] = 2.0; c["3"] = 3.0; c["4"] = 3.0;
for (key, value) in c { print(key, "->", value) }
Результат: 4 -> 3.0 7 -> 1.0 1 -> 2.0 3 -> 3.0
![Page 28: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/28.jpg)
Swift підтримує кортежіtypealias StrIntDouble = (String, Int, Double) let sid:StrIntDouble = ("Hello", 1, 3.4) print(sid) print(sid.0) print(sid.1) print(sid.2)
Результат: (0, 0) ("Hello", 1, 3.3999999999999999) Hello 1 3.4
![Page 29: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/29.jpg)
Кортежі можуть мати іменовані атрибутиtypealias NamedTripple = (first:Int, second:String, third:Double) var a : NamedTripple = (1, "String", 2.5) print(a) print(a.first) print(a.second) print(a.third) print(a.0) print(a.1) print(a.2)
Результат: (1, "String", 2.5) 1 String 2.5 1 String 2.5
![Page 30: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/30.jpg)
Оператор switch підтримує різні методи порівняння значень, навіть користувацькі. Спрацьовує лише
одна гілка (перша з можливих)! Switch має перебрати всі можливі варіанти!
let vegetable = "red pepper" switch vegetable { case "cucumber", "watercress": print("That would make a good tea sandwich.") case let x where x.hasSuffix("pepper"): print("Is it a spicy \(x)?") case "red pepper": print("This is red pepper") default: print("Everything tastes good in soup.") }
Результат: Is it a spicy red pepper?
![Page 31: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/31.jpg)
Swift підтримує for … in циклиlet interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25], ] var largest = 0 for (kind, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number } } } print(largest)
Результат: 25
![Page 32: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/32.jpg)
Цикли while i repeat в Swiftvar n = 2 while n < 100 { n *= 2 } print(n) var m = 2 repeat { m *= 2 } while m < 100 print(m)
Результат: 128 128
![Page 33: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/33.jpg)
Цикли for <змінна> in from..<toexcl for <змінна> in from…toincl
var total = 0 for i in 0..<4 { total += i } print(total)
var total2 = 0 for i in 0...4 { total2 += i } print(total2)
Результат: 6 10
![Page 34: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/34.jpg)
Важливо! Межі циклу перевіряються на етапі виконання
var a1 = 1 var b1 = -5
for i in a1...b1 { print(i) }
Результат: fatal error: Can't form Range with upperBound < lowerBound
![Page 35: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/35.jpg)
Functions in Swift
func greet(person: String, day: String) -> String { return "Hello \(person), today is \(day)." } print(greet(person: "Bob", day: "Tuesday"))
Результат: Hello Bob, today is Tuesday.
Порядок параметрів і їх назви мають співпадати з оголошенням функції!!!
![Page 36: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/36.jpg)
Назву параметра можна робити без назви за допомогою символа _, або робити різну
назву параметра і локальної зміної
func greet(_ person: String, on day: String) -> String { return "Hello \(person), today is \(day)." } print(greet("John", on: "Wednesday"))
Результат: Hello John, today is Wednesday.
![Page 37: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/37.jpg)
Функція може не вертати значення
func greet(person: String, day: String) -> Void { print("Hello \(person), today is \(day).") }
greet(person: "Bob", day: "Tuesday")
Результат: Hello Bob, today is Tuesday.
![Page 38: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/38.jpg)
Функція може вертати кортежfunc calculateStatistics(scores: [Int]) ->
(min: Int, max: Int, sum: Int) { var min = scores[0] var max = scores[0] var sum = 0 for score in scores { if score > max { max = score } if score < min { min = score } sum += score } return (min, max, sum) } let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9]) print(statistics.min) print(statistics.sum) print(statistics.2)
Результат: 3 120 120
![Page 39: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/39.jpg)
Функція може приймати декілька параметрів одного типу і додавати їх в масив
func sumOf(numbers: Int...) -> Int { print(type(of:numbers)) var sum = 0 for number in numbers { sum += number } return sum } print(sumOf()) print(sumOf(numbers: 42, 597, 12))
Результат: Array<Int> 0 Array<Int> 651
![Page 40: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/40.jpg)
Лише один параметр може приймати список значень
func dump(other: Any...) -> Void { for x in other { print("x=\(x)") } } dump(other:"String", ["Item1", "Item2"])
Результат: x=String x=["Item1", "Item2"]
![Page 41: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/41.jpg)
Функції можуть бути вкладені
func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y } print(returnFifteen())
Результат: 15
![Page 42: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/42.jpg)
Вкладені функції можуть використовувати змінні зовнішньої функції навіть після її завершення (ця
властивість називається замикання)func makeIncrementer(val:Int) -> ((Int) -> Int) { func add(number: Int) -> Int { return val + number } return add } var increment10 = makeIncrementer(val:10) var increment5 = makeIncrementer(val:5) print(increment10(7)) print(increment5(7))
Результат: 17 12
![Page 43: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/43.jpg)
Функція може приймати функцію як параметр
func printMatches(list: [Int], condition: (Int) -> Bool) -> Void {
for item in list { if condition(item) { print(item) } } } func lessThanTen(number: Int) -> Bool { return number < 10 } printMatches(list: [20, 19, 7, 12, 5], condition: lessThanTen)
Результат: 7 5
![Page 44: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/44.jpg)
Функції без імені можна описувати у фігурних дужках {}. Є засоби скороченого
запису функцій
var numbers = [20, 19, 7, 12, 5] print(numbers.map({ (number: Int) -> Int in let result = 3 * number return result })) print(numbers.map({ number in 4 * number })) print(numbers.map({ 5 * $0 }))
Результат: [60, 57, 21, 36, 15] [80, 76, 28, 48, 20] [100, 95, 35, 60, 25]
![Page 45: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/45.jpg)
Класи означаються з допомогою ключового слова class
class Shape { var numberOfSides = 0 func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } }
var shape = Shape() shape.numberOfSides = 7 print(shape.simpleDescription())
Результат: A shape with 7 sides.
![Page 46: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/46.jpg)
Конструктор визначається з допомогою ключового слова init
class NamedShape { var numberOfSides: Int = 0 var name: String init(name: String) { self.name = name } func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } }
![Page 47: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/47.jpg)
Наслідуваний клас записується через двокрапку
class Square: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." } } let test = Square(sideLength: 5.2, name: "my test square") test.area() print(test.simpleDescription())
результат: A square with sides of length 5.2.
![Page 48: Lecture 07 swift](https://reader031.vdocument.in/reader031/viewer/2022022413/58ed432b1a28aba35d8b45c3/html5/thumbnails/48.jpg)
Приклад використання Swift - створення додатку для iOS
https://www.youtube.com/watch?v=N-GNV7jhKV4