ios - 将 swift 类型转换为相同类型,为什么会起作用?

标签 ios arrays swift casting

为什么以下行可以在 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/

相关文章:

c++ - 将类型包装在结构中会导致额外的填充吗?

ios - 如何检查通用 swift 数组包含一个元素?

ios - 我想通过单击按钮向 UITableView 添加新行

ios - 我正在尝试实现一个可视化触摸的简单库。我不知道如何将它集成到我的项目中

arrays - Numpy.count_nonzero 在 64 位 Windows 平台上崩溃

javascript - 过滤与第二个数组中的值匹配的对象数组

ios - 无法使用类型为 'NSURL' 的参数列表调用类型为 '(fileURLWithPath: NSURL)' 的初始值设定项

ios - 集合 <__NSArrayM> 在枚举时发生了变异。

macos - 以编程方式快速清除 NSView

swift - String 到 Date 的时间转换 : 12 is becoming 00 swift