SlideShare uma empresa Scribd logo
1 de 48
Baixar para ler offline
Lecture 07. Swift
Lviv Polytechnic National University
M.V.Davydov
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]
Ω
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.
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
Вирази треба відділяти крапкою з
комою, але в кінці рядка крапка з комою
не обов’язкова
Hello world!
Hello world! Hello world!
Hello world!
Hello world!
let x : String = "Hello world!"
print(x);
print(x,x)
print(x); print(x)
var вводить змінну
let — константу
Тип змінної або задається явно,
або визначається автоматично
Swift підтримує Unicode не
лише всередині стрічок
Коментарі у 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. */
Підтримка запису чисел у десятковій,
двійковій, вісімковій і шістнадцятковій
системах числення
let decimalInteger = 17
// 17 in binary notation
let binaryInteger = 0b10001
// 17 in octal notation
let octalInteger = 0o21
// 17 in hexadecimal notation
let hexadecimalInteger = 0x11
Тип виразу можна взнати
командою type(of:вираз)
var a = 10
let c = Int("12")
print(type(of:a))
print(type(of:c))
Результат:
Int
Optional<Int>
Змінна, яка може набувати значення nil,
має тип Optional. Такий тип створюється
додаванням до типу символа «?»
let nickName: String? = nil
print(nickName)
let s:String = nickName // помилка компіляції
Результат:
Optional<String>
nil
error: value of optional type 'String?' not
unwrapped;
При роботі з Optional можна
використовувати оператор ??, щоб
задати значення за замовченням
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi (nickName ?? fullName)"
print(informalGreeting)
Результат:
Hi John Appleseed
Приведення типу, яке не завжди дає
результат, має тип 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
Декілька змінних одного типу без
ініціалізації можна означити в одному рядку
var red, green, blue: Double
print(type(of:red))
print(type(of:green))
print(type(of:blue))
Результат:
Double
Double
Double
Для приведення типу використовується
конструкція тип(вираз)
Є зручна форма для
форматування стрічки (вираз)
При створенні звичайних і асоціативних
масивів тип може визначатися автоматично
let arr = ["Hello", "World"]
print(arr)
print(type(of:arr))
Результат:
["Hello", "World"]
Array<String>
При створенні звичайних і асоціативних
масивів тип може визначатися автоматично
Якщо тип змінних у масиві відрізняється,
то тип масиву не можна визначити
автоматично
let arr = ["Hello", 1]
Результат:
Помилка компіляції!!!
Але є масив типу Any
let arr : Array <Any> = ["Hello", 1, "2"]
print(arr)
Результат:
["Hello", 1, "2"]
Отримати значення зі зміної типу 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).
Означення порожніх звичайних
і асоціативних масивів
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>
Перебір елементів масиву
Перебір елементів асоціативного масиву
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
Альтернативний метод перебору елементів
асоціативного масиву
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
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
Кортежі можуть мати іменовані атрибути
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
Оператор 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?
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
Цикли 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
Цикли 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
Важливо! Межі циклу
перевіряються на етапі виконання
var a1 = 1
var b1 = -5
for i in a1...b1 {
print(i)
}
Результат:
fatal error: Can't form Range with upperBound <
lowerBound
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.
Порядок параметрів і їх назви мають співпадати з
оголошенням функції!!!
Назву параметра можна робити без назви
за допомогою символа _, або робити різну
назву параметра і локальної зміної
func greet(_ person: String, on day: String) ->
String
{
return "Hello (person), today is (day)."
}
print(greet("John", on: "Wednesday"))
Результат:
Hello John, today is Wednesday.
Функція може не вертати значення
func greet(person: String, day: String) -> Void
{
print("Hello (person), today is (day).")
}
greet(person: "Bob", day: "Tuesday")
Результат:
Hello Bob, today is Tuesday.
Функція може вертати кортеж
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
Функція може приймати декілька параметрів
одного типу і додавати їх в масив
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
Лише один параметр може приймати
список значень
func dump(other: Any...) -> Void {
for x in other {
print("x=(x)")
}
}
dump(other:"String", ["Item1", "Item2"])
Результат:
x=String
x=["Item1", "Item2"]
Функції можуть бути вкладені
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
print(returnFifteen())
Результат:
15
Вкладені функції можуть використовувати змінні
зовнішньої функції навіть після її завершення (ця
властивість називається замикання)
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
Функція може приймати функцію як
параметр
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
Функції без імені можна описувати у
фігурних дужках {}. Є засоби скороченого
запису функцій
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]
Класи означаються з допомогою
ключового слова 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.
Конструктор визначається з
допомогою ключового слова 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."
}
}
Наслідуваний клас записується через
двокрапку
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.
Приклад використання Swift
- створення додатку для iOS
https://www.youtube.com/watch?v=N-GNV7jhKV4

