简体   繁体   中英

Replacing multiple characters in swift

I am working on an application that gets info about certain movies from a API, the API returns the genres of a movie in special int ids for each genre(28 for Action and 12 for Adventure). How would I go about changing these ids to the actual genre names? I tried using stringByReplacingOccurrencesOfString("\\(GenreIDS)", withString: "\\(GenreNames)") (GenreIDS and GenreNames are arrays) but my application crashed.

There is no one call (at least not that I know of) that will replace an array of source strings with an array of replacement strings all in one go. The method stringByReplacingOccurrencesOfString replaces all instances of one string with another string.

You need to loop through your arrays of genre IDs and genre names and call that function repeatedly. Something like this:

for (index, genreID in genreIDs.enumerated() {
   let genreName = genreNames[index]
   let genreIDString = "\(genreID)"
   let movieNames = 
      movieNames.stringByReplacingOccurrencesOfString(genreIDString, 
         withString: genreName)
}

(Note that variable names and function names should start with lower-case letters, and class names and type names should start with upper-case letters.)

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