gpt4 book ai didi

swift - 如何在 Swift 中更新变量更改时的字符串

转载 作者:行者123 更新时间:2023-11-30 10:01:52 24 4
gpt4 key购买 nike

很抱歉这个非常初学者的问题...我正在学习 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

字符串插值可帮助您从常量、变量、文字和表达式的混合组合中放入新的字符串值,方法是将它们包括在内字符串文字内的值。例如上面的文档:

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) 是否发生更改。因此,如果您希望发生这种情况,则必须在修改 message 变量后再次编写 if-else 条件,或者只创建 function > 并在消息发生更改时调用该函数。只要看看下面的代码是否有意义。尝试以不同的方式编写您的函数。

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com