Mais conteúdo relacionado

Mais procurados

урок 19 цикли Складання програм
урок 19 цикли Складання програмурок 19 цикли Складання програм
урок 19 цикли Складання програмHelen Pat
 
урок 11 виведення значень мова Паскаль
урок 11 виведення значень мова Паскальурок 11 виведення значень мова Паскаль
урок 11 виведення значень мова ПаскальHelen Pata
 
урок 12 вирази мова Паскаль
урок 12 вирази  мова Паскальурок 12 вирази  мова Паскаль
урок 12 вирази мова ПаскальHelen Pata
 
урок 15 умова паскаль
урок 15 умова паскальурок 15 умова паскаль
урок 15 умова паскальHelen Pat
 
урок 17 поліваріантне розгалуження
урок 17 поліваріантне розгалуженняурок 17 поліваріантне розгалуження
урок 17 поліваріантне розгалуженняHelen Pata
 
Pascal osnovu
Pascal osnovuPascal osnovu
Pascal osnovuEscuela
 
Unit1 summary
Unit1 summaryUnit1 summary
Unit1 summaryeleksdev
 
практ 1 копия
практ 1   копияпракт 1   копия
практ 1 копияcit-cit
 
лекц2 невизн інт
лекц2 невизн інтлекц2 невизн інт
лекц2 невизн інтcit-cit
 
Уроки 31-38 (лінійне пр) - вправи
Уроки 31-38 (лінійне пр) -  вправиУроки 31-38 (лінійне пр) -  вправи
Уроки 31-38 (лінійне пр) - вправиЮлія Артюх
 
Уроки 42-45 (цикли) - вправи
Уроки 42-45 (цикли) -  вправиУроки 42-45 (цикли) -  вправи
Уроки 42-45 (цикли) - вправиЮлія Артюх
 
Основи мови Ci
Основи мови CiОснови мови Ci
Основи мови CiEscuela
 
Уроки 39-41 (розгалуження) - вправи
Уроки 39-41 (розгалуження) -  вправиУроки 39-41 (розгалуження) -  вправи
Уроки 39-41 (розгалуження) - вправиЮлія Артюх
 
Pascal osnovu2
Pascal osnovu2Pascal osnovu2
Pascal osnovu2Escuela
 

Mais procurados (20)

урок 19 цикли Складання програм
урок 19 цикли Складання програмурок 19 цикли Складання програм
урок 19 цикли Складання програм
 
урок 11 виведення значень мова Паскаль
урок 11 виведення значень мова Паскальурок 11 виведення значень мова Паскаль
урок 11 виведення значень мова Паскаль
 
Pascal основи програмування частина 1
Pascal основи програмування частина 1Pascal основи програмування частина 1
Pascal основи програмування частина 1
 
Ppp
PppPpp
Ppp
 
урок 12 вирази мова Паскаль
урок 12 вирази  мова Паскальурок 12 вирази  мова Паскаль
урок 12 вирази мова Паскаль
 
урок 15 умова паскаль
урок 15 умова паскальурок 15 умова паскаль
урок 15 умова паскаль
 
урок 17 поліваріантне розгалуження
урок 17 поліваріантне розгалуженняурок 17 поліваріантне розгалуження
урок 17 поліваріантне розгалуження
 
cpp-2013 #19 Concurrency
cpp-2013 #19 Concurrencycpp-2013 #19 Concurrency
cpp-2013 #19 Concurrency
 
cpp-2013 #20 Best practices
cpp-2013 #20 Best practicescpp-2013 #20 Best practices
cpp-2013 #20 Best practices
 
Pascal основи програмування частина 2
Pascal основи програмування частина 2Pascal основи програмування частина 2
Pascal основи програмування частина 2
 
Pascal osnovu
Pascal osnovuPascal osnovu
Pascal osnovu
 
Unit1 summary
Unit1 summaryUnit1 summary
Unit1 summary
 
практ 1 копия
практ 1   копияпракт 1   копия
практ 1 копия
 
лекц2 невизн інт
лекц2 невизн інтлекц2 невизн інт
лекц2 невизн інт
 
