Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through an array of objects in swift

Tags:

arrays

ios

swift

I'm trying to access the url of an object stored in an array, but I'm getting errors no matters what methods I'm using.

let userPhotos = currentUser?.photos      for var i = 0; i < userPhotos!.count ; ++i {         let url = userPhotos[i].url     } 

Here I get

Could not find member 'url'

and with a foreach:

for photo in userPhotos {          Utils.getImageAsync(photo.url , completion: { (img: UIImage?) -> () in          })     } 

I get:

'[ModelAttachment]?' does not have a member named 'Generator'

My array is var photos: Array<ModelAttachment>? and my ModelAttachment looks like this:

class ModelAttachment :Model { var id: String? var url: String? var thumb: String? } 

Any pointers to what I'm doing wrong would be great :)

like image 533
Kali Aney Avatar asked Jun 02 '15 12:06

Kali Aney


People also ask

How do I iterate a list in Swift?

Swift provides for-in loop for this kind of job. You use the for-in loop to iterate over a sequence, such as items in an array. This example uses a for-in loop to iterate over the subviews and set their translatesAutoresizingMaskIntoConstraints to false .


2 Answers

Unwrap and downcast the objects to the right type, safely, with if let, before doing the iteration with a simple for in loop.

if let currentUser = currentUser,      let photos = currentUser.photos as? [ModelAttachment]  {     for object in photos {         let url = object.url     } } 

There's also guard let else instead of if let if you prefer having the result available in scope:

guard let currentUser = currentUser,      let photos = currentUser.photos as? [ModelAttachment] else  {     // break or return } // now 'photos' is available outside the guard for object in photos {     let url = object.url } 
like image 191
Eric Aya Avatar answered Oct 10 '22 00:10

Eric Aya


Your userPhotos array is option-typed, you should retrieve the actual underlying object with ! (if you want an error in case the object isn't there) or ? (if you want to receive nil in url):

let userPhotos = currentUser?.photos  for var i = 0; i < userPhotos!.count ; ++i {     let url = userPhotos![i].url } 

But to preserve safe nil handling, you better use functional approach, for instance, with map, like this:

let urls = userPhotos?.map{ $0.url } 
like image 26
Sergei Avatar answered Oct 10 '22 00:10

Sergei