在 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 行抛出错误:

Expression type 'String' is ambiguous without more context

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
        }
    }
}

我知道这是 Beta 版软件,但很好奇是否有人能看出此行为的原因,或者这只是一个错误。如果这无法解释,我会提交一个雷达。

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

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 中,它会这样做:

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 as Int:

来帮助编译器
Text("My selection \(String(format: "%02d", selection as Int))")

更新 (Xcode 11.2)

我也收到错误:

'inout Path' is not convertible to '@lvalue Path'

使用此代码:

struct ContentView : View {
    @State var selection = 2

    var body: some View {
        VStack {
            Text(String(format: "%d", selection)) // does not work
        }
    }
}

通过添加 $ 前缀然后在 String(format:, args:) 中访问 wrappedValue 解决:

struct ContentView : View {
    @State var selection = 2

    var body: some View {
        VStack {
            Text(String(format: "%d", $selection.wrappedValue)) // works
        }
    }
}