【问题标题】:iOS - 'val' is inaccessible due to 'internal' protection level(from my pod)iOS - 由于“内部”保护级别(来自我的 pod),无法访问“val”
【发布时间】:2019-05-11 08:55:11
【问题描述】:

所以我已经构建了一个 pod,我正在尝试在我的项目中使用它。 我有这个数据结构:

public struct Device {
  public init() {}

  var id: String = ""
  var serial: String = ""
  var account: String = ""
  var name: String = ""
  var isAttached: Bool?
  var isShared: Bool?
}

我在解析器中有这个函数:

func getDevices(json: JSON) -> [Device] {
    var devices = [Device]()

    for device in json.arrayValue {
        var item = Device()
        item.account = device["account"].string!
        item.id = device["id"].string!
        item.isAttached = device["isAttached"].boolValue
        item.isShared = device["isShared"].boolValue
        item.name = device["name"].string!
        item.serial = device["serial"].string!
        devices.append(item)
    }
    return devices
}

以及api类中的这个方法:

func getDevices( success: @escaping ([Device]) -> Void, failure: @escaping (String) -> Void) {

    let headers: HTTPHeaders = [
        "Authorization": "Bearer \(UserDefaults.standard.string(forKey: "accessToken")!)",
        "X-Account-ID": UserDefaults.standard.string(forKey: "accountToken")!
    ]

    Alamofire.request(Constants.Url.PENDING_DEVICE, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { response in
        if response.result.isSuccess {
            guard let data = response.data else { return }
            let json = JSON(data)
            self.devices = self.helper.getDevices(json: json)
            success(self.devices)
        }

        if response.result.isFailure {
            print("status code is:\(String(describing: response.response?.statusCode))")
            let error : Error = response.result.error!
            print(error.localizedDescription)
            failure(error.localizedDescription)
        }
    }
}

然而,当我像这样在项目中使用它时:

    self.requestManager.getDevice(success: { (devices) in
            for device in devices {
                var item = Device()
                item = device
                item.name //'name' is inaccessible due to 'internal' protection level error

        }
    }) { (error) in
        //
    }

在其他结构中,我已经创建了完美的作品,有什么想法吗?我认为 public init() {} 是解决此问题的方法。

【问题讨论】:

    标签: ios json swift swifty-json


    【解决方案1】:

    如果你单独构建一个 pod 并在框架中使用它,那么在 pod 中声明的所有变量都应该是 public 或 open。

    例子:

    public struct Device {
      ...
      ...
      public var name: String = ""
      ...
    }
    

    public 和 open 仅适用于框架编写者,这意味着框架之外(没有项目之外:))。

    public - 这可以被我的框架之外的对象使用。

    open - 我的框架之外的公共和对象可以继承它。

    【讨论】:

    • 公共 init() 不能确保发生这种情况?
    • 会怎么样?公开 init 使 init 公开。结束。它不公开名称。要公开名称,请声明 public var name。
    猜你喜欢
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 2017-12-23
    • 2018-08-25
    • 1970-01-01
    • 2021-08-24
    相关资源
    最近更新 更多