【问题标题】:Casting Syntax to Loop Through Array of Arrays in Swift在 Swift 中将语法转换为遍历数组数组
【发布时间】:2018-12-16 19:47:52
【问题描述】:

我有一个 NSArray 由在 Objective-C 中创建的字符串的 NSArrays 组成。

我现在想在 swift 类中循环遍历数组中的项目,但遇到语法问题。

原始的Objective-C Array 的数组如下所示:

NSArray* shapes =@[@[@"square",@"square.png"],@[@"circle",@"circle.png"],@[@"square",@"square.png"]];

我可以使用以下方法从 Objective-C 类中获取和打印数组:

let shapes:Array = Utilities.sharedInstance().getShapes

但是,以下循环遍历数组的代码没有编译:

var term : String = ""
var pic : String = ""
for shape in shapes  {
term  = shape[1] //ERROR HERE
pic = shape[2] //SAME ERROR HERE
            }

它给出了错误:Type 'Any' has no subscript members

循环遍历元素的正确语法是什么?

【问题讨论】:

    标签: ios objective-c arrays swift loops


    【解决方案1】:

    你可以试试

     let shapes = Utilities.sharedInstance().getShapes as! [[String]]
    

    您的 Array 元素属于 Any 类型,因此在您 cast 之前,您不能将 [] 与它们一起使用,当您使用来自 Objective-c 的桥接代码时,情况总是如此,因此您必须具体说明您使用的实际类型,我也鼓励

    struct Item {
       let term,pic:String
    }
    

    然后

    let res:[Item] = shapes.map { Item(term:$0[0],pic:$0[1]) }
    

    一个无关紧要的注释,但很重要,你可以做

    NSArray* shapes = @[@"square",@"circle",@"square"];
    

    那么附加 .png 的问题很简单,而不是直接使用 [[String]] [String]

    【讨论】:

    • 这是一个旁注,但显然 swift 中数组的第一个元素是 [1] 而不是 [0]?
    • swift 数组索引也是基于 zer0 的,对于您的情况,您可以使用 shape[2] 轻松测试它,它会导致应用程序因索引超出范围异常而崩溃
    • 好的。这更有意义。
    猜你喜欢
    • 2018-11-27
    • 2018-05-13
    • 2016-11-05
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多