是否可以根據字符串的乞求找到NSMutableArray的索引。例如,如果我有NSMutableArray ["Joe","Jim","Jason"]
,並且我想查找字符串的開頭包含"Jo"
的索引,那麼它將返回"Joe"
的索引0
。基本上只是試圖找到一個基於字符串的一部分而不是整個字符串本身的索引。在NSMutableArray中查找字符串Swift
回答
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)")
}
當我試圖提出錯誤'參數標籤'(其中:)'不匹配任何可用的重載' – SpartanEngr1297
@ SpartanEngr1297在此[Swift 3.1沙箱](http://swift.sandbox.bluemix。淨/#/ REPL/58e29dd281da4259378b9940)。你使用的是什麼版本的Swift? – Alexander
同樣的版本,我在我的objective-c類的變量上調用它,例如'let index = myfirstconnection.information.index(其中:{$ 0.hasPrefix(「Jobs」)})'其中'myfirstconnection'是類的實例和'信息'是'NSMutableArray' – SpartanEngr1297
- 1. Swift:將字符串轉換爲NSMutableArray
- 2. 在字符串中查找字符串
- 3. 在字符串中查找字符串
- 4. Swift - 在字符串中的兩個位置之間查找子字符串
- 5. 在Swift中查找字符串中的空格數
- 6. 在字符串中查找字符
- 7. 查找字符串中的字符串
- 8. 查找字符串中的字符串
- 9. 查找字符串中的字符串
- 10. 在Swift中查找字符串數組的方式
- 11. 在字符串C++中查找子字符串(在「hello」中查找「el」)
- 12. 在輸入字符串中查找字符串中的子串
- 13. 如何查找Swift字符串中子字符串的最後一次出現?
- 14. 檢查NSMutableArray是否包含字符串
- 15. 在字符串中查找數字
- 16. 在字符串lua中查找數字
- 17. 在字符串中查找數字
- 18. 查找字符串中的
- 19. 在字符串中插入字符(Swift)
- 20. 查找字符串
- 21. 查找字符串
- 22. 查找字符串
- 23. 查找字符串
- 24. 查找字符串
- 25. 查找字符串
- 26. 查找字符串
- 27. 查找字符串
- 28. 查找字符串
- 29. 查找字符串
- 30. 查找字符串
你試過什麼了嗎?爲什麼你在Swift中使用'NSMutableArray'而不是本地的Swift數組? – rmaddy
@rmaddy我已經嘗試過使用'.index(of:)',並且我使用的是'NSMutableArray',因爲它是我的objective-c類中的一個變量,數據被添加到數組中。 – SpartanEngr1297
Objective-C?但這個問題只涉及Swift。這是什麼? – rmaddy