如何在Swift商店属性中制作协议及其扩展?

问题描述 投票:0回答:1

以下是Swift中的协议及其扩展不存储属性的“问题”的解决方法。它似乎“有效”,但我想知道人们可能有什么理由来避免它?

fileprivate var strings: [String] = []

protocol SomeProat {
    func add(someString: String)
}

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

(我意识到这个问题可以被解释为主观的btw)。

swift protocols protected protocol-extension
1个回答
3
投票

没有好的方法可以在非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"]
© www.soinside.com 2019 - 2024. All rights reserved.