为什么以下行会迅速编译并工作?
employeeListing.text = (jumperCablesRoles[row] as! [String] as [String]).joinWithSeparator("...")
看来我正在将字符串数组转换为我认为完全相同的字符串数组。它有效,但我不知道为什么,有人可以解释吗?
最佳答案
对您的代码说几点:
首先,jumperCablesRoles[row] as! [String]
在Swift中是一个潜在的危险动作,因为您强制将(cc)jumperCablesRoles[row]
展开为字符串数组。了解有关保存小马here的更多信息。
更好的解决方案是:
if let role = jumperCablesRoles[row] as? [String] {
employeeListing.text = role.joinWithSeparator("...") // role is guaranteed to be an Array of Strings. Safe to operate on it.
} else {
// jumperCablesRoles[row] is not an array of strings, handle so here.
}
这将检查
jumperCablesRoles[row]
是否是实际的字符串数组,而不会引起爆炸,如果不能,则可以处理它。要停止投射,您还可以像下面这样指定
jumperCablesRoles
的类型:jumperCablesRoles: [[String]] = []
这将允许您直接将
jumperCablesRoles
用作:employeeListing.text = jumperCablesRoles.joinWithSeparator("...")
其次,回答有关将字符串数组转换为字符串数组(
... as! [String] as [String]
)的问题。您实际上在说这行代码是:let role = jumperCableRoles[row] as! [String] // role is an Array of Strings
let role2 = role as [String] // Specifying an object as an Array of Strings when it already is an Array of Strings. Which is trivial.