swift - 如何在 Swift 存储属性中创建协议(protocol)及其扩展?

标签 swift protocols protected protocol-extension

以下是 Swift 中的协议(protocol)及其扩展不存储属性的“问题”的变通方法。它似乎“有效”,但我想知道人们可能出于什么原因避免使用它?

fileprivate var strings: [String] = []

protocol SomeProat {
    func add(someString: String)
}

extension SomeProat {
    func add(someString: String) {
        strings.append(someString)
        print(strings)
    }
}

(我意识到这个问题可以被解释为主观顺便说一句)。

最佳答案

没有好的方法可以在非 Apple 平台上用纯 Swift 完成您的要求。

如果您在 Apple 平台(macOS、iOS、tvOS、watchOS)上,并且您的符合类型是一个类,那么您可以使用 Objective-C 运行时提供的关联对象支持:

import ObjectiveC

protocol MyProtocol: class {
    var strings: [String] { get }
    func add(someString: String)
}

private var MyProtocolSomeStringKey: UInt8 = 0

extension MyProtocol {
    var strings: [String] {
        get {
            return objc_getAssociatedObject(self, &MyProtocolSomeStringKey) as? [String] ?? []
        }
        set {
            let value = newValue.isEmpty ? nil : newValue
            objc_setAssociatedObject(self, &MyProtocolSomeStringKey, value, .OBJC_ASSOCIATION_RETAIN)
        }
    }

    func add(someString: String) {
        strings.append(someString)
    }
}

class MyObject { }
extension MyObject: MyProtocol { }

let myObject = MyObject()
myObject.add(someString: "hello")
myObject.add(someString: "world")
print(myObject.strings)
// Output: ["hello", "world"]

关于swift - 如何在 Swift 存储属性中创建协议(protocol)及其扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55071020/

相关文章:

java - 为什么在java中类可以有默认修饰符却不能被保护

swift - 这个语句在 Swift 中总是计算为 nil 吗?

swift - 如何在 Swift 中从 [DDXMLElement] 中提取值?

ios - 在两个不同的类中对同一文件使用委托(delegate)

专门化泛型协议(protocol)的 Swift 协议(protocol)

c++ - 如何允许某些类的对象访问另一个类的对象的 protected 成员

ios - UILabel 的宽度超过使用编程自动布局的文本

ios - 如何在 SwiftUI 中的大型导航栏标题旁边显示配置文件图标?

networking - 四层防火墙功能

C++:为什么我的 DerivedClass 的构造函数无法访问 BaseClass 的 protected 字段?