2017-02-22 36 views
-1

我試圖alphabetize數組[字符串:任何]。我到目前爲止:Swift:Alphabetize List忽略「The」

func filterList() { 
    self.titleData.sort() { 
     item1, item2 in 
     let title1 = item1["title"] as! String 
     let title2 = item2["title"] as! String 
     return title1.localizedCaseInsensitiveCompare(title2) == ComparisonResult.orderedAscending 
    } 
    self.myCollectionTableView.reloadData() 
} 

它工作正常。但是,title1和title2是電影標題,所以我想在字母表中忽略「The」,但在TableView中返回完整的一個。我試過的所有東西(比如字符串中包含「The」的子字符串)只會讓我更困惑,任何幫助都會被讚賞!

+0

寫上字符串的擴展,像'removingFirstThe',然後comaring之前調用兩個字符串。 – Alexander

回答

0

這裏的編輯,工作從@rmaddy的答案代碼:

func removeLeadingArticle(string: String) -> String { 
    let article = "the " 
    if string.characters.count > article.characters.count && string.lowercased().hasPrefix(article) { 
     return string.substring(from: string.index(string.startIndex, offsetBy: article.characters.count)) 
    } else { 
     return string 
    } 
} 

func filterList() { 
    self.titleData.sort() { 
     item1, item2 in 
     let title1 = removeLeadingArticle(string: item1["title"] as! String) 
     let title2 = removeLeadingArticle(string: item2["title"] as! String) 

     return title1.localizedCaseInsensitiveCompare(title2) == ComparisonResult.orderedAscending 
    } 
    self.myCollectionTableView.reloadData() 
} 
1

您需要刪除任何領先的「the」(或「a」或「an」可能 - 也可能與其他語言打交道),然後比較更新的標題。

這裏足以讓你開始刪除任何領先的「the」。

func removeLeadingArticle(from string: String) -> String { 
    // This is a simple example. Expand to support other articles and languages as needed 
    let article = "the " 
    if string.length > article.length && string.lowercased().hasPrefix(article) { 
     return string.substring(from: string.index(string.startIndex, offsetBy: article.length)) 
    } else { 
     return string 
    } 
} 

func filterList() { 
    self.titleData.sort() { 
     item1, item2 in 
     let title1 = removeLeadingArticle(from: item1["title"] as! String) 
     let title2 = removeLeadingArticle(from: item2["title"] as! String) 

     return title1.localizedCaseInsensitiveCompare(title2) == ComparisonResult.orderedAscending 
    } 
    self.myCollectionTableView.reloadData() 
} 

這沒有經過測試,所以可能會有一個錯字在那裏隱藏。