简体   繁体   English

用于Value(Structures)类型的Swift协议扩展

[英]Swift protocol extensions for Value(Structures) types

public struct KZErrorInfo: Unboxable {

var statusCode = -1
var status: String?
var errorMessage: String?

public init() {

}

public init(unboxer: Unboxer) {
    self.statusCode = unboxer.unbox("StatusCode")
    self.status = unboxer.unbox("Status")
    self.errorMessage = unboxer.unbox("Message")
}

} }

protocol KZClientResponse: ETClientResponse {

var errorInfo: KZErrorInfo? { get set }

} }

var errorInfo: KZErrorInfo? {
    get {
        if let value = objc_getAssociatedObject(self, &xoAssociationKeyErrorInfo) as? KZErrorInfo {
            return value
        }
        return nil
    }
    set(newValue) {
        if let error = newValue {
           objc_setAssociatedObject(self, &xoAssociationKeyErrorInfo, error, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }
}

My objective is to have a default implantation for the protocol KZClientResponse and Xcode is giving me a compile error as below. 我的目标是为协议KZClientResponse提供默认植入,并且Xcode给我一个如下的编译错误。 In the case of value types, how to overcome this issue? 对于值类型,如何克服这个问题? Appreciate you suggestions. 感谢您的建议。

在此处输入图片说明

As the error message is indicating, objc_getAssociatedObject(_:_:) and objc_setAssociatedObject(_:_:_:_:) require AnyClass as the first argument. 如错误消息所示, objc_getAssociatedObject(_:_:)objc_setAssociatedObject(_:_:_:_:)需要AnyClass作为第一个参数。 You cannot use Swift structs as AnyClass . 您不能将Swift结构用作AnyClass

Think another way to store errorInfo which works with structs. 考虑另一种存储与结构一起使用的errorInfo方法。 Why don't you have it as the struct's property? 为什么没有它作为结构的属性?

... giving me a compile error as below. ...给我一个如下的编译错误。 In the case of value types, how to overcome this issue? 对于值类型,如何克服这个问题?

You can't overcome the compiler error. 您无法克服编译器错误。 You're trying to mix apples with oranges. 您正在尝试将苹果与橙子混合。 objc_getAssociatedObject is, by definition, Objective-C. 根据定义, objc_getAssociatedObject是Objective-C。 But Objective-C knows nothing of Swift structs; 但是Objective-C对Swift结构一无所知。 it cannot possibly see them. 它不可能看到他们。 The only thing it knows about are what it calls objects — that is, classes and their instances. 它唯一知道的是它所谓的对象 -即类及其实例。 To work with a Swift struct, you cannot use the Objective-C runtime at all: you must operate entirely within Swift itself. 要使用Swift结构,您完全不能使用Objective-C运行时:您必须完全在Swift本身内进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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