I have a custom collection that can receive values of any type and converts them to strings. For example:
collection["key"] = 10
let value = collection["key"] // value is a String
Is there a way to do this? I tried implementing two subscript methods but Swift doesn't support write-only subscripts.
subscript(key: String) -> String {
get { ... }
}
// Doesn't compile
subscript(key: String) -> AnyObject {
set { ... }
}
Define subscript to return
AnyObject(orAnyas needed) and at the point you use the getter cast the result toString. You may already need to deal withsubscriptreturning an optional so the coercion is just all part of extracting your desired value.