首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在此上下文中,“JSONEncoder”/“JSONDecoder”用于类型查找是不明确的。

在此上下文中,“JSONEncoder”/“JSONDecoder”用于类型查找是不明确的。
EN

Stack Overflow用户
提问于 2018-08-09 05:51:52
回答 1查看 474关注 0票数 0

我收到了跟随错误

我不知道我为什么要得到这个,我怎么解决它呢?请帮帮忙!

注意:我使用的是JSONCodable.JSONEncoder Xcode版本9.3.1和Swift4,我试过使用和Swift4,但它无法工作。

这里是代码:

代码语言:javascript
复制
import Foundation
import JSONCodable

extension JSONEncoder {
    func encode(_ value: CGAffineTransform, key: String) {
        object[key] = NSValue(cgAffineTransform: value)
    }

    func encode(_ value: CGRect, key: String) {
        object[key] = NSValue(cgRect: value)
    }

    func encode(_ value: CGPoint, key: String) {
        object[key] = NSValue(cgPoint: value)
    }
}

extension JSONDecoder {

    func decode(_ key: String, type: Any.Type) throws -> NSValue {
        guard let value = get(key) else {
            throw JSONDecodableError.missingTypeError(key: key)
        }
        guard let compatible = value as? NSValue else {
            throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: NSValue.self)
        }
        guard let objcType = String(validatingUTF8: compatible.objCType), objcType.contains("\(type)") else {
            throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: type)
        }
        return compatible
    }

    func decode(_ key: String) throws -> CGAffineTransform {
        return try decode(key, type: CGAffineTransform.self).cgAffineTransformValue
    }

    func decode(_ key: String) throws -> CGRect {
        return try decode(key, type: CGRect.self).cgRectValue
    }

    func decode(_ key: String) throws -> CGPoint {
        return try decode(key, type: CGPoint.self).cgPointValue
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-09 06:07:04

JSONCodable还声明了JSONEncoder/JSONDecoder类,因此编译器不知道要扩展哪些类:标准类或库中的类。

通过在类的前缀中加上模块名来告诉编译器要扩展的类,应该消除歧义。

代码语言:javascript
复制
import Foundation
import JSONCodable

extension JSONCodable.JSONEncoder {
    // extension code
}

extension JSONCodable.JSONDecoder {
    // extension code
}

但是,对于这个特定的库来说,这是行不通的,因为库声明了一个同名协议(JSONCodable)。因此,您只需要显式地从模块导入两个类(有关更多细节,请参见this SO post ):

代码语言:javascript
复制
import Foundation
import class JSONCodable.JSONEncoder
import class JSONCodable.JSONDecoder

extension JSONCodable.JSONEncoder {
    // your code
}

extension JSONCodable.JSONDecoder {
    // your code
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51759671

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档