在Xcode11 Beta 4中将String(format:,args)与SwiftUI一起使用时出错

ODY*_*Kon 2 xcode swiftui xcode11

升级到Xcode 11 Beta 4之后,在String(format: , args)@Stateproperty一起使用时,我开始看到错误。请参见下面的代码。第二Text行抛出一个错误:

表达式类型“字符串”不明确,没有更多上下文

Texts 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我意识到这是Beta版软件,但很好奇是否有人可以看到此行为的原因,或者仅仅是一个错误。如果无法解释,我将提交雷达报告。

kon*_*iki 7

在beta 4中,属性包装器的实现略有变化。在beta 3中,编译器将View重写为:

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
}
Run Code Online (Sandbox Code Playgroud)

在Beta 4上,它执行以下操作:

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
}
Run Code Online (Sandbox Code Playgroud)

现在我正在猜测:此更改使编译器更难推断变量的类型吗?注意,另一个可行的替代方法是通过强制转换来帮助编译器selection as Int

Text("My selection \(String(format: "%02d", selection as Int))")
Run Code Online (Sandbox Code Playgroud)