协议的检查与转换
protocol Slogan {
var desc:String {get}
}
protocol Coder:Slogan {
var name:String {get}
}
struct JavaCoder:Coder {
var name:String
var desc:String {
return "会Java"
}
}
struct JsCoder:Coder {
var name:String
var desc:String {
return "会Js"
}
}
struct NewBie {
var name:String
var desc:String {
return "新手"
}
}
let java = JavaCoder(name:"张三")
let js = JsCoder(name:"李四")
let newBie = NewBie(name:"王五")
let array = [java,js,newBie] as [Any]
for elements in array {
if let element = elements as? Coder {
print(element.name,element.desc)
}
if let element = elements as? NewBie {
print("\(element.name)是一个新手")
}
}
for element in array {
if element is Coder {
print("程序员")
}
if element is NewBie {
print("新手")
}
}