The code below highlights a problem I\'m having combining optional chaining and casts with Apple\'s swift language
import Foundation
import CoreData
class M
There are 2 problems: the first is that in this line:
let name: String = self.detailItem?.valueForKey("name") as String
the right part is an optional (detailItem
is optional), so whatever the expression returns, it cannot be assigned to a non-optional variable having type String
The second problem is that valueForKey
returns AnyObject!
, which can be an instance of any class - but String
is not a class, you'd need Any
in order to be able to cast that into a String
.
I presume that NSManagedObject
returns an NSString
, so you can achieve what you need with this line:
let name: String? = (self.detailItem?.valueForKey("name") as? NSString) as? String