Argument type 'LanguageItem?' does not conform to expected type 'CVarArg'

I have the following code:

let obj: LanguageItem? = LanguageItem(language: "zh-CN")
// Argument type 'LanguageItem?' does not conform to expected type 'CVarArg'
print(String(format:"obj: %@", obj))

struct LanguageItem: Codable
{
    var language: String
    var name: String?
}

How can I make my class work with String(format:)?

That's logical.

%@ expects a String parameter. LanguageItem is not a String.

What do you want to print ?

You have several options:

  • pass the language property
print(String(format:"obj: %@", (obj?.language ?? "")))
  • if you want to print the compete struct, create a description var:
struct LanguageItem: Codable {
    var language: String
    var name: String?
    
    var description: String {
        return language + (name ?? "")
    }
}
let obj: LanguageItem? = LanguageItem(language: "zh-CN")

print(String(format:"obj: %@", (obj?.description ?? "")))

How can I make my class work with String(format:)?

The technically correct approach is to conform your type to CustomStringConvertible:

https://developer.apple.com/documentation/swift/customstringconvertible/

Argument type 'LanguageItem?' does not conform to expected type 'CVarArg'
 
 
Q