Dynamic Cast Faild - NSArray的AnyObject

时间:2015-03-07 10:35:35

标签: iphone swift

我正在尝试读取即将通过警报控制器发送的textFields值,但是在使用Anyobject转换为NSArray时出现运行时错误

alertUserStatus.addAction(UIAlertAction(title: "Sign Up", style: UIAlertActionStyle.Default, handler: {                
            alertAction in                
 //let textField:NSArray=alertUserStatus.textFields as AnyObject! as NSArray

 let textField=alertUserStatus.textFields! as AnyObject! as NSArray

            let username:String=textField.objectAtIndex(0) as String
            let password:String=textField.objectAtIndex(1) as String


            var signUpUser=PFUser()
            signUpUser.username=username
            signUpUser.password=password

            signUpUser.signUpInBackgroundWithBlock{

                (success:Bool!,error:NSError!)->Void in

                if success == true {
                    println("sign up successfully")
                }
                else{
                    println("fail to sign up")
                }
            }


        }))

1 个答案:

答案 0 :(得分:0)

在尝试将其按到另一种类型之前,查看从函数中获得的类型总是有帮助的。在这种情况下,alertUserStatus.textFields会返回[AnyObject]? - 也就是AnyObject的可选数组。因此,实际上没有必要将其转换为AnyObject然后转换为NSArray,这样您就可以从中获取前两个条目。相反,您想要打开它并将其转换为String数组。

最好避免使用!,即使您确信选项不可能是nil,因为有一天会有一个边缘情况,你错过了不成功,你的代码会因莫名其妙的强制解包错误信息而崩溃。

// nb you can skip the handler: argument name with trailing-closure syntax
alertUserStatus.addAction(UIAlertAction(title: "Sign Up", style: UIAlertActionStyle.Default) {
    alertAction in

    if let textFields = alertUserStatus.textFields as? [String] where textFields.count > 1 {

        let username = textFields[0]
        let password = textFields[1]

        // rest of your code...
    }
    else {
        // assert with intelligible message or log error or similar
    }
})