[英]Swift: unexpectedly found nil while unwrapping an Optional value, NSObject
Using Swift 2 and Xcode 7 in an IOS app, I'm trying to avoid the fatal error unexpectedly found nil while unwrapping an Optional value
applying the optional chaining to a FriendShip NSObject but I don't know which is the correct way. 我试图在IOS应用程序中使用Swift 2和Xcode 7,以避免在
fatal error unexpectedly found nil while unwrapping an Optional value
链应用于FriendShip NSObject fatal error unexpectedly found nil while unwrapping an Optional value
但是我不知道哪种方法是正确的。
The class FriendShip showed below receives a nil value in the friend property but the compiler gives me the fatal error unexpectedly found nil while unwrapping an Optional value
: 下面显示的FriendShip类在friend属性中接收到一个nil值,但是编译器
fatal error unexpectedly found nil while unwrapping an Optional value
给了我一个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
}
}
but if I set the friend property to optional, the compiler gives me an EXC_BAD_INSTRUCTION
error: 但是,如果我将friend属性设置为可选,编译器会给我一个
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
}
}
How could I solve it? 我该怎么解决?
You're still unwrapping an optional here: 您仍在此处展开可选项:
friend = User(dictionary: (dictionary["friend"] as? [String: AnyObject])!)
Namely: 即:
(dictionary["friend"] as? [String: AnyObject])!
This should be instead something like: 而是应该类似:
if let friendDictionary = dictionary["friend"] as? [String: AnyObject] {
friend = User(dictionary:friendDictionary)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.