我有一些类具有相同的行为,它们都有
属性> savedPath:字符串
,项目:[字符串]
,当前项目:[字符串]
函数> 归档(包含项目:[String])
,unarchive()
所以我创建了一个protocol.swift并让这些类符合这个协议(protocol)来实现这些常见的行为。但是,就我而言,我想要:
items
是只读外部,可读写内部归档/取消归档
是私有(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/