+5 розгал в с++
+5 розгал в с+++5 розгал в с++
+5 розгал в с++
 
Уроки 31-38 (лінійне пр) - вправи
Уроки 31-38 (лінійне пр) -  вправиУроки 31-38 (лінійне пр) -  вправи
Уроки 31-38 (лінійне пр) - вправи
 
Уроки 42-45 (цикли) - вправи
Уроки 42-45 (цикли) -  вправиУроки 42-45 (цикли) -  вправи
Уроки 42-45 (цикли) - вправи
 
Основи мови Ci
Основи мови CiОснови мови Ci
Основи мови Ci
 
Уроки 39-41 (розгалуження) - вправи
Уроки 39-41 (розгалуження) -  вправиУроки 39-41 (розгалуження) -  вправи
Уроки 39-41 (розгалуження) - вправи
 
Pascal osnovu2
Pascal osnovu2Pascal osnovu2
Pascal osnovu2
 

Destaque

Lecture 06. iOS Programming. Основи Objective-C
Lecture 06. iOS Programming. Основи Objective-CLecture 06. iOS Programming. Основи Objective-C
Lecture 06. iOS Programming. Основи Objective-CMaksym Davydov
 
Lecture 04. Mobile App Design
Lecture 04. Mobile App DesignLecture 04. Mobile App Design
Lecture 04. Mobile App DesignMaksym Davydov
 
Lecture 03 Mobile App Design. Feature Development
Lecture 03 Mobile App Design. Feature DevelopmentLecture 03 Mobile App Design. Feature Development
Lecture 03 Mobile App Design. Feature DevelopmentMaksym Davydov
 
Lecture 05. UI programming for Mobile Apps
Lecture 05. UI programming for Mobile AppsLecture 05. UI programming for Mobile Apps
Lecture 05. UI programming for Mobile AppsMaksym Davydov
 
iOS intro to 3D graphics with Metal
iOS intro to 3D graphics with MetaliOS intro to 3D graphics with Metal
iOS intro to 3D graphics with MetalSigmapoint
 
GPU Programming: Chicago CocoaConf 2015
GPU Programming: Chicago CocoaConf 2015GPU Programming: Chicago CocoaConf 2015
GPU Programming: Chicago CocoaConf 2015Janie Clayton
 
iOS & Android Dev in C# & Visual Studio using Xamarin
iOS & Android Dev in C# & Visual Studio using XamariniOS & Android Dev in C# & Visual Studio using Xamarin
iOS & Android Dev in C# & Visual Studio using XamarinNish Anil
 
New Technology Lecture L11 Connecting People
New Technology Lecture L11 Connecting PeopleNew Technology Lecture L11 Connecting People
New Technology Lecture L11 Connecting PeopleÓlafur Andri Ragnarsson
 
CG requiremnets for banks in tanzania
CG requiremnets for banks in tanzaniaCG requiremnets for banks in tanzania
CG requiremnets for banks in tanzaniaKassim Hussein
 
Workhsop on Logic Building for Programming
Workhsop on Logic Building for ProgrammingWorkhsop on Logic Building for Programming
Workhsop on Logic Building for ProgrammingAdarsh Patel
 
Optimizing apps for better performance extended
Optimizing apps for better performance extended Optimizing apps for better performance extended
Optimizing apps for better performance extended Elif Boncuk
 
Optimizing Apps for Better Performance
Optimizing Apps for Better PerformanceOptimizing Apps for Better Performance
Optimizing Apps for Better PerformanceElif Boncuk
 
Project Analysis - How to Start Project Develoment
Project Analysis - How to Start Project DevelomentProject Analysis - How to Start Project Develoment
Project Analysis - How to Start Project DevelomentAdarsh Patel
 
Workshop on Search Engine Optimization
Workshop on Search Engine OptimizationWorkshop on Search Engine Optimization
Workshop on Search Engine OptimizationAdarsh Patel
 
Openstack Swift overview
Openstack Swift overviewOpenstack Swift overview
Openstack Swift overview어형 이
 
Hack'n Break Android Workshop
Hack'n Break Android WorkshopHack'n Break Android Workshop
Hack'n Break Android WorkshopElif Boncuk
 
Overview of DroidCon UK 2015
Overview of DroidCon UK 2015 Overview of DroidCon UK 2015
Overview of DroidCon UK 2015 Elif Boncuk
 

