├── README.md
└── Module 1. Swift
└── Playgrounds
├── video1_8.playground
├── Contents.swift
└── contents.xcplayground
├── video1_10.playground
├── contents.xcplayground
└── Contents.swift
├── video1_11.playground
├── contents.xcplayground
└── Contents.swift
├── video1_12.playground
├── contents.xcplayground
└── Contents.swift
├── video1_13.playground
├── contents.xcplayground
└── Contents.swift
├── video1_14.playground
├── contents.xcplayground
└── Contents.swift
├── video1_15.playground
├── contents.xcplayground
└── Contents.swift
├── video1_17.playground
├── contents.xcplayground
└── Contents.swift
├── video1_3.playground
├── contents.xcplayground
└── Contents.swift
├── video1_4.playground
├── contents.xcplayground
└── Contents.swift
├── video1_5.playground
├── contents.xcplayground
└── Contents.swift
├── video1_6.playground
├── contents.xcplayground
└── Contents.swift
└── video1_9.playground
├── contents.xcplayground
└── Contents.swift
/README.md:
--------------------------------------------------------------------------------
1 | # course1
2 | Курс «Разработка под iOS.Начинаем»
3 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_8.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | struct Car {
4 | let mark: String
5 | let model: String
6 | }
7 |
8 | print(Car(mark: "Bobik Motors", model: "Tuzik"))
9 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_10.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_11.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_12.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_13.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_14.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_15.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_17.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_3.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_4.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_5.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_6.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_8.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_9.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_14.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | let arr1 = [1, 2, 3, 4]
4 | let res1 = arr1.map { $0 + 1 }
5 |
6 | let arr2 = [[1, 2], [3, 4]]
7 | let flat2 = arr2.flatMap { $0 }
8 |
9 | let arr3 = [1, 2, nil, 3, nil, 4, nil, 5]
10 | let res3 = arr3.compactMap { $0 }
11 |
12 | let arr4 = [1, 2, 3, 4]
13 | let sum4 = arr4.reduce(into: 0) { (res, val) in
14 | res += val
15 | }
16 |
17 | let arr5 = [1, 2, 3, 4]
18 | let dict5 = arr5.reduce(into: [:]) { (res, val) in
19 | res[val] = "\(val)"
20 | }
21 |
22 | let res5 = arr5.filter { $0 > 2 }
23 |
24 | let index = arr5.index(of: 3)
25 |
26 | let element = arr5.first { $0 > 2 }
27 |
28 | arr5.forEach { val in
29 | print(val)
30 | }
31 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_13.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | let sayHello = {
4 | print("Hello")
5 | }
6 |
7 | sayHello()
8 |
9 | let greetings1 = { (_ name: String) in
10 | print("Hello, \(name)")
11 | }
12 |
13 | greetings1("Me")
14 |
15 | let greetings2: (String) -> Void = { name in
16 | print("Hello, \(name)")
17 | }
18 |
19 | greetings2("Me")
20 |
21 | let rndUUID = { () -> String in
22 | return UUID().uuidString
23 | }
24 |
25 | class Printer {
26 | func print(_ p: String) {
27 | print(p)
28 | }
29 | }
30 |
31 | var printer = Printer()
32 | let greetings3 = {
33 | printer.print("Hello")
34 | }
35 |
36 | let greetings4 = { [printer] in
37 | printer.print("Hello")
38 | }
39 |
40 | let greetings5 = { [weak printer] in
41 | printer?.print("Hello")
42 | }
43 |
44 | let greetings6 = { [unowned printer] in
45 | printer.print("Hello")
46 | }
47 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_12.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | let array1 = [1, 2, 3, 4]
4 | let array2 = [Int]()
5 | let array3 = Array()
6 |
7 | let array4: [Int] = [1, 2, 3, 4]
8 | let array5: [Int] = [Int]()
9 |
10 | print(array1[0])
11 |
12 | var arraym = [1, 2, 3]
13 | arraym.append(1)
14 | arraym.insert(2, at: 3)
15 | arraym.remove(at: 2)
16 | arraym.removeAll()
17 |
18 | for element in array4 {
19 | print(element)
20 | }
21 |
22 | for (index, element) in arraym.enumerated() {
23 | print(index, " => ", element)
24 | }
25 |
26 | let dict1 = [1: "One", 2: "Two"]
27 | let dict2 = [Int: String]()
28 | let dict3 = Dictionary()
29 |
30 | let dict4: [Int: String] = [1: "One", 2: "Two"]
31 | let dict5: [Int: String] = [Int: String]()
32 |
33 | print(dict1[1])
34 |
35 | var dictm = [1: "One", 2: "Two"]
36 | dictm[3] = "Three"
37 | dictm[3] = nil
38 |
39 | for (key, value) in dictm {
40 | print(key, " => ", value)
41 | }
42 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_17.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 | import UIKit
3 |
4 | let now1 = Date()
5 | let ts = now1.timeIntervalSince1970
6 | let now2 = Date(timeIntervalSince1970: ts)
7 |
8 | let fmt = DateFormatter()
9 | fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
10 | let str = fmt.string(from: now1)
11 | let now3 = fmt.date(from: str)
12 |
13 | let nd = Calendar.current.date(byAdding: .hour, value: 1, to: now1)
14 |
15 | let red = UIColor.red
16 | let green = UIColor.green
17 | let custom = UIColor(red: 34.0 / 255.0, green: 45.0 / 255.0, blue: 245.0 / 255.0, alpha: 1.0)
18 |
19 | var r: CGFloat = 0
20 | var g: CGFloat = 0
21 | var b: CGFloat = 0
22 | var a: CGFloat = 0
23 |
24 | custom.getRed(&r, green: &g, blue: &b, alpha: &a)
25 |
26 | let jsx: [String: Any] = ["one": 1, "two": 2.0, "three": "3"]
27 | do {
28 | let jsdata = try JSONSerialization.data(withJSONObject: jsx, options: [])
29 | let jsdict = try JSONSerialization.jsonObject(with: jsdata, options: [])
30 | print(jsdict)
31 | } catch {
32 | }
33 |
34 | let path = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
35 |
36 | var isDir: ObjCBool = false
37 | let dirurl = path.appendingPathComponent("caches")
38 | if FileManager.default.fileExists(atPath: dirurl.path, isDirectory: &isDir), isDir.boolValue {
39 | }
40 |
41 | try? FileManager.default.createDirectory(at: dirurl, withIntermediateDirectories: true, attributes: nil)
42 |
43 | try? FileManager.default.removeItem(at: dirurl)
44 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_3.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 | import UIKit
3 |
4 | print("Hello, World")
5 | print("Hello") ; print("World")
6 |
7 | let a1 = 10
8 |
9 | var b1 = UIView()
10 | b1 = UIView()
11 |
12 | let a2: Int = 10
13 | var b2: UIView = UIView()
14 |
15 | var something = true
16 | if something {
17 | // делаем что-нибудь
18 | } else {
19 | // делаем что-то другое
20 | }
21 |
22 | var something2 = false
23 | if something {
24 | // делаем что-нибудь
25 | } else if something2 {
26 | // делаем что-нибудь не то
27 | } else {
28 | // делаем что-то другое
29 | }
30 |
31 | for i in 0..<10 {
32 | print("i: ", i)
33 | }
34 |
35 | for i in 0...10 {
36 | print("i: ", i)
37 | }
38 |
39 |
40 | var i1 = 0
41 | while i1 < 10 {
42 | print("i1: ", i1)
43 | i1 += 1 // в Swift нет конструкции i1++
44 | }
45 |
46 | var a3 = 1
47 | // нет a3++
48 | a3 += 1
49 |
50 | var i2 = 0
51 | repeat {
52 | print("i2: ", i2)
53 | i2 += 1
54 | } while i2 < 10
55 |
56 | var array = [1, 2, 3, 4, 10, 100]
57 | for item in array {
58 | print("item: ", item)
59 | }
60 |
61 | // Эта конструкция будет рассматриваться дальше, тут дано лишь для примера и для иллюстрации материала из лекции
62 | enum Errors: Error {
63 | case anyError
64 | }
65 | func doSomething() throws {
66 | throw Errors.anyError
67 | }
68 | do {
69 | try doSomething()
70 | } catch {
71 | print("e: \(error)") // тут конструкция \() подставляет значение переменной в строку, известная как "строковоая интерполяция"
72 | }
73 |
74 |
75 |
76 |
77 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_9.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | enum Planets {
4 | case mercury
5 | case venus
6 | case earth
7 | case mars
8 | case jupiter
9 | case saturn
10 | case uranus
11 | case neptune
12 | // NOTE: sadly, but no Pluto
13 |
14 | var isInnerSolarSystem: Bool {
15 | switch self {
16 | case .mercury, .venus, .earth, .mars: return true
17 | default: return false
18 | }
19 | }
20 |
21 | func distance(to other: Planets) -> Double {
22 | return Double(arc4random())
23 | }
24 | }
25 |
26 | let p1: Planets = .jupiter
27 |
28 | enum Planets_typed: Int {
29 | case mercury = 1
30 | case venus = 2
31 | case earth = 3
32 | case mars = 4
33 | case jupiter = 5
34 | case saturn = 6
35 | case uranus = 7
36 | case neptune = 8
37 | }
38 |
39 | print(Planets_typed.mercury.rawValue)
40 |
41 | enum Result {
42 | case success(data: Data, headers: [String: Any])
43 | case failure(error: Error)
44 |
45 | var rawValue: String {
46 | switch self {
47 | case .success: return "success"
48 | case .failure: return "failure"
49 | }
50 | }
51 | }
52 |
53 | print(Planets.earth.isInnerSolarSystem)
54 | print(Planets.mars.distance(to: .jupiter))
55 |
56 | let res1: Result = .success(data: Data(), headers: [:])
57 | switch res1 {
58 | case let .success(data, headers): print(data, " ", headers)
59 | case let .failure(error): print(error)
60 | }
61 |
62 | enum Errors: Error {
63 | case anyError
64 | }
65 |
66 | let res2: Result = .failure(error: Errors.anyError)
67 | switch res2 {
68 | case let .success(data, headers): print(data, " ", headers)
69 | case let .failure(error): print(error)
70 | }
71 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_10.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | func sumi(lhs: Int, rhs: Int) -> Int {
4 | return lhs + rhs
5 | }
6 |
7 | func sumf(lhs: Float, rhs: Float) -> Float {
8 | return lhs + rhs
9 | }
10 |
11 | func sum(lhs: T, rhs: T) -> T {
12 | return lhs + rhs
13 | }
14 |
15 | print(sum(lhs: 1, rhs: 2)) // 3
16 | print(sum(lhs: 1.5, rhs: 3.5)) // 5.0
17 |
18 | protocol Packable {}
19 | extension String: Packable {}
20 |
21 | struct Pack {
22 | private var storage: [Obj] = []
23 |
24 | mutating func pack(_ obj: Obj) {
25 | storage.append(obj)
26 | }
27 |
28 | mutating func unpack() -> Obj? {
29 | guard !storage.isEmpty else {
30 | return nil
31 | }
32 |
33 | return storage.remove(at: 0)
34 | }
35 | }
36 |
37 | var pack = Pack()
38 |
39 | pack.pack("Drill")
40 | pack.pack("Bolt")
41 | pack.pack("Bolt")
42 |
43 | print(pack.unpack()) // Optional
44 | print(pack.unpack()) // Optional
45 | print(pack.unpack()) // Optional
46 | print(pack.unpack()) // nil
47 |
48 | protocol PackingContainer {
49 | associatedtype Element
50 | mutating func pack(_ obj: Element)
51 | mutating func unpack() -> Element?
52 | }
53 |
54 | struct IntPack: PackingContainer {
55 | typealias Element = Int
56 |
57 | mutating func pack(_ obj: Int) {
58 | //
59 | }
60 |
61 | mutating func unpack() -> Int? {
62 | //
63 | return nil
64 | }
65 | }
66 |
67 | struct FloatPack: PackingContainer {
68 | // typealias Element будет выведен автоматически
69 |
70 | mutating func pack(_ obj: Float) {
71 | //
72 | }
73 |
74 | mutating func unpack() -> Float? {
75 | //
76 | return nil
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_5.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 | import UIKit
3 |
4 | var thing: String = "Hello"
5 |
6 | var maybeThing: String? = nil
7 | maybeThing = "Hello"
8 |
9 | var view1 = UIView()
10 | print(view1.frame)
11 |
12 | var view2: UIView?
13 | var view3: Optional
14 |
15 | var frame2 = view2?.frame
16 | var frame3 = view3?.frame
17 |
18 | // var frame2fo = view2!.frame // раскомментируйте чтобы увидеть крэш
19 | // var frame3fo = view3!.frame // раскомментируйте чтобы увидеть крэш
20 |
21 | var view4: UIView? = nil
22 | var view5: UIView? = UIView()
23 |
24 | var f4 = view4?.frame // nil
25 | var f5 = view5?.frame // Optional
26 |
27 | // var f4fo = view4!.frame // раскомментируйте чтобы увидеть крэш
28 | var f5fo = view5!.frame // frame
29 |
30 | if let view = view2 {
31 | print("view: ", view)
32 | }
33 |
34 | if let v4 = view4 {
35 | print("v4: ", v4)
36 | } else {
37 | print("no v4")
38 | }
39 | if let v5 = view5 {
40 | print("v5: ", v5)
41 | } else {
42 | print("no v5")
43 | }
44 |
45 | func wrap() {
46 | guard let v = view4 else {
47 | print("We are in guard else clause")
48 | return
49 | }
50 | print("v: ", v)
51 | }
52 | wrap()
53 |
54 | enum Errors: Error {
55 | case noView
56 | }
57 |
58 | func getFrame(_ view: UIView?) throws -> CGRect {
59 | guard let v = view else {
60 | throw Errors.noView
61 | }
62 | return v.frame
63 | }
64 |
65 | do {
66 | try print("v4 frame: ", getFrame(view4))
67 | } catch {
68 | print("v4 no frame")
69 | }
70 |
71 | do {
72 | try print("v5 frame: ", getFrame(view5))
73 | } catch {
74 | print("v5 no frame")
75 | }
76 |
77 | func getFrame_bad(_ view: UIView?) throws -> CGRect {
78 | if let v = view {
79 | return v.frame
80 | } else {
81 | throw Errors.noView
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_11.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 | import CoreGraphics // для структуры CGPoint
3 |
4 | protocol Vehicle {
5 | var isMoving: Bool { get }
6 | var name: String { get set }
7 | func move(to pos: CGPoint) -> Bool
8 | }
9 |
10 | class Car : Vehicle {
11 | var isMoving: Bool = true
12 | var name: String = "basic car"
13 | var position: CGPoint = .zero
14 |
15 | func move(to pos: CGPoint) -> Bool {
16 | self.position = pos
17 | return true
18 | }
19 | }
20 |
21 | protocol Soldier {
22 | associatedtype Weapon
23 | var weapon: Weapon { get }
24 | }
25 |
26 | class Machinegun {}
27 | class Trooper : Soldier {
28 | var weapon: Machinegun = Machinegun()
29 | }
30 |
31 | class SnipperRiffle {}
32 | class Sniper : Soldier {
33 | typealias Weapon = SnipperRiffle
34 |
35 | var weapon: SnipperRiffle = SnipperRiffle()
36 | }
37 |
38 | extension String {
39 | func md5() -> String {
40 | // реализация md5
41 | return "" // реализация md5 не входит сюда, можете написать самостоятельно
42 | }
43 | }
44 |
45 | enum Planets {
46 | case mercury
47 | case venus
48 | case earth
49 | case mars
50 | case jupyter
51 | case saturn
52 | case neptune
53 | case uranus
54 | // no Pluto :(
55 | }
56 |
57 | private extension Planets {
58 | var diameter: Double {
59 | switch self {
60 | case .mercury: return 12432
61 | case .venus: return 2452
62 | case .earth: return 292394
63 | case .mars: return 2324
64 | case .jupyter: return 2984208428
65 | case .saturn: return 244245
66 | case .neptune: return 2342
67 | case .uranus: return 28488
68 | }
69 | }
70 | }
71 |
72 | protocol Packable {}
73 | struct Pack {
74 | //
75 | }
76 | extension String: Packable {}
77 |
78 |
79 |
80 |
81 |
82 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_6.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | // Дано для иллюстрации
4 | struct Location {
5 | let lat: Double
6 | let lon: Double
7 | }
8 |
9 | // Дано для иллюстрации, не пытайтесь понять смысл :)
10 | class Press {
11 | static func crash(_ obj: Any) {
12 | // разделить на ноль !
13 | }
14 | }
15 |
16 | class Car {
17 | let mark: String
18 | let model: String
19 | public var mileage: Int
20 | static let steelType: Int = 25
21 | class var productionAmount: Int {
22 | return 100500
23 | }
24 | private var owner: String = "Pupkin"
25 | private(set) var guardian: String = "Sentinel"
26 | fileprivate var uid: String = UUID().uuidString
27 |
28 | var buyDate: Date = Date()
29 | var buyTimestamp: TimeInterval {
30 | set { buyDate = Date(timeIntervalSince1970: newValue) }
31 | get { return buyDate.timeIntervalSince1970 }
32 | }
33 |
34 | var sellDate: Date = Date()
35 | var ownTime: TimeInterval {
36 | return sellDate.timeIntervalSince(buyDate)
37 | }
38 |
39 | func drive(to: Location) -> Bool {
40 | guard abs(to.lat) > 0 && abs(to.lon) > 0 else {
41 | return false
42 | }
43 |
44 | // едем в to
45 |
46 | return true
47 | }
48 |
49 | static func search(model: String) -> Car {
50 | if model == "Tuzik" {
51 | return Car(mark: "Bobik Motors", model: model)
52 | }
53 |
54 | return Car()
55 | }
56 |
57 | init(mark: String, model: String, mileage: Int = 0) {
58 | self.mark = mark
59 | self.model = model
60 | self.mileage = mileage
61 | // super.init() // эта конструкция нужна, если у вас есть суперкласс, для корневых классов не надо
62 | }
63 |
64 | convenience init() {
65 | self.init(mark: "Bobik Motors", model: "Tuzik")
66 | }
67 |
68 | deinit {
69 | Press.crash(self) // =]
70 | }
71 | }
72 |
73 | let car: Car = Car()
74 | print(car.model)
75 | car.mileage += 1
76 |
77 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_4.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | func foo1() {
4 | // не делаем ничего :(
5 | }
6 |
7 | func foo2() -> Int {
8 | return 1
9 | }
10 | print(foo2())
11 |
12 | func say1(p: String) {
13 | print(p)
14 | }
15 | say1(p: "Hello, World")
16 |
17 | func say2(phrase p: String) {
18 | print(p)
19 | }
20 | say2(phrase: "Hello, World")
21 |
22 | func say3(_ p: String) {
23 | print(p)
24 | }
25 | say3("Hello, World")
26 |
27 | func sum(lhs: Int, rhs: Int) -> Int {
28 | return lhs + rhs
29 | }
30 | print(sum(lhs: 1, rhs: 1))
31 |
32 | func sub(lhs: Int = 0, rhs: Int = 0) -> Int {
33 | return lhs - rhs
34 | }
35 | print(sub())
36 | print(sub(lhs: 1))
37 | print(sub(rhs: 1))
38 | print(sub(lhs: 1, rhs: 1))
39 |
40 | func two(a: Int) -> String? { // тут String? со знаком вопроса это правильно, это Optional которые будут рассмотрены позднее
41 | guard a == 2 else {
42 | return nil
43 | }
44 | return "two"
45 | }
46 |
47 | // Этот класс тут для того, чтобы код собирался, классы будут рассмотрены позднее
48 | class Door {
49 | func open() {
50 | //
51 | }
52 |
53 | func close() {
54 | //
55 | }
56 | }
57 |
58 | func openTheDoor_bad(condition1: Bool, condition2: Bool) {
59 | let door = Door()
60 | door.open()
61 |
62 | if condition1 {
63 | door.close()
64 | return
65 | }
66 |
67 | // тут много разного кода
68 |
69 | if condition2 {
70 | // тут забыли сделать door.close()
71 | return
72 | }
73 |
74 | // тут много разного кода
75 |
76 | door.close()
77 | }
78 |
79 | func openTheDoor_good(condition1: Bool, condition2: Bool) {
80 | let door = Door()
81 | door.open()
82 | defer { door.close() }
83 |
84 | if condition1 {
85 | // тут не надо door.close()
86 | return
87 | }
88 |
89 | // тут много разного кода
90 |
91 | if condition2 {
92 | // тут не надо door.close()
93 | return
94 | }
95 |
96 | // тут много разного кода
97 |
98 | // тут не надо door.close()
99 | }
100 |
101 | // Перечисления (enum) будут детально рассмотрены позднее
102 | enum OurErrors: Error {
103 | case somethingBadHappened
104 | }
105 | func doSomething() throws -> Void {
106 | throw OurErrors.somethingBadHappened
107 | }
108 |
109 |
--------------------------------------------------------------------------------
/Module 1. Swift/Playgrounds/video1_15.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | let a = 1
4 | switch a {
5 | case 1: print("1")
6 | case 2: fallthrough
7 | case 3: print("More than one")
8 | default: break
9 | }
10 |
11 | let ab: Bool = true
12 | let bb: Bool = false
13 |
14 | switch (ab, bb) {
15 | case (false, false): print("0")
16 | case (false, true): print("1")
17 | case (true, false): print("2")
18 | case (true, true): print("3")
19 | }
20 |
21 | let p: String? = "Hello, World"
22 |
23 | switch p {
24 | case _?: print("Value!")
25 | case nil: print("No Value!")
26 | }
27 |
28 | switch p {
29 | case .some: print("Value!")
30 | case .none: print("No Value!")
31 | }
32 |
33 | let val = (15, "example", 3.14)
34 | switch val {
35 | case (_, _, let pi): print("pi: \(pi)")
36 | }
37 |
38 | switch (4, 5) {
39 | case let (x, y): print("We are at \(x) \(y)")
40 | }
41 |
42 | let age = 13
43 | let job: String? = "Worker"
44 | let userInfo: AnyObject = NSDictionary()
45 |
46 | switch (age, job, userInfo) {
47 | case (let age, _?, _ as NSDictionary): print("OK, age: ", age)
48 | default: break
49 | }
50 |
51 | enum Entities {
52 | case soldier(x: Int, y: Int)
53 | case player(x: Int, y: Int)
54 | case tank(x: Int, y: Int)
55 | }
56 |
57 | let entities: [Entities] = [
58 | .tank(x: 1, y: 1),
59 | .player(x: 2, y: 3)
60 | ]
61 |
62 | for e in entities {
63 | switch e {
64 | case let .soldier(x, y): print("S at \(x) \(y)")
65 | case .player(let x, let y): print("P at \(x) \(y)")
66 | default: break
67 | }
68 | }
69 |
70 | let ax: Any = 5
71 |
72 | switch ax {
73 | case is Int: print("Hurray, Int!")
74 | default: break
75 | }
76 |
77 | switch ax {
78 | case let n as Int: print("Int: \(n)")
79 | default: break
80 | }
81 |
82 | switch 5 {
83 | case 0...10: print("0-10")
84 | default: break
85 | }
86 |
87 | struct Soldier {
88 | let hp: Int
89 | let x: Int
90 | let y: Int
91 | }
92 |
93 | func ~= (pattern: Int, value: Soldier) -> Bool {
94 | return pattern == value.hp
95 | }
96 |
97 | let soldier = Soldier(hp: 0, x: 0, y: 0)
98 | switch soldier {
99 | case 0: print("Dead soldier")
100 | default: break
101 | }
102 |
103 | func fibonacci(_ i: Int) -> Int {
104 | switch(i) {
105 | case let n where n <= 0: return 0
106 | case 0, 1: return 1
107 | case let n: return fibonacci(n - 1) + fibonacci(n - 2)
108 | }
109 | }
110 | print(fibonacci(10))
111 |
--------------------------------------------------------------------------------