【问题标题】:Error using String(format: , args) with SwiftUI in Xcode11 Beta 4在 Xcode11 Beta 4 中将 String(format: , args) 与 SwiftUI 一起使用时出错
【发布时间】:2019-07-18 02:19:46
【问题描述】:

升级到 Xcode 11 Beta 4 后,我在使用 String(format: , args)@State 属性时开始看到错误。请参阅下面的代码。第二个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
        }
    }
}

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

【问题讨论】:

    标签: xcode swiftui xcode11


    【解决方案1】:

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

    在 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))")
    

    【讨论】:

    • 这份搜查令是否提交雷达?
    • 好问题。我想它不会受伤,对吗?
    • 我向苹果提交了反馈。我们会看看会发生什么,如果他们回应,我会更新。
    【解决方案2】:

    更新(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
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 2020-01-28
      • 2013-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多