ios - 如何在协议(protocol)中设置读写内部、只读外部属性

标签 ios swift

我有一些类具有相同的行为,它们都有

属性> savedPath:字符串项目:[字符串]当前项目:[字符串]

函数> 归档(包含项目:[String])unarchive()

所以我创建了一个protocol.swift并让这些类符合这个协议(protocol)来实现这些常见的行为。但是,就我而言,我想要:

  1. items 是只读外部,可读写内部
  2. 归档/取消归档是私有(private)函数

我尝试在items之前使用private(set),在archive/unarchive之前使用private,并出现一些错误出现。 有没有灵活的解决方案来解决这个问题?

没有协议(protocol)之前

class SampleClass {
    private(set) var items: [SampleModel] {
        set {
            archive(with: newValue)
        } get {
            return unarchive()
        }
    }

    func archive(with addresses: [SampleModel]) { ... }
    func unarchive() -> [SampleModel] { ... }
}

尝试使用协议(protocol)来满足之后

protocol SampleProtocol {
    associatedtype Item: Switchable

    var savedPath: String { get }
    var items: [Item] { get }
    var currentItem: Item? { get }

    func archive(with items: [Item])
    func unarchive() -> [Item]
}

最佳答案

您必须从协议(protocol)中删除任何私有(private)函数(因为它毫无意义)。协议(protocol)内部没有什么是私有(private)的(setter 或函数等)

protocol SampleProtocol {
    associatedtype Item: Switchable

    var savedPath: String { get }
    var items: [Item] { get }
    var currentItem: Item? { get }
}

然后您应该像这样实现类访问控制:

class SampleClass {
    private(set) var items: [SampleModel] {
        set {
            archive(with: newValue)
        } get {
            return unarchive()
        }
    }

    private func archive(with addresses: [SampleModel]) { /* ... */ }
    private func unarchive() -> [SampleModel] { /* ... */ }
}

关于ios - 如何在协议(protocol)中设置读写内部、只读外部属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56354655/

相关文章:

ios - 使用 Swift 设置 Game Center

iOS URL 请求。信号量问题

swift - Apple 事件未添加到日历中

ios - 如何解决使用未解析的标识符 'SetOptions'?

ios - SwiftUI - 放置在 NavigationView 中时 VStack 未填充整个屏幕

ios - 在不叠加的情况下以随机持续时间生成对象

swift - ARKit 将对象放置在平面上

ios - UITextView 中的文本显示不正确,不可见,但占用空间

ios - 我可以稍后更改包标识符吗

ios - UITableView 从 UIView 的右侧出现