2. 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]
Ω
3.
4. 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.
5. 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
6. Вирази треба відділяти крапкою з
комою, але в кінці рядка крапка з комою
не обов’язкова
Hello world!
Hello world! Hello world!
Hello world!
Hello world!
let x : String = "Hello world!"
print(x);
print(x,x)
print(x); print(x)
10. Коментарі у 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. */
11. Підтримка запису чисел у десятковій,
двійковій, вісімковій і шістнадцятковій
системах числення
let decimalInteger = 17
// 17 in binary notation
let binaryInteger = 0b10001
// 17 in octal notation
let octalInteger = 0o21
// 17 in hexadecimal notation
let hexadecimalInteger = 0x11
12. Тип виразу можна взнати
командою type(of:вираз)
var a = 10
let c = Int("12")
print(type(of:a))
print(type(of:c))
Результат:
Int
Optional<Int>
13. Змінна, яка може набувати значення nil,
має тип Optional. Такий тип створюється
додаванням до типу символа «?»
let nickName: String? = nil
print(nickName)
let s:String = nickName // помилка компіляції
Результат:
Optional<String>
nil
error: value of optional type 'String?' not
unwrapped;
14. При роботі з Optional можна
використовувати оператор ??, щоб
задати значення за замовченням
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi (nickName ?? fullName)"
print(informalGreeting)
Результат:
Hi John Appleseed
15. Приведення типу, яке не завжди дає
результат, має тип 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
16. Декілька змінних одного типу без
ініціалізації можна означити в одному рядку
var red, green, blue: Double
print(type(of:red))
print(type(of:green))
print(type(of:blue))
Результат:
Double
Double
Double
20. let arr = ["Hello", "World"]
print(arr)
print(type(of:arr))
Результат:
["Hello", "World"]
Array<String>
При створенні звичайних і асоціативних
масивів тип може визначатися автоматично
21. Якщо тип змінних у масиві відрізняється,
то тип масиву не можна визначити
автоматично
let arr = ["Hello", 1]
Результат:
Помилка компіляції!!!
22. Але є масив типу Any
let arr : Array <Any> = ["Hello", 1, "2"]
print(arr)
Результат:
["Hello", 1, "2"]
23. Отримати значення зі зміної типу 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).
24. Означення порожніх звичайних
і асоціативних масивів
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>
26. Перебір елементів асоціативного масиву
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
27. Альтернативний метод перебору елементів
асоціативного масиву
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
28. 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
29. Кортежі можуть мати іменовані атрибути
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
30. Оператор 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?
31. 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
32. Цикли while i repeat в Swift
var n = 2
while n < 100 {
n *= 2
}
print(n)
var m = 2
repeat {
m *= 2
} while m < 100
print(m)
Результат:
128
128
33. Цикли 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
34. Важливо! Межі циклу
перевіряються на етапі виконання
var a1 = 1
var b1 = -5
for i in a1...b1 {
print(i)
}
Результат:
fatal error: Can't form Range with upperBound <
lowerBound
35. 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.
Порядок параметрів і їх назви мають співпадати з
оголошенням функції!!!
36. Назву параметра можна робити без назви
за допомогою символа _, або робити різну
назву параметра і локальної зміної
func greet(_ person: String, on day: String) ->
String
{
return "Hello (person), today is (day)."
}
print(greet("John", on: "Wednesday"))
Результат:
Hello John, today is Wednesday.
37. Функція може не вертати значення
func greet(person: String, day: String) -> Void
{
print("Hello (person), today is (day).")
}
greet(person: "Bob", day: "Tuesday")
Результат:
Hello Bob, today is Tuesday.
38. Функція може вертати кортеж
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
39. Функція може приймати декілька параметрів
одного типу і додавати їх в масив
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
40. Лише один параметр може приймати
список значень
func dump(other: Any...) -> Void {
for x in other {
print("x=(x)")
}
}
dump(other:"String", ["Item1", "Item2"])
Результат:
x=String
x=["Item1", "Item2"]
41. Функції можуть бути вкладені
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
print(returnFifteen())
Результат:
15
42. Вкладені функції можуть використовувати змінні
зовнішньої функції навіть після її завершення (ця
властивість називається замикання)
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
43. Функція може приймати функцію як
параметр
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
44. Функції без імені можна описувати у
фігурних дужках {}. Є засоби скороченого
запису функцій
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]
45. Класи означаються з допомогою
ключового слова 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.
46. Конструктор визначається з
допомогою ключового слова 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."
}
}
47. Наслідуваний клас записується через
двокрапку
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.