'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"
Solution 1:[1]
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){
// ...
Solution 2:[2]
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
Solution 3:[3]
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")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrew Magee |
| Solution 2 | Kirk |
| Solution 3 | vadian |