Destaque (20)

Lecture 06. iOS Programming. Основи Objective-C
Lecture 06. iOS Programming. Основи Objective-CLecture 06. iOS Programming. Основи Objective-C
Lecture 06. iOS Programming. Основи Objective-C
 
Lecture 08 Xamarin
Lecture 08 XamarinLecture 08 Xamarin
Lecture 08 Xamarin
 
Lecture 04. Mobile App Design
Lecture 04. Mobile App DesignLecture 04. Mobile App Design
Lecture 04. Mobile App Design
 
Lecture 03 Mobile App Design. Feature Development
Lecture 03 Mobile App Design. Feature DevelopmentLecture 03 Mobile App Design. Feature Development
Lecture 03 Mobile App Design. Feature Development
 
Lecture 05. UI programming for Mobile Apps
Lecture 05. UI programming for Mobile AppsLecture 05. UI programming for Mobile Apps
Lecture 05. UI programming for Mobile Apps
 
iOS intro to 3D graphics with Metal
iOS intro to 3D graphics with MetaliOS intro to 3D graphics with Metal
iOS intro to 3D graphics with Metal
 
GPU Programming: Chicago CocoaConf 2015
GPU Programming: Chicago CocoaConf 2015GPU Programming: Chicago CocoaConf 2015
GPU Programming: Chicago CocoaConf 2015
 
iOS & Android Dev in C# & Visual Studio using Xamarin
iOS & Android Dev in C# & Visual Studio using XamariniOS & Android Dev in C# & Visual Studio using Xamarin
iOS & Android Dev in C# & Visual Studio using Xamarin
 
OpenStack Swift
OpenStack SwiftOpenStack Swift
OpenStack Swift
 
New Technology Lecture L11 Connecting People
New Technology Lecture L11 Connecting PeopleNew Technology Lecture L11 Connecting People
New Technology Lecture L11 Connecting People
 
CG requiremnets for banks in tanzania
CG requiremnets for banks in tanzaniaCG requiremnets for banks in tanzania
CG requiremnets for banks in tanzania
 
Workhsop on Logic Building for Programming
Workhsop on Logic Building for ProgrammingWorkhsop on Logic Building for Programming
Workhsop on Logic Building for Programming
 
Optimizing apps for better performance extended
Optimizing apps for better performance extended Optimizing apps for better performance extended
Optimizing apps for better performance extended
 
App indexing api
App indexing apiApp indexing api
App indexing api
 
Optimizing Apps for Better Performance
Optimizing Apps for Better PerformanceOptimizing Apps for Better Performance
Optimizing Apps for Better Performance
 
Project Analysis - How to Start Project Develoment
Project Analysis - How to Start Project DevelomentProject Analysis - How to Start Project Develoment
Project Analysis - How to Start Project Develoment
 
Workshop on Search Engine Optimization
Workshop on Search Engine OptimizationWorkshop on Search Engine Optimization
Workshop on Search Engine Optimization
 
Openstack Swift overview
Openstack Swift overviewOpenstack Swift overview
Openstack Swift overview
 
Hack'n Break Android Workshop
Hack'n Break Android WorkshopHack'n Break Android Workshop
Hack'n Break Android Workshop
 
Overview of DroidCon UK 2015
Overview of DroidCon UK 2015 Overview of DroidCon UK 2015
Overview of DroidCon UK 2015
 

Semelhante a Lecture 07 swift

02 Copying Objects
02 Copying Objects02 Copying Objects
02 Copying Objectsolegapster
 
09 Static Polymorphism
09 Static Polymorphism09 Static Polymorphism
09 Static Polymorphismolegapster
 
Mka python jr-urok_07_ua_1563258932
Mka python jr-urok_07_ua_1563258932Mka python jr-urok_07_ua_1563258932
Mka python jr-urok_07_ua_1563258932PavloTsiura
 
алфавіт мови програмування Pascal 14
алфавіт мови програмування Pascal 14алфавіт мови програмування Pascal 14
алфавіт мови програмування Pascal 14zero1996
 
Основи алгоритмізації та програмування. Лекція 1
Основи алгоритмізації та програмування. Лекція 1Основи алгоритмізації та програмування. Лекція 1
Основи алгоритмізації та програмування. Лекція 1Dmitry Chabanenko
 
Programuvanna na movi_pascal
Programuvanna na movi_pascalProgramuvanna na movi_pascal
Programuvanna na movi_pascal1cana1
 
