Swift: Init a lovely day?

Swift 2.0 introduced .init, which offers functional access to initialization. You can construct an array of strings from integers by mapping String.init:

[1, 2, 3, 4, 5, 6].map(String.init)

Contrast with the old construction, which isn’t nearly as nice:

[1, 2, 3, 4, 5, 6].map{String($0)}

You can also populate enumerations with associated values. This example uses the Container enumeration I wrote about a few weeks ago.

Screen Shot 2015-06-25 at 10.42.46 AM

What you don’t want to do is use this as a long-hand for standard initialization. I think it’s a good rule to prefer String(5) over String.init(5).

Apple writes, “.init is still implicit when constructing using a static type, as in String(5). .init is required when using dynamic type objects, or when referring to the initializer as a function value.”

Update 1:

Trying to decide whether this is worth a radar:

Screen Shot 2015-06-25 at 10.58.30 AM

Update 2:

I oopsed on the initial post, using ()’s instead of {}’s for the 2nd map. But why does the first one work? (p.s. You want to debugPrint to see the quotation marks to confirm as String, not print)

Screen Shot 2015-06-25 at 12.58.48 PM

5 Comments

  • > But why does the first one work?
    In first case: because .init you can use as closure, and you set it in map as callback.
    In second: I’m sure work case like .map { String.init($0) }

    • I agree the last line is equivalent to String.init($0). Didn’t know you could use init as a closure. Thanks.

      • to be clear, I’m providing example:

        class A {
            var x: Int!, y: Int!   
             init(completion: A -> Void) {
                completion(self)
            }
        }
        let a = A {
            $0.x = 5
            $0.y = 25
        }
  • Where in the Apple docs did you find that “Swift 2.0 introduced .init, which offers functional access to initialization.”?

    • Release notes