在重新访问一些似乎与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
}))
}
任何想法是什么问题?
答案 0 :(得分:31)
“无法转换表达式的类型'[AnyObject]?”输入'NSArray'“
loginAlert.textFields
之类的声音被定义为可选,可能是nil
因此,如果您确定它不是nil
,请先使用!
打开它:
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