Play Mongodb
Play MongodbPlay Mongodb
Play MongodbInfinity
 
Gamedev Mixer. Лев Лукомський "Розробка власного 2D-редактора рівнів на Unity"
Gamedev Mixer. Лев Лукомський "Розробка власного 2D-редактора рівнів на Unity"Gamedev Mixer. Лев Лукомський "Розробка власного 2D-редактора рівнів на Unity"
Gamedev Mixer. Лев Лукомський "Розробка власного 2D-редактора рівнів на Unity"Lviv Startup Club
 
11 Iterated Containers
11 Iterated Containers11 Iterated Containers
11 Iterated Containersolegapster
 
Знайомство з програмуванням на мові C++
Знайомство з програмуванням на мові C++Знайомство з програмуванням на мові C++
Знайомство з програмуванням на мові C++Alexander Kuzmenko
 
"Is there life in react without redux" by Babich Sergiy. OdessaJS'2021
"Is there life in react without redux" by Babich Sergiy. OdessaJS'2021"Is there life in react without redux" by Babich Sergiy. OdessaJS'2021
"Is there life in react without redux" by Babich Sergiy. OdessaJS'2021OdessaJS Conf
 
Programuvanna na movi_pascal
Programuvanna na movi_pascalProgramuvanna na movi_pascal
Programuvanna na movi_pascalAnn Eres
 

Semelhante a Lecture 07 swift (20)

05 Arrays
05 Arrays05 Arrays
05 Arrays
 
Clean code (UA)
Clean code (UA)Clean code (UA)
Clean code (UA)
 
Less37
Less37Less37
Less37
 
02 Copying Objects
02 Copying Objects02 Copying Objects
02 Copying Objects
 
09 Static Polymorphism
09 Static Polymorphism09 Static Polymorphism
09 Static Polymorphism
 
Mka python jr-urok_07_ua_1563258932
Mka python jr-urok_07_ua_1563258932Mka python jr-urok_07_ua_1563258932
Mka python jr-urok_07_ua_1563258932
 
алфавіт мови програмування Pascal 14
алфавіт мови програмування Pascal 14алфавіт мови програмування Pascal 14
алфавіт мови програмування Pascal 14
 
Основи алгоритмізації та програмування. Лекція 1
Основи алгоритмізації та програмування. Лекція 1Основи алгоритмізації та програмування. Лекція 1
Основи алгоритмізації та програмування. Лекція 1
 
08 Functions
08 Functions08 Functions
08 Functions
 
+1 вступ
+1 вступ+1 вступ
+1 вступ
 
Programuvanna na movi_pascal
Programuvanna na movi_pascalProgramuvanna na movi_pascal
Programuvanna na movi_pascal
 
Play Mongodb
Play MongodbPlay Mongodb
Play Mongodb
 
Gamedev Mixer. Лев Лукомський "Розробка власного 2D-редактора рівнів на Unity"
Gamedev Mixer. Лев Лукомський "Розробка власного 2D-редактора рівнів на Unity"Gamedev Mixer. Лев Лукомський "Розробка власного 2D-редактора рівнів на Unity"
Gamedev Mixer. Лев Лукомський "Розробка власного 2D-редактора рівнів на Unity"
 
07 Containers
07 Containers07 Containers
07 Containers
 
Povtor 7 8kl
Povtor 7 8klPovtor 7 8kl
Povtor 7 8kl
 
11 Iterated Containers
11 Iterated Containers11 Iterated Containers
11 Iterated Containers
 
Знайомство з програмуванням на мові C++
Знайомство з програмуванням на мові C++Знайомство з програмуванням на мові C++
Знайомство з програмуванням на мові C++
 
"Is there life in react without redux" by Babich Sergiy. OdessaJS'2021
"Is there life in react without redux" by Babich Sergiy. OdessaJS'2021"Is there life in react without redux" by Babich Sergiy. OdessaJS'2021
"Is there life in react without redux" by Babich Sergiy. OdessaJS'2021
 
3018 1
3018 13018 1
3018 1
 
Programuvanna na movi_pascal
Programuvanna na movi_pascalProgramuvanna na movi_pascal
Programuvanna na movi_pascal
 

Mais de Maksym Davydov

Microsoft mobile services
Microsoft mobile servicesMicrosoft mobile services
Microsoft mobile servicesMaksym Davydov
 
Mobile app design feature development
Mobile app design feature developmentMobile app design feature development
Mobile app design feature developmentMaksym Davydov
 
