gpt4 book ai didi

swift - 必须将属性声明为公共(public),因为它符合公共(public)协议(protocol)中的要求?

转载 作者:行者123 更新时间:2023-12-03 09:23:17 24 4
gpt4 key购买 nike

public protocol CDViewModel: class {
var cancellableList: [AnyCancellable] { get set }
}
public extension CDViewModel {
func subscribe(_ callback: @escaping (Project) -> Void) {
cancellableList.append( /*...*/)
}
}

我有一个将在模块之外使用的协议(protocol)。所以我必须公开它。

但我希望符合该类的类实现具有私有(private)访问权限的cancellableList。
   class MyClass: CDViewModel {
private var cancellableList: [AnyCancellable] = [AnyCancellable]()
}

必须将属性“cancellableList”声明为公共(public),因为它符合公共(public)协议(protocol)“CDViewModel”中的要求

这可能吗?

最佳答案

一种解决方法是创建一个中间对象类,它可以使用 fileprivate 保护对其变量的访问。 .您在 MyClass 中声明了“包装对象类型”。实例从而符合 MyClass的必需接口(interface)。

现在,您可以从协议(protocol)扩展内部完全访问包装对象 ( wrappedList ) 属性,但不能从模块外部访问。

CDViewModel.swift


import Combine

class CDViewModelList {
fileprivate var cancellableList: [AnyCancellable] = [AnyCancellable]()
}

protocol CDViewModelProtocol: AnyObject {
var wrappedList: CDViewModelList { get }
}

extension CDViewModelProtocol {
func subscribe(_ callback: Int) {
self.wrappedList.cancellableList.append(/****/)
}
}

MyClass.swift


class MyClass: CDViewModelProtocol {
let wrappedList = CDViewModelList()

func doStuff () {
self.subscribe(24)
self.wrappedList.cancellableList // 'cancellableList' is inaccessible due to 'fileprivate' protection level
}
}

感谢这个问题,它让我在这里好好阅读:

FULL CREDIT

关于swift - 必须将属性声明为公共(public),因为它符合公共(public)协议(protocol)中的要求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60611613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com