swift基础之协议和扩展

原创
2021/04/16 14:20
阅读数 80

协议

//协议
protocol Named {
    var name: String { get }
}

protocol Aged {
    var age: Int { get }
}

struct Person: Named, Aged {
    var name: String
    var age: Int
}

let p = Person(name: "zhang san", age: 20)

func wish(to: Named & Aged) {
    print("name \(to.name) age \(to.age)")
}

wish(to: p)
//name zhang san age 20

协议扩展

protocol TextRepresentable {
    var desc: String { get }
}

//扩展协议
extension Person: TextRepresentable {
    var desc: String {
        return "name \(name) age \(age)"
    }
}

extension Array: TextRepresentable where Element: TextRepresentable {
    var desc: String {
        let itemDesc = self.map{ $0.desc }
        return itemDesc.joined(separator: ",")
    }
}

let arr = [
    Person(name: "zhang san", age: 20),
    Person(name: "li si", age: 25)
]
print(arr.desc)
//name zhang san age 20,name li si age 25
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部