Android mix Java and C++
Android mix Java and C++Android mix Java and C++
Android mix Java and C++Maksym Davydov
 
Handler declaration in layout
Handler declaration in layoutHandler declaration in layout
Handler declaration in layoutMaksym Davydov
 
Interface Programming Android
Interface Programming AndroidInterface Programming Android
Interface Programming AndroidMaksym Davydov
 
Android Programming Intro
Android Programming IntroAndroid Programming Intro
Android Programming IntroMaksym Davydov
 
Lecture 02 Mobile hardware
Lecture 02 Mobile hardwareLecture 02 Mobile hardware
Lecture 02 Mobile hardwareMaksym Davydov
 
Lecture 01 Mobile operating systems
Lecture 01 Mobile operating systemsLecture 01 Mobile operating systems
Lecture 01 Mobile operating systemsMaksym Davydov
 
Lecture 12. iOS and Android Animations
Lecture 12. iOS and Android AnimationsLecture 12. iOS and Android Animations
Lecture 12. iOS and Android AnimationsMaksym Davydov
 
Lecture 11. Microsoft mobile services
Lecture 11. Microsoft mobile servicesLecture 11. Microsoft mobile services
Lecture 11. Microsoft mobile servicesMaksym Davydov
 
Lecture 11 Firebase overview
Lecture 11 Firebase overviewLecture 11 Firebase overview
Lecture 11 Firebase overviewMaksym Davydov
 
Lecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile DevicesLecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile DevicesMaksym Davydov
 
Lecture 09 Android Storage
Lecture 09 Android StorageLecture 09 Android Storage
Lecture 09 Android StorageMaksym Davydov
 

Mais de Maksym Davydov (19)

Firebase overview
Firebase overviewFirebase overview
Firebase overview
 
Microsoft mobile services
Microsoft mobile servicesMicrosoft mobile services
Microsoft mobile services
 
Design of mobile apps
Design of mobile appsDesign of mobile apps
Design of mobile apps
 
Mobile app design feature development
Mobile app design feature developmentMobile app design feature development
Mobile app design feature development
 
Android mix Java and C++
Android mix Java and C++Android mix Java and C++
Android mix Java and C++
 
Android animations
Android animationsAndroid animations
Android animations
 
Handler declaration in layout
Handler declaration in layoutHandler declaration in layout
Handler declaration in layout
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
 
Android Storage
Android StorageAndroid Storage
Android Storage
 
Interface Programming Android
Interface Programming AndroidInterface Programming Android
Interface Programming Android
 
Java Small Tests
Java Small TestsJava Small Tests
Java Small Tests
 
Android Programming Intro
Android Programming IntroAndroid Programming Intro
Android Programming Intro
 
Lecture 02 Mobile hardware
Lecture 02 Mobile hardwareLecture 02 Mobile hardware
Lecture 02 Mobile hardware
 
Lecture 01 Mobile operating systems
Lecture 01 Mobile operating systemsLecture 01 Mobile operating systems
Lecture 01 Mobile operating systems
 
Lecture 12. iOS and Android Animations
Lecture 12. iOS and Android AnimationsLecture 12. iOS and Android Animations
Lecture 12. iOS and Android Animations
 
Lecture 11. Microsoft mobile services
Lecture 11. Microsoft mobile servicesLecture 11. Microsoft mobile services
Lecture 11. Microsoft mobile services
 
Lecture 11 Firebase overview
Lecture 11 Firebase overviewLecture 11 Firebase overview
Lecture 11 Firebase overview
 
Lecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile DevicesLecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile Devices
 
Lecture 09 Android Storage
Lecture 09 Android StorageLecture 09 Android Storage
Lecture 09 Android Storage
 

Lecture 07 swift

  • 1. Lecture 07. Swift Lviv Polytechnic National University M.V.Davydov
  • 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)
  • 7. var вводить змінну let — константу
  • 8. Тип змінної або задається явно, або визначається автоматично
  • 9. Swift підтримує Unicode не лише всередині стрічок
  • 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
  • 17. Для приведення типу використовується конструкція тип(вираз)
  • 18. Є зручна форма для форматування стрічки (вираз)
  • 19. При створенні звичайних і асоціативних масивів тип може визначатися автоматично
  • 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.
  • 48. Приклад використання Swift - створення додатку для iOS https://www.youtube.com/watch?v=N-GNV7jhKV4