在 SwiftUI 中的哪里声明扩展?
Where to declare extensions in SwiftUI?
我在 ContentView 的末尾声明了 Double 的扩展。但它显示错误 "Initializeer 'init(_:) requires that 'Double' conform to 'StringProtocol'".
struct ContentView : View {
@State var demo: Double = 0
var body: some View {
VStack {
Slider(value: $demo, from: 0.0, through: 100.0, by: 0.01)
.padding()
Text(demo.roundTo(places: 5))
}
}
}
extension Double {
public func roundTo(places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}
文本视图需要一个字符串。将您的文本视图更改为:
Text("\(demo.roundTo(places: 5))")
在 Swift 中,字符串插值是使用 \()
完成的。
例如:
let age = 20
print("I am \(age) years old")
有关更多信息,请访问苹果的 swift docs
我在 ContentView 的末尾声明了 Double 的扩展。但它显示错误 "Initializeer 'init(_:) requires that 'Double' conform to 'StringProtocol'".
struct ContentView : View {
@State var demo: Double = 0
var body: some View {
VStack {
Slider(value: $demo, from: 0.0, through: 100.0, by: 0.01)
.padding()
Text(demo.roundTo(places: 5))
}
}
}
extension Double {
public func roundTo(places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}
文本视图需要一个字符串。将您的文本视图更改为:
Text("\(demo.roundTo(places: 5))")
在 Swift 中,字符串插值是使用 \()
完成的。
例如:
let age = 20
print("I am \(age) years old")
有关更多信息,请访问苹果的 swift docs