[英]How do I search an array of strings and return a specific value in swift?
I'm new to swift and I'm trying to search an array of strings and return a specific value, for example let's say i want to search my array and check if contains mango, if it does then I would like to print that. 我是Swift的新手,正在尝试搜索字符串数组并返回特定值,例如,假设我要搜索我的数组并检查是否包含芒果,如果它包含芒果,那么我想打印该芒果。
var fruitArray: Array = ["Banana", "Apple", "Mango", "Strawberry", "blueberry"]
fruitArray.append("Orange")
for fruits in fruitArray{
print(fruits)
}
You don't need to iterate over the array yourself. 您不需要自己遍历数组。
let searchTerm = "Mango"
if fruitArray.contains(searchTerm) {
print(searchTerm)
}
You can use collection's method firstIndex(of:)
to find the index of the element on your collection and access the element through subscript or if the index of the element is irrelevant you can use first(where:)
to find the first element that matches your element or any predicate you may need: 您可以使用集合的方法
firstIndex(of:)
查找集合上元素的索引并通过下标访问该元素,或者如果该元素的索引不相关,则可以使用first(where:)
查找与之匹配的第一个元素您的元素或您可能需要的任何谓词:
var fruits = ["Banana", "Apple", "Mango", "Strawberry", "blueberry"]
fruits.append("Orange")
if let firstIndex = fruits.firstIndex(of: "Mango") {
print(fruits[firstIndex]) // Mango
// if you need to replace the fruit
fruits[firstIndex] = "Grape"
print(fruits) // "["Banana", "Apple", "Grape", "Strawberry", "blueberry", "Orange"]\n"
}
or 要么
if let firstMatch = fruits.first(where: { $0.hasSuffix("go")}) {
print(firstMatch) // Mango
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.