Kirk
Kirk

Reputation: 21

String is not convertible to an Int in Swift

Swift / Xcode

I do not understand why it seems like Swift is not checking the equality for "iPicked_p and numForColorPick" in the IF statement without giving me an error that says "String is not convertible to int"

var colors: [String] = ["red", "yellow", "green", "blue", "orange", "purple", "white"]

func pickAColor (iPicked_p: String){
    for num4ColPick in colors{
        if (iPicked_p == colors[num4ColPick]){
            println ("This color is available.")
        } else{ 
            println ("Sorry, this is not an available color"){
    }

}

pickAColor = "red"

Upvotes: 2

Views: 194

Answers (3)

vadian
vadian

Reputation: 285039

As num4ColPick is an index (Int) you could enumerate the indices

for num4ColPick in colors.indices { ...

But there is a simpler way, contains

var colors = ["red", "yellow", "green", "blue", "orange", "purple", "white"]

func pickAColor (iPicked: String){
    if colors.contains(iPicked) {
        print ("This color is available.")
    } else{
        print ("Sorry, this is not an available color")
    }
}

pickAColor(iPicked: "red")

Upvotes: 0

Kirk
Kirk

Reputation: 21

So I believe the following is working for me... I do think that there is a few different ways to do this, but for the sake of closing this out I just want to post a working snippet for those looking for similar answers.

var colors: [String] = ["red", "yellow", "green", "blue", "orange", "purple", "white"]

func pickAColor (iPicked_p : String){
    println("Your color is "+"\(iPicked_p)")
    for nameOfColor in colors{
        println("\(nameOfColor)")
        if (iPicked_p == nameOfColor){
            println ("This color is available.")
            println ("\(nameOfColor)")
            let iColor = find (colors, "\(iPicked_p)")! //The ! removes the "some" in result
            println("Your color is at Index +\(iColor)")
        } else{
          // println ("Sorry, this is not a color match.")
        }
    }

}

pickAColor("white") // call the function and pass the color

Upvotes: 0

Andrew Magee
Andrew Magee

Reputation: 6684

Given that you're looping through your colors list which is a list of Strings, num4ColPick will be a String, and then you are trying to index a list of Strings by a String, but you can only index a list by a number.

You probably want to change the loop to:

for colorToCheck in colors{
    if (iPicked_p == colorToCheck){
        // ...

Upvotes: 1

Related Questions