1

I wonder if its possible to store both Data and String in a array? I need a way to store images that user picks together with the image names inside a array so I later can append it to my API request when I upload it.

Now I am using a array tuple that I later append Data and String to

var imgArray = [(Data, String)]()

Then I add data to that array tuple like this:

if let firstImage = self.firstImage {
                if let firstImageData = firstImage.compressImage() {
                    self.imgArray.append(firstImageData, self.randomImageName(length: 15))
                }

I use the code above for everyimage the user uploads and it works, imgArray gets populated with both Data and String which I later send to my API.

But is there a way to use a array to store Data and String values to?

I am not sure if tuples is the best solution }

2
  • If the Strings can be made unique, then a Dictionary might be the way to go. How are you pulling the Strings and Data out of the array? Commented Apr 11, 2017 at 17:44
  • @BallpointBen Eg pulling strings out: parameters["images"] = imgArray.map{$0.1} Commented Apr 11, 2017 at 19:20

1 Answer 1

4

Apple discourages from using tuples as data source.

Tuples are useful for temporary groups of related values. They are not suited to the creation of complex data structures. If your data structure is likely to persist beyond a temporary scope, model it as a class or structure, rather than as a tuple


The (object oriented) Swift way is a struct:

struct ImageData {
    var data : Data
    var name : String
}

var imgArray = [ImageData]()

if let firstImage = self.firstImage {
    if let firstImageData = firstImage.compressImage() {
       self.imgArray.append(ImageData(data:firstImageData, name:self.randomImageName(length: 15))
     }

The benefit is to get the members by name

let imageName = imgArray[0].name
Sign up to request clarification or add additional context in comments.

2 Comments

Great answer and a great example. But I only use my tuple above for a uploading form for blog posts. The user enters some text and adds a few images then presses upload and its done. Doesnt this count as a "temporary groups of related values"
Of course you can use a tuple, the Apple statement is more a suggestion than a necessity. However I'd prefer a struct also for better readability of the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.