Extra argument 'specifier' in call error

I have a view that when I call it and try to format a double to a string I getting this error "Extra argument 'specifier' in call". I'm new to Swift and I'm stuck on this.

Calling this throws the error
TextWithTitle(title: "Price", content: "$\(3.00, specifier: "%.2f")”)

struct TextWithTitle: View {
  let title: String
  let content: String

  var body: some View {
    VStack(alignment: .leading) {
      Text(title).font(.caption)
        .foregroundColor(Color(.placeholderText))
      Text(content).font(.body)
    }
  }
}

When you’re creating a value from the string literal ("abcd"), you’ll be using one of the available string interpolations defined by StringInterpolationProtocol. The choice of interpolation depends solely on the type of the value you’re creating, meaning that all Strings use the same interpolation, while OtherString may use another. Most of the time (including String) you’ll be using DefaultStringIngerpolation.

DefaultStringInterpolation does not have \(x, specifier: y), however. The syntax is in LocalizedSteingKey.StringIngerpolation, which IIRC is only used when you’re creating LocalizedStringKey.

You can add the syntax to DefaultStringInterpolation manually, which I personally think is a hassle, or you can switch to use LocalizedStringKey (which is in SwiftUI) instead. So something like:

var content: LocalizedStringKey

Thanks for the help, it worked great! I modified the view and added another property for the specifier

struct TextWithTitle: View {
  let title: String
  let content: String
  let specifier: LocalizedStringKey?
  
  var body: some View {
    VStack(alignment: .leading) {
      Text(title).font(.caption)
        .foregroundColor(Color(.placeholderText))
      if specifier == nil {
        Text(content).font(.body)
      } else {
        Text(specifier!).font(.body)
      }
    }
  }
}

I needed to be able to use a string or string interpolation.

How about using init:

struct TextWithTitle: View {
  let title: String, content: LocalizedStringKey
    
  public init(title: String, content: LocalizedStringKey) {
    self.title = title
    self.content = content
  }
  public init(title: String, content: String) {
    self.title = title
    self.content = .init(content)
  }
  ...
}
Terms of Service

Privacy Policy

Cookie Policy