CustomStringConvertible
遵守 CustomStringConvertible 协议,可以自定义实例的打印字符串
class MyClass: CustomStringConvertible {
var description: String {
return "this is MyClass..."
}
}
var instance = MyClass()
print(instance) // this is MyClass...
Equatable
遵守 Equatable 协议,可以让两个实例进行等价判断,实现 == 方法即可
struct Point : Equatable {
var x: Int
var y: Int
// 若不实现 == 方法,则默认判断两个实例的每个属性是否等价
static func == (p1: Point, p2: Point) -> Bool {
return (p1.x == p2.x) && (p1.y == p2.y)
}
}
var p1 = Point(x: 10, y: 10)
var p2 = Point(x: 10, y: 10)
print(p1 == p2)
[备注]:参考1 参考2 你一定不知道Swift源码怎么看?
Comparable
Comparable 继承自 Equatable 协议。
遵守 Comparable 协议,可以让两个实例进行大小比较,实现 > >= < <= 方法即可。
CaseIterable
枚举遵守 CaseIterable 协议,可以实现遍历枚举名称
enum Season : CaseIterable {
case spring, summer, autumn, winter
}
let seasons = Season.allCases
print(seasons.count) // 4
for season in seasons {
print(season)
} // spring summer autumn winter
Codable
可编码解码的,由 Decodable 和 Encodable 两个协议组合而成
public typealias Codable = Decodable & Encodable
import Foundation
// 枚举原始值应可以 Codable,比如 String/Int
enum Level: String, Codable {
case large
case medium
case small
}
struct Location: Codable {
let latitude: Double
let longitude: Double
}
class City: Codable, CustomStringConvertible {
var name: String?
var level: Level?
var location: Location?
var description: String {
return """
{
"name": \(name ?? ""),
"level": \(level?.rawValue ?? ""),
"location": {
"latitude": \(location?.latitude ?? 0),
"longitude": \(location?.longitude ?? 0)
}
}
"""
}
}
let city = City()
city.name = "ShangHai"
city.level = .large
city.location = Location(latitude: 30.40, longitude: 120.51)
let data = try JSONEncoder().encode(city)
let string = String(data: data, encoding: .utf8)!
print(string)
let data2 = string.data(using: .utf8)
let city2 = try JSONDecoder().decode(City.self, from: data2!)
print(city2)
{"name":"ShangHai","level":"large","location":{"longitude":120.51000000000001,"latitude":30.399999999999999}}
{
"name": ShangHai,
"level": large,
"location": {
"latitude": 30.4,
"longitude": 120.51
}
}
Literal Protocol
参考:字面量协议