Why calling this way: .map(String.init(localized:)) on an array of String.LocaizationValue do not compile?

Just simply changing it to:

.map { String.init(localized: $0) }

works?

Test:

import SwiftUI

struct Foo {
    init(localized: String.LocalizationValue) { }
}

struct ContentView: View {
    let genresAA = Array<String.LocalizationValue>(["Pop", "Rock", "Electronic"]).map { String.init(localized: $0) }  // String.init(localized:) exist!

    let genresBB = Array<String.LocalizationValue>(["Pop", "Rock", "Electronic"]).map(Foo.init(localized:)) // my own struct this form works!!

    // but String.init(localized:) do not compile:
    // compile errors: Generic parameter 'T' could not be inferred
    //                 Type 'String' has no member 'init(localized:)'
    //             v                                                                         v
    let genresXX = Array<String.LocalizationValue>(["Pop", "Rock", "Electronic"]).map(String.init(localized:))

    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}

Edit: it seem String.init(localized:) is odd: Xcode jump to definition cannot find it. Maybe it's some kind of strange thing? Maybe it's not a function?

Okay, never mind, its full signature is:

Try

struct Foo {
    init(localized: String, x: Int = 0) { }
}

PS

You can remove ContentView for an even smaller example.

I think I understand func/init with param with default value cannot omit any param labels when use as a closure. You must use the full signature:

Foo.init(localized:x:)

and needs to be given two parameters. Whereas calling it:

Foo(localized: "blah")

the compiler supply the x: 0 for you at the call site so it becomes:

Foo(localized: "blah", x: 0)
Terms of Service

Privacy Policy

Cookie Policy