UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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()

2      

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à!

7      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.