Swift 协议
封面图
•
2025-10-24
•
Swift
6
0
0
0
在 **Swift** 中,**协议(Protocol)** 是一种定义行为的蓝图,它规定了某个类型必须实现的方法、属性、下标等。协议本身不提供具体实现,而是用来定义接口,让不同的类型可以遵循这个接口并提供自己的实现。 --- ## ✅ 一、协议的基本语法 ```swift protocol SomeProtocol { // 属性要求 var someProperty: Int { get set } // 可读可写 var anotherProperty: String { get } // 只读 // 方法要求 func someMethod() func anotherMethod(param: String) -> Int // 下标要求 subscript(index: Int) -> Int { get set } } ``` --- ## ✅ 二、遵循协议(Conforming to a Protocol) 一个类、结构体或枚举可以通过 `: ProtocolName` 来遵循协议: ```swift struct MyStruct: SomeProtocol { var someProperty: Int = 0 var anotherProperty: String = "Hello" func someMethod() { print("Method called") } func anotherMethod(param: String) -> Int { return param.count } subscript(index: Int) -> Int { get { return index * 2 } set { print("Setting value at $index): $newValue)") } } } ``` --- ## ✅ 三、协议中的可选要求(Optional Requirements) 使用 `@objc` 标记后,可以在协议中定义可选方法和属性: ```swift @objc protocol OptionalProtocol { @objc optional var optionalProperty: String { get } @objc optional func optionalMethod() } ``` > 注意:只有在类中才能使用 `@objc` 协议,并且需要继承自 `NSObject` 或使用 `@objc` 标记类。 --- ## ✅ 四、协议扩展(Protocol Extension) Swift 允许你为协议提供默认实现,这被称为 **协议扩展(Protocol Extension)**。 ```swift protocol Greeting { func sayHello() } extension Greeting { func sayHello() { print("Hello!") } } ``` 任何遵循 `Greeting` 的类型都可以直接使用 `sayHello()` 而不需要自己实现: ```swift struct Person: Greeting {} let person = Person() person.sayHello() // 输出 "Hello!" ``` --- ## ✅ 五、协议继承(Protocol Inheritance) 协议可以继承其他协议: ```swift protocol A { func methodA() } protocol B: A { func methodB() } ``` --- ## ✅ 六、协议组合(Protocol Composition) 你可以将多个协议组合在一起使用: ```swift func doSomething<T: SomeProtocol & AnotherProtocol>(item: T) { // ... } ``` 或者使用 `where` 子句: ```swift func doSomething<T>(item: T) where T: SomeProtocol, T: AnotherProtocol { // ... } ``` --- ## ✅ 七、协议与泛型结合 协议可以用于泛型约束: ```swift func process<T: SomeProtocol>(item: T) { item.someMethod() } ``` --- ## ✅ 八、协议中的 Self 关键字 在协议中可以使用 `Self` 表示当前类型: ```swift protocol Identifiable { associatedtype IDType var id: IDType { get } static func describe() -> String } ``` --- ## ✅ 九、协议的扩展中使用 Self ```swift protocol Animal { func speak() } extension Animal { func speak() { print("Unknown animal") } func makeSound() { self.speak() } } ``` --- ## ✅ 十、常见用途 - 定义接口(如 `Equatable`, `Comparable`, `CustomStringConvertible` 等) - 实现多态(通过协议类型调用) - 实现依赖注入(通过协议来解耦) - 构建可测试代码(通过协议 mock 对象) --- 如果你有具体的使用场景或想了解某个特定协议(如 `Equatable`, `Hashable`, `Codable` 等),欢迎继续提问!
上一篇:
Swift 扩展
下一篇:
Swift 泛型
标题录入,一次不能超过6条
返回顶部
留言
留言
评论