6. Swift 有趣的协议.png

CustomStringConvertible

遵守 CustomStringConvertible 协议,可以自定义实例的打印字符串

  1. class MyClass: CustomStringConvertible {
  2. var description: String {
  3. return "this is MyClass..."
  4. }
  5. }
  6. var instance = MyClass()
  7. print(instance) // this is MyClass...

Equatable

遵守 Equatable 协议,可以让两个实例进行等价判断,实现 == 方法即可

  1. struct Point : Equatable {
  2. var x: Int
  3. var y: Int
  4. // 若不实现 == 方法,则默认判断两个实例的每个属性是否等价
  5. static func == (p1: Point, p2: Point) -> Bool {
  6. return (p1.x == p2.x) && (p1.y == p2.y)
  7. }
  8. }
  9. var p1 = Point(x: 10, y: 10)
  10. var p2 = Point(x: 10, y: 10)
  11. print(p1 == p2)

[备注]:参考1 参考2 你一定不知道Swift源码怎么看?

Comparable

Comparable 继承自 Equatable 协议。
遵守 Comparable 协议,可以让两个实例进行大小比较,实现 > >= < <= 方法即可。

CaseIterable

枚举遵守 CaseIterable 协议,可以实现遍历枚举名称

  1. enum Season : CaseIterable {
  2. case spring, summer, autumn, winter
  3. }
  4. let seasons = Season.allCases
  5. print(seasons.count) // 4
  6. for season in seasons {
  7. print(season)
  8. } // spring summer autumn winter

Codable

可编码解码的,由 Decodable 和 Encodable 两个协议组合而成

  1. public typealias Codable = Decodable & Encodable
  1. import Foundation
  2. // 枚举原始值应可以 Codable,比如 String/Int
  3. enum Level: String, Codable {
  4. case large
  5. case medium
  6. case small
  7. }
  8. struct Location: Codable {
  9. let latitude: Double
  10. let longitude: Double
  11. }
  12. class City: Codable, CustomStringConvertible {
  13. var name: String?
  14. var level: Level?
  15. var location: Location?
  16. var description: String {
  17. return """
  18. {
  19. "name": \(name ?? ""),
  20. "level": \(level?.rawValue ?? ""),
  21. "location": {
  22. "latitude": \(location?.latitude ?? 0),
  23. "longitude": \(location?.longitude ?? 0)
  24. }
  25. }
  26. """
  27. }
  28. }
  1. let city = City()
  2. city.name = "ShangHai"
  3. city.level = .large
  4. city.location = Location(latitude: 30.40, longitude: 120.51)
  5. let data = try JSONEncoder().encode(city)
  6. let string = String(data: data, encoding: .utf8)!
  7. print(string)
  8. let data2 = string.data(using: .utf8)
  9. let city2 = try JSONDecoder().decode(City.self, from: data2!)
  10. print(city2)
  1. {"name":"ShangHai","level":"large","location":{"longitude":120.51000000000001,"latitude":30.399999999999999}}
  2. {
  3. "name": ShangHai,
  4. "level": large,
  5. "location": {
  6. "latitude": 30.4,
  7. "longitude": 120.51
  8. }
  9. }

参考:参考1 参考2

Literal Protocol

参考:字面量协议