爲了與比較的你正在做我應該使用hasPrefix
或range
方法的類型更加明確:
import Foundation
let foo = "test"
let arrayValues = ["Testy", "tester", "Larry", "testing", "untested"]
// hasPrefix is case-sensitive
let filterArray = arrayValues.filter {
$0.hasPrefix(foo)
}
print(filterArray) // -> "["tester", "testing"]\n"
/* Range can do much more, including case-insensitive.
The options [.anchored, .caseInsensitive] mean the search will
only allow a range that starts at the startIndex and
the comparison will be case-insensitive
*/
let filterArray2 = arrayValues.filter {
// filters the element if foo is not found case-insensitively at the start of the element
$0.range(of: foo, options: [.anchored, .caseInsensitive]) != nil
}
print(filterArray2) // -> "["Testy", "tester", "testing"]\n"
如何定義你的arrayValues? –
var arrayValues = JSON [「array」] as? [字符串],我正在下載這個表單API –
而'print(arrayValues)'輸出是? –