简体   繁体   中英

How to convert model to arrays in iOS swift3

from the below code, How can I take two different arrays of movie and genre. Then I need to use that models with these two arrays?Could anyone guide me to do this task.

models = [
        Model(movie:"The Dark Night", genre:"Action"),
        Model(movie:"The Avengers", genre:"Action"),
        Model(movie:"Logan", genre:"Action"),
        Model(movie:"Shutter Island", genre:"Thriller"),
        Model(movie:"Inception", genre:"Thriller"),
        Model(movie:"Titanic", genre:"Romance"),
        Model(movie:"La la Land", genre:"Romance"),
        Model(movie:"Gone with the Wind", genre:"Romance"),
        Model(movie:"Godfather", genre:"Drama"),
        Model(movie:"Moonlight", genre:"Drama")
    ]

I am not able to figure out the purpose of the segregating movie and genre in separate array . However this can be done as follows :

var movies = [String]()
var genres = [String]()
for model in models {
    movies.append(model.movie)
    genres.append(model.genre)
}

And in more swifty way :

var movies = models.map{$0.movie}
var genres = models.map{$0.genre}

Instead of segregating them, it can be used as model.movie and model.genre anywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM