简体   繁体   中英

How to set a readwrite internal, readonly external property in protocol

I have some classes have same behaviors, they all have

properties > savedPath: String , items: [String] , currentItem: [String]

functions > archive(with items: [String]) , unarchive()

So I create a protocol.swift and let those classes conform this protocol to implement these common behavior.But, in my case, i want:

  1. items is a readonly external, readwrite internal
  2. archive/unarchive are private func

i tried to use private(set) before items , private before archive/unarchive and some errors showed up. Is there any flexible solutions to fix that?

before without protocol

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

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

after try to use protocol to satisfy

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]
}

You must remove any private function from protocol (Since it's meaningless). Nothing is private inside a protocol( setter or function or etc. )

protocol SampleProtocol {
    associatedtype Item: Switchable

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

And you should then implement the class access controls like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM