struct Social {
var twitter:String
}
struct PersonOne {
var name:String
var age :Int
var social:Social
}
class PersonTwo {
var name:String
var age :Int
var social :Social
init(name:String,age:Int,social:Social) {
self.name = name
self.age = age
self.social = social
}
}
class Person :ReflectedStringConvertible{
var name:String
var age :Int
var social:Social
init(name:String,age:Int,social:Social) {
self.name = name
self.age = age
self.social = social
}
}
public protocol ReflectedStringConvertible:CustomStringConvertible {}
extension ReflectedStringConvertible {
public var description:String {
let mirror = Mirror(reflecting: self)
var str = "(mirror.subjectType)("
var first = true
for(label,value) in mirror.children {
if let label = label {
if first {
first = false
}else {
str += ","
}
str += label
str += ":"
str += "(value)"
}
}
str += ")"
return str
}
}
let matt = Person(name: "Tony", age: 23, social: Social(twitter: "@matt"))
print(matt)
let tony = PersonTwo(name: "tony", age: 32, social: Social(twitter: "@tony"))
print(tony)
let marc = PersonOne(name: "Steven", age: 23, social: Social(twitter: "@PinkZhao"))
print(marc)
如果你用结构体构造一个Person,则新建实例后输出的带有name,age和social等信息,但如果用class替代后则输出PersonTwo,如何实现呢?我们自己定义了一个协议-反射字符串可变的协议,让它遵从自定义字符串可变的协议,进而让类遵从反射字符串可变协议,从而实现了和结构体一样输出的功能。