字符串是不可转换为int在斯威夫特
问题描述:
斯威夫特/ Xcode的字符串是不可转换为int在斯威夫特
我不明白为什么看起来斯威夫特不检查IF语句中的“iPicked_p和numForColorPick”平等不给我一个错误,指出“字符串是不能转换成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"
答
假设你通过你的colors
列表,它是String
个列表循环,num4ColPick
将是一个String
,然后你想指数String
列表s由String
,但你只能索引一个列表由一个数字。
你可能想改变环路:
for colorToCheck in colors{
if (iPicked_p == colorToCheck){
// ...
答
所以我认为这是为我工作如下...我认为有几个不同的方法可以做到这一点,但为求关闭此我只想发布一个工作片段寻找类似的答案。
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
除了编译器错误,此代码中的逻辑也是错误的,它不会给出所需的输出。你想使用'contains'函数来代替。 – 2015-02-23 10:32:03
嗨康拉德,并感谢您的意见。我会查找该功能。 – Kirk 2015-02-23 18:04:01