gpt4 book ai didi

ios - 我如何根据以下需求对 NSArray 进行排序/过滤?

转载 作者:搜寻专家 更新时间:2023-11-01 05:58:56 26 4
gpt4 key购买 nike

有人可以告诉我一种以正确方式过滤/排序我的数组的方法吗?

我目前拥有的 Playground 如下:

//: Playground - noun: a place where people can play

import UIKit

var candidates: NSArray = ["Berlin-Lichtenberg", "Berlin-Lichterfelde Ost", "Berlin-Lichterfelde West", "Braunsdorf-Lichtenwalde", "Darmstadt-Lichtwiese", "Lichtenberg (Erzgeb)", "Lichtenfels", "Lichtenrade", "Lichtenstein (Sachs)", "Lichtentanne (Sachs)", "Lichtentanne (Thür)", "Lichtenthal", "Lichterfelde Süd", "Rostock Lichtenhagen", "Hamburg", "München", "Köln", "Bonn"]

var root = "Licht"

var predicate = NSPredicate(format: "(SELF BEGINSWITH[c] %@) OR (SELF MATCHES[c] %@)", root, NSString(format: ".*[^\\w]%@.*", root))

var filteredArray = NSMutableArray(array: candidates.filteredArrayUsingPredicate(predicate))

println(filteredArray)

这将打印出以下内容:

(
"Berlin-Lichtenberg",
"Berlin-Lichterfelde Ost",
"Berlin-Lichterfelde West",
"Braunsdorf-Lichtenwalde",
"Darmstadt-Lichtwiese",
"Lichtenberg (Erzgeb)",
Lichtenfels,
Lichtenrade,
"Lichtenstein (Sachs)",
"Lichtentanne (Sachs)",
"Lichtentanne (Thu\U0308r)",
Lichtenthal,
"Lichterfelde Su\U0308d",
"Rostock Lichtenhagen"
}

这一切都很好,但我需要的数组排序是不同的,我没有做对:(

它应该是这样的:

(
"Lichtenberg (Erzgeb)",
Lichtenfels,
Lichtenrade,
"Lichtenstein (Sachs)",
"Lichtentanne (Sachs)",
"Lichtentanne (Thu\U0308r)",
Lichtenthal,
"Lichterfelde Su\U0308d",
"Berlin-Lichtenberg",
"Berlin-Lichterfelde Ost",
"Berlin-Lichterfelde West",
"Braunsdorf-Lichtenwalde",
"Darmstadt-Lichtwiese",
"Rostock Lichtenhagen"
)

所以我需要以我搜索的字符串(根)开头的结果,它是“Licht”开头的,然后它应该显示它只包含在的其他字符串。

我怎样才能做到这一点?

最佳答案

我建议使用 Swift Array 类型而不是 NSArray,并使用 filter 结合 sort 方法,它采用闭包来确定2 个元素的排序顺序。

在您的情况下,它将实现为:

var candidates = ["Berlin-Lichtenberg", "Berlin-Lichterfelde Ost", "Berlin-Lichterfelde West", "Braunsdorf-Lichtenwalde", "Darmstadt-Lichtwiese", "Lichtenberg (Erzgeb)", "Lichtenfels", "Lichtenrade", "Lichtenstein (Sachs)", "Lichtentanne (Sachs)", "Lichtentanne (Thür)", "Lichtenthal", "Lichterfelde Süd", "Rostock Lichtenhagen", "Hamburg", "München", "Köln", "Bonn"]

let root = "Licht"

var results = candidates.filter {
$0.rangeOfString(root) != nil
}.sorted { (lhs: String, rhs: String) -> Bool in
if startsWith(lhs, root) {
if (startsWith(rhs, root)) {
// Both start with root, so return the string comparison
return lhs < rhs
}
// lhs starts with root, rhs doesn't, so lhs comes first
return true
}

// rhs starts with root, lhs doesn't, so rhs comes first
if (startsWith(rhs, root)) {
return false
}

// return the normal string comparison
return lhs < rhs
}

关于ios - 我如何根据以下需求对 NSArray 进行排序/过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29670125/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com