swift – 无法转换表达式的类型'[AnyObject]?’键入’NSArray’

前端之家收集整理的这篇文章主要介绍了swift – 无法转换表达式的类型'[AnyObject]?’键入’NSArray’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在重新审视似乎与Xcode6 beta 5一起使用的代码时,我注意到我得到一个“无法转换表达式的类型”[AnyObject]?为此行键入“NSArray”错误
let textFields:NSArray = loginAlert.textFields as NSArray

这是代码似乎是问题的部分:

override func viewDidAppear(animated: Bool) {
    if PFUser.currentUser() == nil{
        var loginAlert:UIAlertController = UIAlertController(title: "Sign Up / Login",message: "Please sign up or login",preferredStyle: UIAlertControllerStyle.Alert)

loginAlert.addTextFieldWithConfigurationHandler({
            textfield in
            textfield.placeholder = "Your username"
        })

        loginAlert.addTextFieldWithConfigurationHandler({
            textfield in
            textfield.placeholder = "Your password"
            textfield.secureTextEntry = true
        })

        loginAlert.addAction(UIAlertAction(title: "Login",style: UIAlertActionStyle.Default,handler: {
            alertAction in
            let textFields:NSArray = loginAlert.textFields as NSArray
            let usernameTextfield:UITextField = textFields.objectAtIndex(0) as UITextField
            let passwordTextfield:UITextField = textFields.objectAtIndex(1) as UITextField            
        }))
}

任何想法是什么问题?

“Cannot convert the expression’s type ‘[AnyObject]?’ to type ‘NSArray'”

听起来像loginAlert.textFields被定义为可选,可能是零,因此如果你确定它不是零 – 首先使用!打开它:

loginAlert.textFields as AnyObject! as NSArray

要么:

loginAlert.textFields! as NSArray

操场上相当基本的例子:

var temp:Array<String>?  // define Optional array 

temp = Array<String>()   // well,we create new Array but since its optional we need set "!" each time during manipulation

temp!.append("val1") // 1st off we unwrap it and add new value

var newArray = temp as AnyObject! as Array<String> // to downcast to Array<String>,we unwrap it with AnyObject! first
原文链接:https://www.f2er.com/swift/320405.html

猜你在找的Swift相关文章