升级到Xcode 11 Beta 4之后,在String(format: , args)
与@State
property一起使用时,我开始看到错误。请参见下面的代码。第二Text
行抛出一个错误:
表达式类型“字符串”不明确,没有更多上下文
而Text
s 1、3和4可以正常工作。
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版软件,但很好奇是否有人可以看到此行为的原因,或者仅仅是一个错误。如果无法解释,我将提交雷达报告。
在beta 4中,属性包装器的实现略有变化。在beta 3中,编译器将View重写为:
internal struct ContentView : View {
@State internal var selection: Int { get nonmutating set }
internal var $selection: Binding { get }
@_hasInitialValue private var $$selection: State
internal var body: some View { get }
internal init(selection: Int = 2)
internal init()
internal typealias Body = some View
}
在Beta 4上,它执行以下操作:
internal struct ContentView : View {
@State @_projectedValueProperty($selection) internal var selection: Int { get nonmutating set }
internal var $selection: Binding { get }
@_hasInitialValue private var _selection: State
internal var body: some View { get }
internal init(selection: Int = 2)
internal init()
internal typealias Body = some View
}
现在我正在猜测:此更改使编译器更难推断变量的类型吗?注意,另一个可行的替代方法是通过强制转换来帮助编译器selection as Int
:
Text("My selection \(String(format: "%02d", selection as Int))")