2017-02-22 54 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() 
} 

这没有经过测试,所以可能会有一个错字在那里隐藏。