二元运算符' =='不能应用于' [String]'类型的操作数和'字符串

时间:2017-10-30 02:18:19

标签: swift

我是编码新手,我需要一些帮助来应对这一挑战。

Instructions: 
// Given the two arrays below, write a function that takes a String as an input parameter and returns a Boolean value. The function should return true if the String input is in either array and it should return false if the String input is in neither array.
//
// Examples:
// Call your function and pass in the String "cat" as the input. Your function should return true
// Call your function and pass in the String "cow" as the input. Your function should return false

let array1 = ["dog", "cat", "bird", "pig"]
let array2 = ["turtle", "snake", "lizard", "shark"]

// Write your function below:

这是我编写函数的地方:

func test(Animal:String){
    let list = array1 + array2
    for animal in list {
        if list == animal {
            print("true")
        } else {
            print("false")
        }
    }
}
test(Animal: "dog")

我得到的错误是:

Binary operator '==' cannot be applied to operands of type '[String]' and 'String under the if statement.

如果可以,请提供帮助,如果格式不正确,我会提前道歉。

谢谢!

1 个答案:

答案 0 :(得分:4)

只是一个提示,将来你应该尝试添加一个更具描述性的问题标题,这是非常模糊的,可能意味着什么。

无论如何,你的问题在于:

[String]

你得到的错误是非常具体的,并告诉你究竟出了什么问题。 String是一个字符串数组,而for animal in list只是一个项目。因此,当你在[String]中一次写下你的一只动物的时候。

不允许将动物与列表进行比较。它们的类型不同(StringString是不同的类型,因为编译器错误告诉你)。您只能比较相同类型的变量。因此,在您的情况下,列表([String]数组又名String)到另一个列表,或动物(.contains)到动物。

现在你要做的是查看你得到的字符串是否在任何一个数组中。实际上,数组中的内置方法可以让您完成此操作:func test(animal:String){ let list = array1 + array2 if list.contains(animal) { print("true") } else { print("false") } }

func test(animal:String){
    let list = array1 + array2
    print(list.contains(animal)) // will be false if it doesn't so prints false, true if it does so prints true.
}

或者如果您希望使用一些优秀的代码更加简洁,可以尝试

func test(animal:String){
    let list = array1 + array2
    for candidate in list {
        if animal == candidate { // there's a match! we can return true
            print("true ")
            return // return says to exit the function since we no longer need to keep going this is appropriate
        }
    } // for loop ends

    // we only return false once the ENTIRE for loop has run, because we know if it did exist, we would never get to this point in the code
    // this part only runs once EVERY item has been checked and none were a match
    print("false")
}

还有另一个注意事项..你要非常小心在for循环中执行if else,其中if和else都返回。在仅查看一个元素后,您不应该做出决定。

因为通常你想在打印false之前检查每个值,但是如果你有if else,你只需要检查第一个值后返回/打印。

如果你想按自己的方式去做(没有内置的方法,遍历数组)你会想做这样的事情:

String

最后,正如bilal所说,永远不要用大写字母开始变量名。通常大写字母表示其类型(如 { "compileOnSave": false, "compilerOptions": { "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es5", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2017", "dom" ], "paths": { "@services/*": ["app/services/*"] // here! } } })。你会注意到我改名为Animal - >在我的例子中为你动物