简体   繁体   English

在swift中替换多个字符

[英]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). 我正在开发一个应用程序,它从API获取某些电影的信息,API返回每个类型的特殊int id中的电影类型(28个用于Action,12个用于Adventure)。 How would I go about changing these ids to the actual genre names? 我如何将这些ID更改为实际的流派名称? I tried using stringByReplacingOccurrencesOfString("\\(GenreIDS)", withString: "\\(GenreNames)") (GenreIDS and GenreNames are arrays) but my application crashed. 我尝试使用stringByReplacingOccurrencesOfString("\\(GenreIDS)", withString: "\\(GenreNames)") (GenreIDS和GenreNames是数组)但我的应用程序崩溃了。

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. 方法stringByReplacingOccurrencesOfString用一个字符串替换一个字符串的所有实例。

You need to loop through your arrays of genre IDs and genre names and call that function repeatedly. 您需要遍历您的流派ID和流派名称数组并重复调用该函数。 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.) (请注意,变量名称和函数名称应以小写字母开头,类名称和类型名称应以大写字母开头。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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