SwiftUI-Day11 协议

文章目录

  • 吐槽
  • 结果
  • 协议
  • 协议继承性
  • 扩展
  • 协议扩展
  • 面向协议的编程 - Protocol-Oriented Programming

吐槽

Xcode升级,什么appdelegate都没有了,现在全是swiftUI。。。
下面的代码是playground的代码,不是swiftUI View。
参考资料:
https://www.hackingwithswift.com/100/swiftui/11
时间:10 October, 2020

结果

运行快捷键:shift+command+回车
删除当前行:option+D

协议

效果是:displayID函数可以接受任意的具有identifiable属性的对象

protocol Identifiable {
    var id: String { get set }
}
struct User: Identifiable {
    var id: String
}
func displayID(thing: Identifiable) {
    print("My ID is \(thing.id)")
}

协议继承性

protocol Payable {
    func calculateWages() -> Int
}

protocol NeedsTraining {
    func study()
}

protocol HasVacation {
    func takeVacation(days: Int)
}
protocol Employee: Payable, NeedsTraining, HasVacation { }

扩展

extension Int {
    func squared() -> Int {
        return self * self
    }
}
let number = 8
number.squared()

扩展不允许有属性,但是可以用计算过的属性(computed property,这翻译太别扭了,还是自己看原文吧)

extension Int {
    var isEven: Bool {
        return self % 2 == 0
    }
}

协议扩展

let pythons = ["Eric", "Graham", "John", "Michael", "Terry", "Terry"]
let beatles = Set(["John", "Paul", "George", "Ringo"])

// swift中数组类型(arrays)和集合(sets)都遵循集合协议(Collecttion)。
extension Collection {
    func summarize() {
        print("There are \(count) of us:")

        for name in self {
            print(name)
        }
    }
}
pythons.summarize()
beatles.summarize()

面向协议的编程 - Protocol-Oriented Programming

protocol Identifiable {
    var id: String { get set }
    func identify()
}
extension Identifiable {
    func identify() {
        print("My ID is \(id).")
    }
}
struct User: Identifiable {
    var id: String
}

let twostraws = User(id: "twostraws")
twostraws.identify()

你可能感兴趣的:(swift)