简体   繁体   English

如何在Swift中扩展数组?

[英]How to extend an array in Swift?

I have this protocol 我有这个协议

protocol JsonConvertable {
    init?(_ underlyingValue: UnderlyingValue)
}

UnderlyingValue is an enum : UnderlyingValue是一个enum

enum UnderlyingValue {
    case string(String)
    case int(Int)
    case double(Double)
    case bool(Bool)
    case array(Array<Dictionary<String, AnyObject>>)
    case dictionary(Dictionary<String, AnyObject>)

    init?(value: JsonConvertable) {
        switch rawValue {
        case let value as [String: AnyObject]: self = .dictionary(value)
        case let value as Array<[String: AnyObject]>: self = .array(value)
        case let value as Double: self = .double(value)
        case let value as Int: self = .int(value)
        case let value as Bool: self = .bool(value)
        case let value as String: self = .string(value)
        default: return nil
        }
    }
}

I can extend most types as follows 我可以扩展大多数类型,如下所示

extension String: JsonConvertable {
    init?(_ underlyingValue: UnderlyingValue) {
        switch underlyingValue {
        case .bool(let value): self = value
        default: return nil
    }
}

However the Array extension is giving me the error Cannot assign value of type 'Array<Dictionary<String, AnyObject>>' to type 'Array<_>' 但是,数组扩展名给我错误: Cannot assign value of type 'Array<Dictionary<String, AnyObject>>' to type 'Array<_>'

extension Array: JsonConvertable {
    init?(_ underlyingValue: UnderlyingValue) {
        switch underlyingValue {
        case .array(let value): self = value
        default: return nil
        }
    }
}

I have tried everything I can think of but nothing is working. 我已经尝试了所有可以想到的方法,但是没有任何效果。 I tried to have JsonConvertable conform to ArrayLiteralConvertable, I have tried using generics in the init but I am just starting to understand generics and don't really know how it would be beneficial in this case, the same with AssociatedType. 我试图让JsonConvertable符合ArrayLiteralConvertable,我试图在init中使用泛型,但是我才刚刚开始理解泛型,并且并不真正知道在这种情况下它会有什么好处,与AssociatedType一样。 I have tried to constrict Element. 我试图收缩元素。 I have been trying to get this to work for 2 whole days and everything I do seems to not make any headway. 我一直在努力使其工作整整2天,而我所做的一切似乎都没有取得任何进展。 What am I missing? 我想念什么?

In your extension method, you are extending Array which is a type of Array<_> and your _underlyingValue is type of Array<[String:AnyObject]>. 在扩展方法中,您正在扩展Array,它是Array <_>的类型,而_underlyingValue是Array <[String:AnyObject]>的类型。

Have you try this way: 您是否尝试过这种方式:

extension Array where Element:Dictionary<String, AnyObject>, Element:JsonConvertable  {
  init?(_underlyingValue : UnderlyingValue){
      switch _underlyingValue {
        case  .array(let value):
          self = value
        default:
          return nil
      }
  }
}

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

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