代码之家  ›  专栏  ›  技术社区  ›  drewg23

任何Swift类型的Getter Setter

  •  0
  • drewg23  · 技术社区  · 8 年前

    是否可以对类型为“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
            }
        }
    }
    

    当我尝试在我的代码中使用它时,尽管我会收到以下错误:

    无法将字符串与类型Any进行比较

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

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

    2 回复  |  直到 8 年前
        1
  •  3
  •   FruitAddict    8 年前

    你不应该使用 Any

    在我看来,您应该对API调用结果进行公共表示,而不是使用 任何 。您确切地知道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)
    }
    
        2
  •  3
  •   Grimxn    8 年前

    如果此处需要使用固定数量的类型,则可以使用枚举:

    struct BFSignature {
        var a: Int
    }
    
    enum Either {
        case bfSig(BFSignature)
        case string(String)
    }
    
    var a: Either
    var b: Either
    
    a = .bfSig(BFSignature(a: 7))
    b = .string("Stack Overflow")
    a = b
    

    用法:

    switch (b) {
    case Either.bfSig(let signature):
        print(signature.a) // Output integeral value
    case Either.string(let str):
        print(str)          //Output string value
    }