arrays - 确定字符串来自哪个数组

标签 arrays swift loops contains

我有 3 个动物数组:

let mammals = ["Dog", "Cat", "Bear"]
let fish = ["Clownfish", "Seahorse", "Scorpion Fish"]
let reptiles = ["Chameleon", "Snake", "Lizard"]

一个按钮随机生成一个动物,然后将它附加到一个 allAnimals 数组中。我希望能够确定字符串(动物)来自哪个数组。

我试过用

allAnimals.contains()

然而,它显式地接受一个 var 作为参数。我可以做 allAnimals.contains("Seahorse") 就好了。但我需要能够检查所有数组。

我还尝试遍历数组。

for i in allAnimals {
  if i.contains(mammals){ print("Came from the Mammal array") }
  else if i.contains(fish){ print("Came from the Fish array") }
  else if i.contains(reptiles){ print("Came from the Reptiles array") }
}

抛出错误:

Cannot convert value of type '[String]' to expected argument type 'String'

如何确定随机字符串来自哪个数组?

最佳答案

您可以用不同的动物类型定义一个枚举,并构造该枚举动物类型的数组,其中枚举中每个案例的关联值 (String) 给出了动物的详细信息。

例如

enum Animal: CustomStringConvertible {
    case mammal(String)
    case fish(String)
    case reptile(String)

    var description: String {
        switch self {
        case .mammal: return "Mammal"
        case .fish: return "Fish"
        case .reptile: return "Reptile"
        }
    }

    var species: String {
        switch self {
        case .mammal(let s), .fish(let s), .reptile(let s): return s
        }
    }
}

示例用法:

let mammals = ["Dog", "Cat", "Bear"].map(Animal.mammal)
let fish = ["Clownfish", "Seahorse", "Scorpion Fish"].map(Animal.fish)
let reptiles = ["Chameleon", "Snake", "Lizard"].map(Animal.reptile)

let allAnimals = [reptiles[2], mammals[1]]

for animal in allAnimals {
    print("\(animal.species) is a \(animal)")
} /* Lizard is a Reptile
     Cat is a Mammal     */

关于arrays - 确定字符串来自哪个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41248312/

相关文章:

java - 尽管Java中没有任何错误,但在输入Char之前代码崩溃

c# - C# 与 C/C++ 中的静态数组

java - 从 Libgdx 的表中删除行时出错

swift - 搜索栏过滤 TableView swift 4

c++ - 使用 For 循环对队列进行入队和出队 - C++

c - 在 C 中存储/访问字符串数组中的下一个元素

php - PHP 中的多维数组

ios - 如何在 objective-c 中使用 swift 类(不是类的实例)

c - 我的第一个循环不起作用

ios - RxSwift 跟踪多个 observables 事件