Swift 1.2 NSDate?!不可转换为NSDate

时间:2015-05-09 10:30:17

标签: swift

升级到1.2后,我遇到了编译错误:

NSDate?! is not convertible to NSDate

代码:

let dateCreated = photoCommentObjects[indexPath.row].createdAt as NSDate

其他尝试:

我也尝试过:

let dateCreated = photoCommentObjects[indexPath.row].createdAt as? NSDate

我收到错误:

Downcast from NSDate?! to 'NSDate' only unwraps optionals

3 个答案:

答案 0 :(得分:2)

这是一个类型问题。您有一个AnyObject类型的数组,但您无法在AnyObject上阅读该属性。

//sample data
class PhotoComment {
   let createdAt = NSDate()
}

let photoCommentObjects: [AnyObject] = [PhotoComment()]


//let's get the indexed object first and let's cast it from AnyObject
let photoComment = photoCommentObjects[indexPath.row] as! PhotoComment
//now trivially
let dateCreated = photoComment.createdAt

//let's cast the whole array first
let photoComments = photoCommentObjects as! [PhotoComment]
let dateCreated = photoComments[indexPath.row].createdAt

答案 1 :(得分:2)

你试过吗?

let dateCreated = photoCommentObjects[indexPath.row].createdAt as! NSDate

自Sift 1.2起,您必须使用!明确标记强制转换。 这提醒您,如果失败,您的应用程序将崩溃。

答案 2 :(得分:1)

显然photoCommentObjects[indexPath.row].createdAt正在返回一种NSDate?!类型,它是一个隐式包含的可选项可选项。要打开它,首先使用NSDate?将结果强制转换为as以删除隐式包装的可选项,然后使用可选绑定来展开生成的NSDate?

if let dateCreated = photoCommentObjects[indexPath.row].createdAt as NSDate? {
    // use dateCreated which is of type NSDate
}

结果是dateCreated将是普通NSDate

或者,您可以使用:

if let temp = photoCommentObjects[indexPath.row].createdAt, dateCreated = temp {
    // each assignment unwraps one layer of Optional
    // use dateCreated which is of type NSDate
} else {
    println("something is nil")
}