2015-09-06 26 views
11

Mã bên dưới hoạt động để sắp xếp một chuỗi các chuỗi nếu chúng là chữ thường hoặc tất cả chữ hoa nhưng tôi muốn bỏ qua trường hợp khi tôi sắp xếp. Làm thế nào tôi có thể làm điều này? Sau đây là một mảng của một lớp tùy chỉnh.Sắp xếp một mảng String và bỏ qua trường hợp

resultListArray.sort({ $0.fileName.compare($1.fileName) == NSComparisonResult.OrderedAscending })

Trả lời

20

Bạn có thể sử dụng phương pháp Chuỗi localizedCompare()

update: Xcode 8.2 • Swift 3.0.2

let array = ["def","Ghi","Abc" ] 

let sorted1 = array.sorted{$0.compare($1) == .orderedAscending} 
print(sorted1) // ["Abc", "Ghi", "def"] 

let sorted2 = array.sorted{$0.localizedCompare($1) == .orderedAscending} 
print(sorted2) // ["Abc", "def", "Ghi"] 


// you can also use the String compare options parameter to give you more control when comparing your strings 
let sorted3 = array.sorted{$0.compare($1, options: .caseInsensitive) == .orderedAscending } 
print(sorted3) // ["Abc", "def", "Ghi"]\n" 

// which can be simplifyed using the string method caseInsensitiveCompare 
let sorted4 = array.sorted{$0.caseInsensitiveCompare($1) == .orderedAscending} 
print(sorted4) // ["Abc", "def", "Ghi"]\n" 

// or localized caseInsensitiveCompare 
let array5 = ["Cafe B","Café C","Café A"] 
let sorted5 = array5.sorted{$0.localizedCaseInsensitiveCompare($1) == .orderedAscending} 
print(sorted5) // "["Café A", "Cafe B", "Café C"]\n" 
+2

Tuyệt vời cảm ơn bạn! –

+0

@GaryDorman bạn được chào đón –

1

Dưới đây là an answer about overriding compareTo in Java để thay đổi cách sort lệnh điều. Điều gì xảy ra nếu bạn chuyển đổi chuỗi thành chữ hoa, sau đó so sánh chúng?

+1

Tôi lập trình trong Swift. Thông thường tôi chỉ có thể chuyển đổi các chuỗi thành chữ hoa hoặc chữ thường nhưng đó không phải là một lựa chọn thời gian này. –

+0

Ồ, xin lỗi tôi. Tôi đã đọc sai thẻ. Xem câu hỏi này, sau đó: https://stackoverflow.com/questions/31871395/swift-2-iterating-and-upper-lower-case-some-characters – Davislor

+1

Làm cho nó hoạt động. Cảm ơn bạn! –

6

Bạn có thể chuyển đổi các String thành chữ thường và sau đó so sánh nó:

array.sort{ $0.lowercaseString < $1.lowercaseString } 
1

Đây là phương pháp nên được sử dụng và dành cho mục đích này:

public func caseInsensitiveCompare(aString: String) -> NSComparisonResult 

Trong trường hợp của bạn:

resultListArray.sort({ $0.fileName.caseInsensitiveCompare($1.fileName) == NSComparisonResult.OrderedAscending }) 
Các vấn đề liên quan