Академический Документы
Профессиональный Документы
Культура Документы
История
Почему Swift
Программа курса
Введение в Swift
Swift заимствовал идеи из «Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, и
еще из стольких многих языков, что сложно перечислить
Версия Swift 1.0 была выпущена 9 сентября 2014 года, вместе с «Gold Master»
версией Xcode 6.0 для iOS.
8 июня 2015 года компания Apple объявила о выпуске новой версии Swift 2.0,
которая получила более высокую производительность
История
3 декабря 2015 года была выпущена бета версия Swift 3.0 с поддержкой
операционных систем OS X, iOS и Linux и лицензированная под открытой
лицензий Apache 2.0 license и с Runtime Library Exception
Для достижения этой цели разработчики считают, что написание кода на Swift должно
быть:
Второй модуль
Работа с сетью и базой данных. Взаимодействие с сторонними фреймворками.
Архитектура приложения.
Написание итогового приложения
Первый модуль
1. Введение в язык. Коротко о мобильной разработке. Где и как используется Swift.
Знакомство с Xcode. Создание первого приложения.
2. Строки и символы. Опциоанльный тип. Базовые операторы. If. Switch. For.
——————————————
3. Коллекции (массивы, словари, наборы). Функции. Замыкания.
4. MVC. Классы, структуры и перечисления. Знакомство с Interface Builder. Создание элементарного
приложения с интерфейсом. IBAction. IBOutlet.
——————————————
5. Работа с интерфейсом. Autolayout, SizeClasses. StackView.
6. Views и их иерархия. Обработка жестов. Путь Безье.
——————————————
7. Расширения. Протоколы и делегирование. UIScrollView. Обработка ошибок.
8. Управление памятью. Замыкания. Углубление в Array, Set, Dictionary. Углубление в Xcode,
Debbuger
——————————————
9. Работа с элементами интерфейса. UIViewController. UIButton, UILabel, UITextField, Segues,
UITextView.
10. Таблицы. UITableView, UITableVIewController. UICollectionView.
——————————————
11. Навигация приложения. UISplitViewController,UITabBarController
12. Навигация приложения. Navigation Controller.
——————————————
13. Работа в команде. Git.
14. Alerts, Работа с сетью.
——————————————
15. Мультипоточность и асинхронность.
16. Повторение.
Второй модуль
17. CoreData. Введение.
18. CoreData. Работа с данными.
——————————————
19. Анимация.
20. Акселерометр и гироскоп. CoreMotion.
——————————————
21. Локализация и интернационализация
приложения.
22. Оповещения. Работа с различными сервисами.
——————————————
23. Работа с соцсетями. Работа с документацией.
24. CocoaPods. Использование. Коротко о
полезных библиотеках.
——————————————
25. UITableView. Углубление.
26. Мультимедиа: фото, музыка, видео.
——————————————
27. Паттерны проектирования.
28-32. Подведение итогов. Написание итогового
приложения.
Что такое iOS
Патерны
MVC
проектирования
Учебные материалы
Swift
https://developer.apple.com/library/content/documentation/Swift/
Conceptual/Swift_Programming_Language/
iOS
https://developer.apple.com/develop/
Куда бежать?
http://stackoverflow.com/questions/tagged/ios
http://stackoverflow.com/questions/tagged/swift
Туториалы
https://www.raywenderlich.com
http://nshipster.com
Демо
Hello World!
Playground
! константы и переменные
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
welcomeMessage = "Hello"
numberOfStoplights += 2
let townDescription =
"\(townName) has a population of \(population) and \
(numberOfStoplights) stoplights.»
print(townDescription) ‘’
Комментарии
/*Это мультистрочный
комментарий*/
точка с запятой
Float - для 32
let meaningOfLife = 42
// meaningOfLife тип Int
let pi = 3.14159
// pi тип Double
let b = 10
var a = 5
a = b
а c
! Арифметические Операторы
1 + 2 // 3
5 - 3 // 2
2 * 3 // 6
10.0 / 2.5 // 4.0
9 % 4 // равно 1
Унарные минус плюс операторы
let three = 3
let minusThree = -three // minusThree равно -3
let plusThree = -minusThree
// plusThree равно 3, или "минус минус три"
let minusSix = -6
let alsoMinusSix = +minusSix // alsoMinusSix equals -6
++Х++ + --Х--
! Оператор составного присвоения
var a = 1
a += 2
// a теперь 3
! Операторы сравнения
1 == 1 // true
2 != 1 // true
2 > 1 // true
1 < 2 // true
1 >= 1 // true
2 <= 1 // false
a && b || c || !d
(a && b) || c || !d
a && (b || c || !d)
Лекция 2
! if
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32
{
print("It's very cold.")
}
if temperatureInFahrenheit <= 32
{
print("It's very cold")
} else
{
print("It's not that cold")
}
! if
temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32
{
print("It's very cold")
}
else if temperatureInFahrenheit >= 86
{
print("It's really warm")
}
else
{
print("It's not that cold.")
}
Тернарный оператор ?:
if question {
answer1
} else { question ? answer1 : answer2
answer2
}
let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
// rowHeight равно 90
let contentHeight = 40
let hasHeader = true
let rowHeight: Int
if hasHeader {
rowHeight = contentHeight + 50
} else {
rowHeight = contentHeight + 20
}
! For in
let names = ["Anna", "Alex", "Brian", «Jack"]
for _ in 1...power {
answer *= base
}
for i in 0..<count {
print("Person \(i + 1) is called \(names[i])")
}
//0.5…15.25
if emptyString.isEmpty {
print("Nothing to see here")
}
if eAcuteQuestion == combinedEAcuteQuestion {
print("These two strings are considered equal")
}
// Выведет "These two strings are considered equal"
Unicode и Спец символы
\0 \\ \t \n \r \" \’ \u{}
let dollarSign = "\u{24}" // $, Unicode U+0024
let blackHeart = "\u{2665}" // ♥, Unicode U+2665
let sparklingHeart = "\u{1F496}" // 💖, Unicode U+1F496
switch someCharacter {
case "a":
print("The first letter of the alphabet")
case "z":
print("The last letter of the alphabet")
default:
print("Some other character")
}
Switch
let anotherCharacter: String = "a"
switch anotherCharacter {
case "a", "A":
print("The letter A")
default:
print("Not the letter A")
}
Switch
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
let naturalCount: String
switch approximateCount {
case 0:
naturalCount = "no"
case 1..<5:
naturalCount = "a few"
case 5..<12:
naturalCount = "several"
case 12..<100:
naturalCount = "dozens of"
case 100..<1000:
naturalCount = "hundreds of"
default:
naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
Switch
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
print("\(somePoint) is at the origin")
case (_, 0):
print("\(somePoint) is on the x-axis")
case (0, _):
print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
print("\(somePoint) is inside the box")
default:
print("\(somePoint) is outside of the box")
}
// на экране "(1, 1) is inside the box"
Switch
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
switch yetAnotherPoint {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
! Switch
let someCharacter: String = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
print("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
print("\(someCharacter) is a consonant")
default:
print("\(someCharacter) is not a vowel or a consonant")
}
switch stillAnotherPoint {
case (let distance, 0), (0, let distance):
print("On an axis, \(distance) from the origin")
default:
print("Not on an axis")
}
! перенос выполнения
• continue
• break
• fallthrough
• return
• throw
Continue
let numbers: [Int] = [0, 1, 2, 3, 4, 5]
switch anotherCharacter {
case "a", "A":
print("The letter A")
default:
break
}
перенос выполнения
fallthrough
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe
{
case 2, 3, 5, 7, 11, 13, 17, 19:
description += " a prime number, and also"
fallthrough
default:
description += " an integer."
}
print(description)
// "The number 5 is a prime number, and also an integer."
! Optional
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber is inferred to be of type "Int?", or
"optional Int"
if s != nil {
display.text = s
} else {
display.text = “ “
}
... можно записать так ...
display.text = s ?? “ “
Задания
var population : Int - это население города
Вывести на экран тип города (хутор, село, ПГТ, город)
тремя способами в зависимости от значения
переменной.
1. Использовать последовательные if
2. else if конструкция
3. switch