What's the most convenient code to write
[results valueForKey:@"attribute"]
in swift? I've found here that it's recommended to use the map() function with a closure:
swiftarray.map({$0["attribute"]})
N.B. swiftarray is not a NSArray
What's the most convenient code to write
[results valueForKey:@"attribute"]
in swift? I've found here that it's recommended to use the map() function with a closure:
swiftarray.map({$0["attribute"]})
N.B. swiftarray is not a NSArray
I'am not sure but if you have some object in array other than Dictionary (or other type that supports subscripting), you will need to use following code
results.map({$0.attribute})
What's the most convenient code to write
[results valueForKey:@"attribute"]
in swift?
That would be:
results.valueForKey("attribute")
Does your class have a subscript?
I've been able to create a test class which can use the KVC accessors like so:
class TestObject
{
var name:String
var numbers:[String:Int] = [String:Int]()
init(name:String)
{
self.name = name
}
subscript(index: String) -> Int? {
get {
return numbers[index]
}
set(newValue) {
numbers[index] = newValue
}
}
}
Tested with the following code:
let testObject1 = TestObject(name: "test1")
testObject1["home-phone"] = 1234
testObject1["mobile-phone"] = 5678
let testObject2 = TestObject(name: "test2")
testObject2["office"] = 0987
testObject2["mobile-phone"] = 6543
let array : [TestObject] = [testObject1, testObject2]
var results = array.map({$0["office"]})
print("Results:\(results)")
results = array.map({$0["mobile-phone"]})
print("Results:\(results)")
produces the following result:
Results:[nil, Optional(987)]
Results:[Optional(5678), Optional(6543)]