Confusing compilation error with @Published

This code won't compile. If I remove the @Published, it's compiles, as expected. What does the error message mean?

import SwiftUI
class Thing : ObservableObject {
    @Published var title: String = ""
    func foo() {
        let str = String(format: "title: %@", title) // error here
        print(str)
    }
}

Error: Expression type 'String' is ambiguous without more context

Xcode underlines in red the "S" of "String" on that line.

Change it to String(format: "title: %@", title as NSString) (or as CVarArg - doesn't matter)

Any idea why? Is it a bug? @Published is not supposed to be changing the types of my properties.

Please file a bug report at bugs.swift.org

Yeah, looks like a bug to me. It seems like the constraint solver is rejecting the solution because Thing does not conform to CVarArg:

(attempting fix [fix: add missing protocol conformance] @ locator@0x7fd5b4801948 [UnresolvedDot@/Users/suyashsrijan/Desktop/test.swift:10:41 -> member])

If I add the conformance, it compiles fine.

Here's a reproducer without SwiftUI:

import Foundation

@propertyWrapper 
struct Wrapper {
  var wrappedValue: String
}

class Foo {
  @Wrapper var bar: String = ""
  
  func foo() {
    let str = String(format: "bar: %@", bar) // expression type 'String' is ambiguous without more context
  }
}

Please file a bug at bugs.swift.org

1 Like

Actually, this compiles fine on master.

I just do this instead:

String(format: "%.2f", arguments: [self.amount])

Terms of Service

Privacy Policy

Cookie Policy