如何在 Swift 中将 Int 转换为 String?详细指南
大家好!我是 Swift 新手,在将数字转换为字符串时遇到了问题。我正在编写一个简单的 iOS 应用——小费计算器。我需要将最终金额显示在 UILabel 中,但编译器报错。
这是我的代码:
```swift
let totalBill: Double = 1250.50
let tipPercentage: Double = 0.15
let tipAmount = totalBill * tipPercentage
let finalAmount = totalBill + tipAmount
// 尝试输出结果
resultLabel.text = finalAmount // 错误!
```
Xcode 报错:"Cannot assign value of type 'Double' to type 'String?'"。我知道 UILabel 期望的是字符串,而不是数字。但如何正确地将 Int 或 Double 转换为 String?
我试过写 `String(finalAmount)`,但不确定这是否正确。还在网上看到不同的方法:通过字符串插值、通过 String 构造函数、通过 NSNumber。哪种方法被认为是 Swift 的最佳实践?
我特别关心:
1. 如何将 Int 转换为 String?
2. 如何将 Double 转换为 String?