我试图发现字符串name:的每个实例都不同。
至于下面的JSON示例,我想把Alamo Draft House Lamar和Alamo Draft House Ritz拉到一个数组中。
JSON格式:

[{
"tmsId": "MV011110340000",
"rootId": "15444050",
"subType": "Feature Film",
"title": "Bohemian Rhapsody",
"releaseYear": 2018,
"releaseDate": "2018-11-02",
"titleLang": "en",
"descriptionLang": "en",
"entityType": "Movie",
"genres": ["Biography", "Historical drama", "Music"],
"longDescription": "Singer Freddie Mercury, guitarist Brian May, drummer Roger Taylor and bass guitarist John Deacon take the music world by storm when they form the rock 'n' roll band Queen in 1970. Surrounded by darker influences, Mercury decides to leave Queen years later to pursue a solo career. Diagnosed with AIDS in the 1980s, the flamboyant frontman reunites with the group for Live Aid -- leading the band in one of the greatest performances in rock history.",
"shortDescription": "Singer Freddie Mercury of Queen battles personal demons after taking the music world by storm.",
"topCast": ["Rami Malek", "Lucy Boynton", "Gwilym Lee"],
"directors": ["Bryan Singer"],
"officialUrl": "https://www.foxmovies.com/movies/bohemian-rhapsody",
"ratings": [{
    "body": "Motion Picture Association of America",
    "code": "PG-13"
}],
"advisories": ["Adult Language", "Adult Situations"],
"runTime": "PT02H15M",
"preferredImage": {
    "width": "240",
    "height": "360",
    "uri": "assets/p15444050_v_v5_as.jpg",
    "category": "VOD Art",
    "text": "yes",
    "primary": "true"
},
"showtimes": [{
    {
    "theatre": {
        "id": "9489",
        "name": "Alamo Drafthouse at the Ritz"
    },
    "dateTime": "2018-11-10T19:15",
    "barg": false,
    "ticketURI": "http://www.fandango.com/tms.asp?t=AAUQP&m=185586&d=2018-11-10"
}, {
    "theatre": {
        "id": "9489",
        "name": "Alamo Drafthouse at the Ritz"
    },
    "dateTime": "2018-11-10T22:30",
    "barg": false,
    "ticketURI": "http://www.fandango.com/tms.asp?t=AAUQP&m=185586&d=2018-11-10"
}, {
    "theatre": {
        "id": "5084",
        "name": "Alamo Drafthouse South Lamar"
    },
    "dateTime": "2018-11-10T12:00",
    "barg": false,
    "ticketURI": "http://www.fandango.com/tms.asp?t=AATHS&m=185586&d=2018-11-10"
}, {
    "theatre": {
        "id": "5084",
        "name": "Alamo Drafthouse South Lamar"
    },
    "dateTime": "2018-11-10T15:40",
    "barg": false,
    "ticketURI": "http://www.fandango.com/tms.asp?t=AATHS&m=185586&d=2018-11-10"
},
}]
}]

这是我的api代码:
var shows = [Shows]()

struct Shows: Codable {
    let showtimes: [Showtimes]

    struct Showtimes: Codable {
    let theatre: Theater

        struct Theater: Codable {
            let id: String
            let name: String
        }

    }
}

func loadShowtimes() {

    let apiKey = ""
    let today = "2018-11-10"
    let zip = "78701"
    let filmId = "MV011110340000"
    let radius = "15"
    let url = URL(string: "http://data.tmsapi.com/v1.1/movies/\(filmId)/showings?startDate=\(today)&numDays=5&zip=\(zip)&radius=\(radius)&api_key=\(apiKey)")
    let request = URLRequest(
        url: url! as URL,
        cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData,
        timeoutInterval: 10 )

    let session = URLSession (
        configuration: URLSessionConfiguration.default,
        delegate: nil,
        delegateQueue: OperationQueue.main
    )

    let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
        if let data = data {
            do { let shows = try! JSONDecoder().decode([Shows].self, from: data)
                self.shows = shows

            }
        }
    })

    task.resume()

}

我如何对数组进行排序,并发现name:的每个实例都不同,然后取每个名称并将它们放入一个新数组中?

最佳答案

有几种方法可以遍历Shows数组及其Theater数组以获得完整的名称列表。一旦你有了完整的名单,你可以得到一个唯一的名单,这些名字。
以下是一种方法:

let names = Array(Set(shows.map { $0.showtimes.map { $0.theatre.name }}.reduce([]) { $0 + $1 }))

让我们把它分开,以便更好地解释发生了什么事。
let allNames = shows.map { $0.showtimes.map { $0.theatre.name }}.reduce([]) { $0 + $1 }
let uniqueNames = Array(Set(allNames))

shows.map遍历Shows中的每个shows。内部map依次迭代每个Theatre中的每个Shows,返回其name。所以内部map给出了一个名称数组。第一个map产生一个名称数组。reduce将这些名称数组合并为一个名称数组,剩下allNames和一个包含每个名称的数组。
使用Array(Set(allNames))首先创建一个唯一的名称集,然后从该名称集创建一个数组。
如果希望最终结果按字母顺序排序,请在末尾添加.sorted()
如果您需要保持原来的顺序,您可以使用NSOrderedSet并删除sorted的任何用法。
let names = NSOrderedSet(array: shows.map { $0.showtimes.map { $0.theatre.name }}.reduce([]) { $0 + $1 }).array as! [String]

关于ios - 通过JSON排序以查找字符串不同的每个实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53244081/

10-10 17:45
查看更多