【问题标题】:Swift skips an "else if"Swift 跳过“else if”
【发布时间】:2019-03-01 17:58:43
【问题描述】:
这个 Swift (Xcode) ChatBot 程序正确返回“你好”和“cookie 在哪里?”字符串。但是对于应该是“向北!”的中间两个返回“可能是任何东西”。我认为这是一个断点或多行字符串的问题,但这发生在 Xcode 工作场所和游乐场:
struct MyQuestionAnswerer {
func responseTo(question: String) -> String {
let question = question.lowercased()
let defaultNumber = question.count % 3
if question == "hello there" {
return "Why hello there"
} else if question == "where should I go on holiday?" {
return "To the North!"
} else if question == "where can I find the north pole?" {
return "To the North!"
} else if question == "where are the cookies?" {
return "In the cookie jar!"
} else if defaultNumber == 0 {
return "That really depends"
} else if defaultNumber == 1 {
return "Ask me again tomorrow"
} else {
return "Could be anything"
}
}
}
【问题讨论】:
标签:
swift
string
if-statement
return
【解决方案1】:
请阅读我在代码块中添加的 cmets
struct MyQuestionAnswerer {
func responseTo(question: String) -> String {
let question = question.lowercased() // <- Converts all the strings in your question into lower case
let defaultNumber = question.count % 3
if question == "hello there" {
return "Why hello there"
} else if question == "where should I go on holiday?" { // <- I is upper case
return "To the North!"
} else if question == "where can I find the north pole?" { // <- I is upper case
return "To the North!"
} else if question == "where are the cookies?" {
return "In the cookie jar!"
} else if defaultNumber == 0 {
return "That really depends"
} else if defaultNumber == 1 {
return "Ask me again tomorrow"
} else {
return "Could be anything"
}
}
}
所以本质上,您是在比较“i...应该在哪里”与“我应该在哪里>...",由于这个比较是假的,并且它不匹配任何其他 if 块,它会落到最后一个 else 块。
【解决方案2】:
您的问题是使用 .lowercased() - 比较两个字符串 being.lowercased
如果你使用 case 语句,这个问题对我来说看起来更好:见下文
struct MyQuestionAnswerer {
func responseTo(question: String) -> String {
let localQuestion = question.lowercased()
question == String("where can I find the north pole?").lowercased()
let defaultNumber = question.count % 3
switch localQuestion {
case String("hello there").lowercased() : return "Why hello there"
case String("where should I go on holiday?").lowercased() : return "To the North!"
case String("where can I find the north pole?").lowercased() : return "To the North!"
case String("where are the cookies?").lowercased() : return "In the cookie jar!"
default: if (defaultNumber == 0) {return "That really depends" } else {return "Could be anything"}
}
}
}