Holy War: This seems wrong

This works:

["23"].map({ Int($0) }) // works

But this doesn’t, presumably because of the defaulted radix argument for public init?(_ text: String, radix: Int = default):

["23"].map(Int.init) // nope
["23"].map(Int.init(_:)) // nope

But this does work:

[("23", 10)].map(Int.init(_:radix:)) // works

and this:

zip(["23"], repeatElement(10, count: .max))
    .map(Int.init(_:radix:)) // works

What do you think? Should this splattage be splermissable or splorbidden?

 

For those who “wish for this every day”, you can always extend Int:

extension Int {
    /// provides map-specific `String` initialization
    ///
    /// e.g. `["23"].map(Int.init(string:))`
    ///
    public init?(string value: String) {
        self.init(value, radix: 10)
    }
}

2 Comments

  • Personally I think the first way is most readable at a glance. I find the `Int.init` bit pretty ugly. For simple type-to-type transformations it would be cool if `as` could do the job – `[“23”] as [Int]` is understandable even if you’ve never heard of `map` before.

  • I’ll go with the most readable option, even if it is longer. Otherwise, it may be clever, but it’s write-only code.