在 Xcode11 Beta 4 中将 String(format: , args) 与 SwiftUI 一起使用时出错 [英] Error using String(format: , args) with SwiftUI in Xcode11 Beta 4
问题描述
升级到 Xcode 11 Beta 4 后,我在使用 String(format: , args)
和 @State
属性时开始看到错误.请参阅下面的代码.第二个 Text
行抛出错误:
After upgrading to Xcode 11 Beta 4, I starting seeing an error when using String(format: , args)
with @State
property. See code below. Second Text
line throws an error:
没有更多上下文的表达式类型字符串"是不明确的
Expression type 'String' is ambiguous without more context
而 Text
s 1、3 和 4 工作得很好.
while Text
s 1, 3, and 4 work just fine.
struct ContentView : View {
@State var selection = 2
var body: some View {
VStack {
Text("My selection \(selection)") // works
Text("My selection \(String(format: "%02d", selection))") // error
Text("My selection \(String(format: "%02d", Int(selection)))") // works
Text("My selection \(String(format: "%02d", $selection.binding.value))") // works
}
}
}
我知道这是 Beta 版软件,但很好奇是否有人能看到这种行为的原因,或者这只是一个错误.如果这不能解释,我会提交雷达.
I realize this is Beta software, but was curious if anyone can see a reason for this behavior or is this simply a bug. If this can't be explained, I'll file a radar.
推荐答案
在 beta 4 中,属性包装器实现略有变化.在 beta 3 中,您的 View 被编译器重写为:
In beta 4, the property wrapper implementation changed slightly. In beta 3, your View was rewritten by the compiler as:
internal struct ContentView : View {
@State internal var selection: Int { get nonmutating set }
internal var $selection: Binding<Int> { get }
@_hasInitialValue private var $$selection: State<Int>
internal var body: some View { get }
internal init(selection: Int = 2)
internal init()
internal typealias Body = some View
}
在 Beta 4 上,它会这样做:
while on Beta 4, it does this:
internal struct ContentView : View {
@State @_projectedValueProperty($selection) internal var selection: Int { get nonmutating set }
internal var $selection: Binding<Int> { get }
@_hasInitialValue private var _selection: State<Int>
internal var body: some View { get }
internal init(selection: Int = 2)
internal init()
internal typealias Body = some View
}
现在我在猜测:这个变化让编译器更难推断你的变量的类型?请注意,另一个有效的替代方法是通过将 selection 强制转换为 Int
来帮助编译器:
Now I am guessing: this change makes it more difficult for the compiler to infer the type of your variable? Note that another alternative that does work, is helping the compiler a little, by casting selection as Int
:
Text("My selection \(String(format: "%02d", selection as Int))")
这篇关于在 Xcode11 Beta 4 中将 String(format: , args) 与 SwiftUI 一起使用时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!