代码之家  ›  专栏  ›  技术社区  ›  Khushbu Desai

“JSONEncoder”/“jsonedcoder”在此上下文中的类型查找不明确

  •  0
  • Khushbu Desai  · 技术社区  · 8 年前

    我有以下错误

    enter image description here

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

    注: 我在用 Xcode版本9.3.1 和 迅捷4 , 我试着用 jsoncoble.JSONEncoder 和 jsoncoble.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
        }
    }
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   Cristik    8 年前

    这个 JSONCodable 同时声明 JSONEncoder / JSONDecoder 类,所以编译器不知道要扩展哪些类:标准类,还是库中的类。

    告诉编译器通过用模块名预先装入类来扩展哪个类,应该消除歧义。

    import Foundation
    import JSONCodable
    
    extension JSONCodable.JSONEncoder {
        // extension code
    }
    
    extension JSONCodable.JSONDecoder {
        // extension code
    }
    

    但是,这对于这个特定的库不起作用,因为库声明了一个同名的协议( J可折叠 ). 因此,您只需要显式地从模块中导入两个类(请参见 this SO post 有关详细信息:

    import Foundation
    import class JSONCodable.JSONEncoder
    import class JSONCodable.JSONDecoder
    
    extension JSONCodable.JSONEncoder {
        // your code
    }
    
    extension JSONCodable.JSONDecoder {
        // your code
    }