[swift-users] dealing with heterogenous lists/dictionary with Codable

David Baraff davidbaraff at gmail.com
Wed Oct 18 20:47:25 CDT 2017


So I have simple structs like this:

	struct Library: Codable {
		let domain: String
		let unit: String
	}

and it’s super-simple to serialize.  Yay.

But:

	struct LibraryGroup : Codable { 	// I wish...
	   let libraries: [Library]
           let someDict: [String : Any]
	}

So what I’m looking for is something where if the values in someDict are themselves Codable, I can serialize things, and if they’re not, I can’t.  In my previous scheme, I was using NSKeyedArchiver to serialize everything, manualy, including someDict; in trying to switch to Codable I ran smack into the fact that Codable wants to know what all the types are, in advance.

Am I just stuck?  How do I get the best of both worlds, where the compiler can make use of the fact that it can see the data types of my structures, while still being able to serialize heterogenous data like is found in LibraryGroup?

Is my only alternative to write a custom coder for LibraryGroup?  Is there any hope I could teach Codable what to do with
	[String: Any]

?




More information about the swift-users mailing list