swift optional chaining with cast

前端 未结 1 1866
遥遥无期
遥遥无期 2021-01-18 15:11

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         


        
1条回答
  •  隐瞒了意图╮
    2021-01-18 15:39

    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
    

    0 讨论(0)
提交回复
热议问题