订购数组的元素(Swift)

时间:2017-11-14 14:50:26

标签: arrays swift

我有这个代码用于下载附近的地方(我正在使用Google Place API)。

if let response = response {
    self.response = response
    if response.status == "OK" {
        if let placesDownloaded = response.places {
            var number = numberPlaces / (categories?.count)!
            number = number == 0 ? 1 : number

            let firstPlace = placesDownloaded.prefix(1)

            var isRestaurant = false
            var isGym = false
            var isSpa = false
            var isBar = false
            var isNight_Club = false
            var isMuseum = false
            var isMovie_Theater = false

            for place in firstPlace {
                for type in place.types! {
                    if (type.lowercased() == "restaurant") {
                        isRestaurant = true
                    }
                    else if (type.lowercased() == "gym") {
                        isGym = true
                    }
                    else if (type.lowercased() == "spa") {
                        isSpa = true
                    }
                    else if (type.lowercased() == "bar") {
                        isBar = true
                    }
                    else if (type.lowercased() == "night_club") {
                        isNight_Club = true
                    }
                    else if (type.lowercased() == "museum") {
                        isMuseum = true
                    }
                    else if (type.lowercased() == "movie_theater") {
                        isMovie_Theater = true
                    }
                }
            }
            if(isRestaurant) && numberPlaces <= 4 {
                number = 1
            }
            else if(isGym) && numberPlaces > 1 {
                number = 1
            }
            else if(isSpa) && numberPlaces <= 6 {
                number = 1
            }
            else if(isNight_Club) && numberPlaces <= 3 {
                number = 1
            }
            else if(isMuseum) && numberPlaces <= 2 {
                number = 1
            }
            else if(isMovie_Theater) && numberPlaces <= 7 {
                number = 1
            }
            else if(isBar) && numberPlaces <= 2 {
                number = 1
            }

            places.append(contentsOf: placesDownloaded.prefix(number))
        }
    }
}

我想要做的是创建一个if语句来排序数组categories的元素。例如,像这样:

else if(isBar) && (isMuseum)  {
    // museum becomes the element [0] of `categories` and bar becomes the element [1]
}

但我真的不知道该怎么做。有人可以帮我举个例子吗?

1 个答案:

答案 0 :(得分:0)

使用Array.sorted()获取有序数组:

let sortedCategories = categories.sorted()

如果您不希望它按字母顺序排序,而是通过您自己定义的排序功能,也可以将函数传递给sorted()。例如,我得到的数组按每个字符串的长度排序,从最短到最长:

let sortedCategoriesByLength = categories.sorted { (first, second) -> Bool in
    return first.count < second.count
}