ios - 'JSONEncoder'/'JSONDecoder' 在此上下文中对于类型查找不明确

标签 ios json swift encoder decoder

我遇到了以下错误

enter image description here

我不知道为什么会出现这个问题,我该如何解决? 请帮忙!

注意:我使用的是 Xcode 版本 9.3.1Swift4, 我曾尝试使用 JSONCodable.JSONEncoderJSONCodable.JSONDecoder 但它不起作用。

代码如下:

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
    }
}

最佳答案

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

通过在类前加上模块名称来告诉编译器要扩展哪个类,应该可以消除歧义。

import Foundation
import JSONCodable

extension JSONCodable.JSONEncoder {
    // extension code
}

extension JSONCodable.JSONDecoder {
    // extension code
}

然而,这对这个特定的库不起作用,因为该库声明了一个具有相同名称的协议(protocol) (JSONCodable)。因此,您只需要从模块中显式导入两个类(有关更多详细信息,请参阅 this SO post):

import Foundation
import class JSONCodable.JSONEncoder
import class JSONCodable.JSONDecoder

extension JSONCodable.JSONEncoder {
    // your code
}

extension JSONCodable.JSONDecoder {
    // your code
}

关于ios - 'JSONEncoder'/'JSONDecoder' 在此上下文中对于类型查找不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51759671/

相关文章:

c# - 如何在约束条件下使多个按钮居中?

ios - 如何从 Core Data 中的持久存储中删除所有对象?

android - 无法使用 android-volley 从 JSON 数组获取数据到自定义 ListView 中

javascript - jquery 自动完成与外部 json 源

json - 如何在Elasticsearch中通过两个子句过滤数据?

ios - Swift:通过 UIView 识别滚动

ios - 以编程方式将应用程序发送到后台

ios - Swift 匹配嵌套结构数组中的元素

ios - 有没有办法使用用户默认值来更改我的所有 IOS 应用程序页面的背景颜色?

ios - 在 Swift 中使用 "Map"创建两个数组的超集