文本字段接收可选('值")而不是"值"

时间:2015-11-05 14:05:48

标签: ios swift

我试图传递一个正确的api文本,他带来了"可选"的消息。这是我的代码:

let accountValues:NSArray = account!.accountNumber.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "-"))
self.accountTextField.text = accountValues.objectAtIndex(0) as? String
self.accountDigitTextField.text = accountValues.objectAtIndex(1) as? String

3 个答案:

答案 0 :(得分:0)

您正在使用可选值" As?字符串&#34 ;.因此,它将返回一个Optional(' value')。

试试这个:

let accountValues:NSArray = account!.accountNumber.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "-"))
self.accountTextField.text = "\(accountValues.objectAtIndex(0))"
self.accountDigitTextField.text = "\(accountValues.objectAtIndex(1))"

答案 1 :(得分:0)

请替换这些行:

 self.accountTextField.text = accountValues.objectAtIndex(0) as? String
 self.accountDigitTextField.text = accountValues.objectAtIndex(1) as? String

by:

self.accountTextField.text = (accountValues.objectAtIndex(0) as! String)
self.accountDigitTextField.text = (accountValues.objectAtIndex(1) as! String)

答案 2 :(得分:0)

检索值时,请使用!之后的价值。垂头丧气的人应该强行解开任何选择。什么设置为?可以通过使用强制解开! 例如,

let intString = 7 as? String

print(intString!)

这应该打印“7”,而不是可选(“7”)

相关问题