Swift:在展开Optional值NSObject时意外地发现了nil

时间:2015-11-18 23:12:23

标签: ios swift

在IOS应用程序中使用Swift 2和Xcode 7,我试图避免fatal error unexpectedly found nil while unwrapping an Optional value将可选链接应用于FriendShip NSObject,但我不知道哪种方法正确。

以下显示的FriendShip类在friend属性中收到一个nil值,但编译器给了我fatal error unexpectedly found nil while unwrapping an Optional value

class FriendShip: NSObject{

  var id: String?
  var friend: User?
  var date: NSDate?

  init(dictionary: [String: AnyObject]){

    id        = dictionary["id"] as? String
    friend    = User(dictionary: (dictionary["friend"] as! [String: AnyObject]))
    date      = dictionary["date"] as? NSDate

  }
} 

但如果我将friend属性设置为optional,则编译器会给我一个 EXC_BAD_INSTRUCTION错误:

class FriendShip: NSObject{

  var id: String?
  var friend: User?
  var date: NSDate?

  init(dictionary: [String: AnyObject]){

    id        = dictionary["id"] as? String
    friend    = User(dictionary: (dictionary["friend"] as? [String: AnyObject])!)
    date      = dictionary["date"] as? NSDate

  }
}  

我怎么解决?

1 个答案:

答案 0 :(得分:1)

你还在这里打开一个可选项:

friend    = User(dictionary: (dictionary["friend"] as? [String: AnyObject])!)

即:

(dictionary["friend"] as? [String: AnyObject])!

这应该是这样的:

if let friendDictionary = dictionary["friend"] as? [String: AnyObject] {
    friend = User(dictionary:friendDictionary)
}