为什么以下行可以在 swift 中编译并运行?
employeeListing.text = (jumperCablesRoles[row] as! [String] as [String]).joinWithSeparator("...")
看来我正在将一个字符串数组转换为一个字符串数组,我认为这是完全相同的事情。它有效,但我不知道为什么,有人可以解释一下吗?
最佳答案
好的,您的代码有几点:
首先,jumperCablesRoles[row]为! [String]
在 Swift 中是一个潜在危险的操作,因为您强制将 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.
关于ios - 将 swift 类型转换为相同类型,为什么会起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36114877/