2017-04-03 34 views
0

是否可以根據字符串的乞求找到NSMutableArray的索引。例如,如果我有NSMutableArray ["Joe","Jim","Jason"],並且我想查找字符串的開頭包含"Jo"的索引,那麼它將返回"Joe"的索引0。基本上只是試圖找到一個基於字符串的一部分而不是整個字符串本身的索引。在NSMutableArray中查找字符串Swift

+3

你試過什麼了嗎?爲什麼你在Swift中使用'NSMutableArray'而不是本地的Swift數組? – rmaddy

+0

@rmaddy我已經嘗試過使用'.index(of:)',並且我使用的是'NSMutableArray',因爲它是我的objective-c類中的一個變量,數據被添加到數組中。 – SpartanEngr1297

+0

Objective-C?但這個問題只涉及Swift。這是什麼? – rmaddy

回答

1

NSMutableArray符合Collection,正因爲如此,它繼承了默認方法index(where:),這確實你尋找什麼:

import Foundation 

let names = ["Joe","Jim","Jason"] 
let desiredPrefix = "Jo" 

if let index = names.index(where: { $0.hasPrefix(desiredPrefix) }) { 
    print("The first name starting with \(desiredPrefix) was found at \(index)") 
} 
else { 
    print("No names were found that start with \(desiredPrefix)") 
} 

如果你這樣做的時候,你可以清理你的代碼把它放在Collection的函數String s:

import Foundation 

extension Collection where Iterator.Element == String { 
    func first(withPrefix prefix: String) -> Self.Index? { 
     return self.index(where: { $0.hasPrefix(prefix)}) 
    } 
} 

let names = ["Joe","Jim","Jason"] 
let desiredPrefix = "Jo" 

if let index = names.first(withPrefix: desiredPrefix) { 
    print("The first name starting with \(desiredPrefix) was found at \(index)") 
} 
else { 
    print("No names were found that start with \(desiredPrefix)") 
} 
+0

當我試圖提出錯誤'參數標籤'(其中:)'不匹配任何可用的重載' – SpartanEngr1297

+0

@ SpartanEngr1297在此[Swift 3.1沙箱](http://swift.sandbox.bluemix。淨/#/ REPL/58e29dd281da4259378b9940)。你使用的是什麼版本的Swift? – Alexander

+0

同樣的版本,我在我的objective-c類的變量上調用它,例如'let index = myfirstconnection.information.index(其中:{$ 0.hasPrefix(「Jobs」)})'其中'myfirstconnection'是類的實例和'信息'是'NSMutableArray' – SpartanEngr1297