Swift_协议、代理(protocol、delegate可选@objc optional与必需、协议扩展、is as? as!检查协议)
2017-08-21 16:28
751 查看
ProtocolClass2.swift
ViewController.swift
例如,可以扩展
例如,你可以扩展
//定义协议 @objc protocol ProClassDelegate { //代理函数 func test2() //必需实现 @objc optional func test(name:String,type:Int) //可选 } class ProtocolClass2: NSObject { //声明类的代理属性变量名 var delegate:ProClassDelegate? func backDelegate() { //代理回调 delegate?.test2() delegate?.test?(name: "back", type: 0) } }
ViewController.swift
import UIKit class ViewController: UIViewController,ProClassDelegate { //遵循代理 override func viewDidLoad() { super.viewDidLoad() var proClass:ProtocolClass2? = ProtocolClass2() proClass?.delegate = self proClass?.backDelegate() } func test2() { print("无参数代理回调") } func test(name: String, type: Int) { print("有参数代理回调") print("name = \(name)\n type = \(type)") } }
以下译文
协议扩展
协议可以通过扩展来为遵循协议的类型提供属性、方法以及下标的实现。通过这种方式,你可以基于协议本身来实现这些功能,而无需在每个遵循协议的类型中都重复同样的实现,也无需使用全局函数。例如,可以扩展
RandomNumberGenerator协议来提供
randomBool()方法。该方法使用协议中定义的
random()方法来返回一个随机的
Bool值:
extension RandomNumberGenerator { func randomBool() -> Bool { return random() > 0.5 } }
检查协议一致性
你可以使用类型转换中描述的is和
as操作符来检查协议一致性,即是否符合某协议,并且可以转换到指定的协议类型。检查和转换到某个协议类型在语法上和类型的检查和转换完全相同:
is用来检查实例是否符合某个协议,若符合则返回
true,否则返回
false。
as?返回一个可选值,当实例符合某个协议时,返回类型为协议类型的可选值,否则返回
nil。
as!将实例强制向下转换到某个协议类型,如果强转失败,会引发运行时错误。
为协议扩展添加限制条件
在扩展协议的时候,可以指定一些限制条件,只有遵循协议的类型满足这些限制条件时,才能获得协议扩展提供的默认实现。这些限制条件写在协议名之后,使用where子句来描述,正如Where子句中所描述的。
例如,你可以扩展
CollectionType协议,但是只适用于集合中的元素遵循了
TextRepresentable协议的情况:
extension Collection where Iterator.Element: TextRepresentable { var textualDescription: String { let itemsAsText = self.map { $0.textualDescription } return "[" + itemsAsText.joined(separator: ", ") + "]" } }
相关文章推荐
- 协议protocol和代理delegate的使用
- 【iOS】Swift中扩展extension与协议protocol
- swift3新路程(10)协议protocol和扩展extension
- iOS开发之Protocol (协议) 和delegate(代理)
- iOS 开发-Objective-c基础:协议和代理delegate&protocol)
- Swift中扩展extension与协议protocol
- 第八讲:Obj-C 协议 Delegate 代理设计模式
- Swift的protocol与协议扩展
- swift 中protocol(协议)中的可选(optional)方法
- 第八讲:Obj-C 协议 Delegate 代理设计模式
- Protocol 协议 与 delegate 代理
- 【IOS沉思录】IOS中的协议Protocol与代理Delegate
- swift 中protocol(协议)中的可选(optional)方法
- objective-c 协议(Protocol)和代理(Delegate)
- 窥探Swift之协议(Protocol)和委托代理(Delegate)回调的使用
- iOS中的协议(Protocol)与代理(Delegate)
- Protocol and Delegate 协议和代理(设计模式之代理模式)
- oc中的protocol(协议)与delegate(代理)
- iOS开发之OC篇(13)—— Protocol(协议)、Delegate(代理)
- protocol(协议) 和 delegate(委托)也叫(代理)---辨析