抱歉,这个非常初学者的问题...我正在学习编码Swift。
我正在定义一个变量,然后根据其值打印条件消息。当我将变量更改为另一个值时,我希望消息字符串会更改,但不会更改。我究竟做错了什么?
这是代码:
//: Playground - noun: a place where people can play
import Cocoa
var str = "Hello, playground"
var townname = "Azadinos"
var population: Int = 5422
var message: String
var Haspostoffice: Bool = true
if population < 10000 {
message = "with a population of \(population), \(townname) is a small town"
} else if population >= 10000 && population < 15000 {
message = "with a population of \(population), \(townname) is a medium sized town!"
}else {message = "\(townname) is a huge town!"}
print (message)
population = 250000
print (population)
print(message)
我希望第二个消息与第一个消息不同,但是没有。我究竟做错了什么?
非常感谢
最佳答案
您应该通过Swift Documentation中的String Interpolation
String interpolation
通过将string
的值包含在constants, variables, literals, and expressions
中,可以帮助您从string literal
的混合组合中输入新的why it is not updating for second message
值。例如上面的文档:
let multiplier = 3 //This is constant
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message prints : "3 times 2.5 is 7.5"
这是您的工作代码:
var townname = "Azadinos"
var population: Int = 5422
var message: String
var Haspostoffice: Bool = true
if population < 10000 {
message = "with a population of \(population), \(townname) is a small town"
} else if population >= 10000 && population < 15000 {
message = "with a population of \(population), \(townname) is a medium sized town!"
} else {
message = "\(townname) is a huge town!"
}
print (message)
population = 250000
print (population)
print(message)
现在作为问题
if-else
,您应该编写一个函数,然后对变量进行更改。因为您的代码以单流程运行,所以在最后一行开始和结束。您的variable(message)
条件不知道if-else
是否发生变化。因此,如果您希望这种情况发生,则必须在修改message
变量后再次编写function
条件,或者只是创建message
并在更改后调用该函数。如果有意义,请看下面的代码。尝试以不同的方式编写函数。var townname = "Azadinos"
var population: Int = 5422
var message = ""
var Haspostoffice: Bool = true
func printMyVars() {
if population < 10000 {
message = "with a population of \(population), \(townname) is a small town"
} else if population >= 10000 && population < 15000 {
message = "with a population of \(population), \(townname) is a medium sized town!"
} else {
message = "\(townname) is a huge town!"
}
print(message)
}
printMyVars()
population = 250000
printMyVars()
打印:
with a population of 5422, Azadinos is a small town
Azadinos is a huge town!
关于swift - 如何在Swift中更改变量时更新字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38066226/