我有一个问题,就是在一个String中连接不同的String。代码有效,但我在每个字符串之间都插入了一个单词。提前感谢您的回复。
let locality = String(self.locality)
let postalCode = String(self.postalCode)
let administrativeArea = String(self.administrativeArea)
let country = String(self.country)
let addressFull = locality + ", " + postalCode + " " + administrativeArea + ", " + country
print(addressFull)
输出
Optional("..."), Optional("...") Optional("..."), Optional("...")
答案 0 :(得分:1)
self.locality
和您的其他属性是可选字符串,因此您必须在使用它们之前安全地打开它们。
if let
的示例:
if let locality = String(self.locality), let postalCode = String(self.postalCode), let administrativeArea = String(self.administrativeArea), let country = String(self.country) {
let addressFull = locality + ", " + postalCode + " " + administrativeArea + ", " + country
print(addressFull)
}
你应该学习关于Optionals的文档,这是Swift中一个非常重要的概念。