StringInterpolation inside SwiftUI

Anyone able to get custom StringInterpolations to work inside SwiftUI Text view?


extension String.StringInterpolation {
    mutating func appendInterpolation(justDate value: Date) {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let dateString = formatter.string(from: value)
        appendLiteral(dateString)
    }
}


struct MyView: View {
    
    var body: some View {
        Text("Now: \(justDate: Date())"}) // Doesn't work
    }
    
    func test() {
        print("Now: \(justDate: Date())") // Works
    }
}

Replies

I am having a similar problem with Xcode 12.2. My extension seem to work elsewhere, but not in Text views.

My extension seem to work elsewhere, but not in Text views.

In a usual context, String interpolation literals are handled by String.
But inside Text (when used as shown in OP), it is LocalizedStringKey, not String.

You may need to define another extension for LocalizedStringKey.