WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: What is .init?

Forums > 100 Days of SwiftUI

example from Day 21:

RadialGradient(stops: [
    .init(color: Color(red: 0.1, green: 0.2, blue: 0.45), location: 0.3),
    .init(color: Color(red: 0.76, green: 0.15, blue: 0.26), location: 0.3),
], center: .top, startRadius: 200, endRadius: 400)
    .ignoresSafeArea()

   

So an initializer is a method that sets up a struct or class or enum so that it can be used.

The initializer for RadialGradient that is being used here looks like this:

init(stops: [Gradient.Stop], center: UnitPoint, startRadius: CGFloat, endRadius: CGFloat)

You can see that the first parameter takes an array of Gradient.Stop items. So you have to provide an array of those, which is usually done like this:

[
    Gradient.Stop(color: ...,location: ...),
    Gradient.Stop(color: ...,location: ...),
    Gradient.Stop(color: ...,location: ...),
]

But since Gradient.Stop(...) is just a shorthand for calling the initializer, you can instead write it like this:

[
    Gradient.Stop.init(color: ...,location: ...),
    Gradient.Stop.init(color: ...,location: ...),
    Gradient.Stop.init(color: ...,location: ...),
]

And since Swift's type inference knows it's looking for Gradient.Stop items here, you can actually leave out the type part and just use .init, like so:

[
    .init(color: ...,location: ...),
    .init(color: ...,location: ...),
    .init(color: ...,location: ...),
]

Et voilà!

5      

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.