Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c Swift 4 initWithObject等价物_Objective C_Swift_Nsmutablearray - Fatal编程技术网

Objective c Swift 4 initWithObject等价物

Objective c Swift 4 initWithObject等价物,objective-c,swift,nsmutablearray,Objective C,Swift,Nsmutablearray,斯威夫特的新手。我有一段Objective-C代码,如下所示: self.imageArray = [[NSMutableArray alloc] initWithObjects:@{@"name":@"James",@"image":@"1.jpg",@"Address":@"xyz"}, @{@"name":@"Doe",@"image":@"2.jpg",@"Address":@"xyz"},nil]; 如何在Swift中使用相同的initWithOb

斯威夫特的新手。我有一段Objective-C代码,如下所示:

self.imageArray = [[NSMutableArray alloc] initWithObjects:@{@"name":@"James",@"image":@"1.jpg",@"Address":@"xyz"},
                  @{@"name":@"Doe",@"image":@"2.jpg",@"Address":@"xyz"},nil];
如何在Swift中使用相同的
initWithObjects
函数。我在网上读到,我们需要创建一个
扩展
,然后使用
zip
功能。然而,从文档来看,zip函数似乎只需要2个序列。My imageArray具有由3个不同键/值组成的字典对象

我尝试了以下操作,但不确定如何将值分配给相应的键:

  extension Dictionary{

        for (name, address, image) in zip(names, address, images) {
        self[name] = names
        }
    }

在Swift中,我们可能会使用本机
数组
(用
[
]
指定)而不是
NSMutableArray
对象。代码片段的Swift等价物是使用
字典
对象的Swift
数组

var imageArray: [[String: String]]?
然后:

imageArray = [["name": "James", "image": "1.jpg", "Address": "xyz"],
              ["name": "Doe",   "image": "2.jpg", "Address": "xyz"]]

话虽如此,您可能希望使用自定义对象类型:

struct PersonImage {
    let name: String
    let image: String
    let address: String
}
然后将
imageArray
定义为
PersonImage
的数组:

var imageArray: [PersonImage]?
然后

imageArray = [PersonImage(name: "James", image: "1.jpg", address: "xyz"),
              PersonImage(name: "Doe",   image: "2.jpg", address: "xyz")]

哇!通读这个解决方案,现在看起来非常简单。我应该知道这一点。我会接受答案的。谢谢