NEW: Learn to build the incredible iOS 15 Weather app today! >>

SOLVED: Help with generics and lists

Forums > Swift

I have a type that represents a key: value pair with some optional attributes. The value can, in practice, be either a String or some numeric type, most likely an integer. So, I've declared my type thus:

public class PassField<T: Encodable>: Encodable {
  public let key: String
  public let value: T
  public var optionalAttribute: String?

  public init(key: String, value: T) {
    self.key = key
    self.value = value
  }
}

Now, I want to have a bunch of these fields on a form. I want to be able to do something like:

// this won't actually compile, which is where my question comes in
var someList = [PassField]()
someList.append(PassField<String>(key: "firstKey", value: "A nice string"))
someList.append(PassField<Int>(key: "secondKey", value: 5))

Is it even possible to have a list like this? I feel like it ought to be possible.

   

You are running into this error because there is nno such type as PassField, there is PassField<Int> and PassField<String> and you can't mix the two types in an array like that.

You could make someList an array of AnyObject instead, but then you'd have to do casting whenever you wanted to access an element of the list.

Maybe consider that generics might not be the proper solution here.

It's a bit more work, but you can do something like this:

public class PassField: Encodable {
    public let key: String
    public let value: PassFieldValue
    public var optionalAttribute: String?

    enum CodingKeys: CodingKey {
        case key, value, attribute
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encode(key, forKey: .key)
        switch value {
        case .intValue(let val):
            try container.encode(val, forKey: .value)
        case .stringValue(let val):
            try container.encode(val, forKey: .value)
        }
        if let attr = optionalAttribute {
            try container.encode(attr, forKey: .attribute)
        }
    }

    public enum PassFieldValue {
        case intValue(Int)
        case stringValue(String)
    }

    public init(key: String, value: PassFieldValue) {
        self.key = key
        self.value = value
    }
}

var someList = [PassField]()
someList.append(PassField(key: "firstkey", value: .stringValue("A nice string")))
let p = PassField(key: "secondkey", value: .intValue(5))
p.optionalAttribute = "thing"
someList.append(p)

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
do {
    let data = try encoder.encode(someList)
    print(String(data: data, encoding: .utf8)!)
} catch {
    print(error)
}

Result prinnted is:

[
  {
    "key" : "firstkey",
    "value" : "A nice string"
  },
  {
    "key" : "secondkey",
    "value" : 5,
    "attribute" : "thing"
  }
]

1      

And if you don't like have to use .intValue(...) or .stringValue(...) when you create a PassField, you can write a couple of convenience initializers like so:

extension PassField {
    public convenience init(key: String, value: Int) {
        self.init(key: key, value: .intValue(value))
    }

    public convenience init(key: String, value: String) {
        self.init(key: key, value: .stringValue(value))
    }
}

Then you can pass in an Int or String directly.

   

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS, you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.