swift - 任何 Swift 类型的 Getter Setter

标签 swift swift3

是否可以为类型为“Any”的属性执行 getter 和 setter

这是我的想法:

private var _valueObject: Any?
public var valueObject: Any? {
    set {
        if newValue is String {
            self._valueObject = newValue as? String
        } else if newValue is BFSignature {
            self._valueObject = newValue as? BFSignature
        }
    }

    get {
        if self._valueObject is String {
            return self._valueObject as? String
        } else if self._valueObject is BFSignature {
            return self._valueObject as? BFSignature
        } else {
            return self._valueObject
        }
    }
}

当我尝试在我的代码中使用它时,虽然我收到错误说明:

Cannot compare String to type Any

有没有一种方法可以在我需要时不将“valueObject”强制转换为字符串来使用类似的东西。一种使用它的方法,它已经知道它是“String”或“BFSignature”而不是“Any”。

错误示例如下: enter image description here 我宁愿它只知道 cellValue 是一个“字符串”。而不是每次使用它时都转换它。

最佳答案

你不应该使用 Any

在我看来,您应该对 API 调用结果进行通用表示,而不是使用 Any。您确切地知道 API 将返回什么,不是吗?它可以是 String 或您转换为自定义对象 BFSignature 的东西。

因此,您可以制作一个枚举来表示您的 API 调用结果:

enum APIResult {
    case signature(BFASignature)
    case justString(String)
}

并像使用它一样

private var _valueObject: APIResult?

if let stringValue = newValue as? String {
    self._valueObject = .justString(stringValue)
}
if let signatureValue = newValue as? BFSignature {
    self._valueObject = .signature(signatureValue)
}

关于swift - 任何 Swift 类型的 Getter Setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49174765/

相关文章:

swift - 如何以编程方式显示 NSTextView 的查找面板?

ios - 在 BluetoothManager Delegate 类中访问 ViewController 按钮

ios - 没有获得正确的 UILabel 行数

swift - "Ambiguous use of ' 子级 '"尝试在 Swift 3.0 中使用 NSTreeController.arrangedObjects

swift - 非 -'@objc' 方法不满足 '@objc' 协议(protocol)的可选要求

swift - 如何提取 swift 3 字典的子集

swift - 类型 'SecondPageController' 的值没有成员 'miniView'

swift : switch case multiples values from dictionary keys

swift - 添加约束时出现运行时错误

ios - 在 for 循环中运行多个 URLRequest,先完成后执行