复制代码
if let button = object as? UIButton {
// object is successfully cast to type UIButton and bound to button
} else {
// object could not be cast to type UIButton
}
if let dataSource = object as? UITableViewDataSource {
// object conforms to UITableViewDataSource and is bound to dataSource
} else {
// object not conform to UITableViewDataSource
}
注:相关教程知识阅读请移步到swift教程频道。
if let button = object as? UIButton {
// object is successfully cast to type UIButton and bound to button
} else {
// object could not be cast to type UIButton
}
请在 Type Casting 中查看更多信息。
检查匹配协议的语法与检查匹配类的语法是一样的,下面是使用 as? 检查匹配协议的示例:
复制代码if let dataSource = object as? UITableViewDataSource {
// object conforms to UITableViewDataSource and is bound to dataSource
} else {
// object not conform to UITableViewDataSource
}
注意,当做完匹配之后,dataSource 会转换为 UITableViewDataSource 类型,所以你只能访问和调用UITableViewDataSource 协议定义的属性和方法。当你想进行其他操作时,必须将其转换为其他的类型。
可以在 Protocols 查看更多相关信息。
注:相关教程知识阅读请移步到swift教程频道。








