Swift 4 initWithObject equivalent

New to Swift. I have an Objective-C piece of code which looks like this:

self.imageArray = [[NSMutableArray alloc] initWithObjects:@{@"name":@"James",@"image":@"1.jpg",@"Address":@"xyz"},
                  @{@"name":@"Doe",@"image":@"2.jpg",@"Address":@"xyz"},nil];

How can i use the same initWithObjects function with Swift. I have read online that we need to create an extension and then use the zip function. However from the docs it seems the zip function only takes 2 sequences. My imageArray has dictionary objects consisting of 3 different keys/values.

I tried the following, but not sure how to assign the values to the respective key:

  extension Dictionary{

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

1 answer

  • answered 2017-06-17 18:18 Rob

    In Swift, we'd probably use a native Array (designated with the [ and ]) rather than a NSMutableArray object. The Swift equivalent of your code snippet would be to use a Swift Array of Dictionary objects:

    var imageArray: [[String: String]]?
    

    And then:

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

    Having said that, you'd probably want to use custom object type:

    struct PersonImage {
        let name: String
        let image: String
        let address: String
    }
    

    Then define imageArray to be an array of PersonImage:

    var imageArray: [PersonImage]?
    

    And then

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