Topics

Topics

In some cases, Initializers can be a pain to implement.

They can often be 100% boilerplate code, and feel like a chore to write.

This issue is at its worst when defining we’re Swift Structs in a framework or module.

In Swift, Structs are given a synthesised initialiser… with an internal modifier. Doh. 😣

This means the initializer is only accessible/visible inside the module we’re defining it in.

This means we’re stuck needing to manually add our own initializers for each of our Structs.

Creating and keeping these initializers up to date can add up to a ton of boilerplate code maintence. Yuck.

Today we’ll try out an Xcode Source Editor Extension (Bite #239) from Bouke Haarsma that can help us write these automatically.

The extension works by taking the Swift properties defined within our selected text and converting them to parameters in a Swift Initializer.

After we install the extension, we can write up an example Struct in our code to try it out:

public struct Record {
  public let name: String
  public let type: UInt16
  public let unique: Bool
  public let ttl: UInt32
  var data: Data
}

We’ll select just the properties, then select Editor > Generate Swift Initializer > Generate Swift Initializer.

- 273 1 - #273: Automatically Generating Swift Initializers 🤖🛠 – Little Bites of Cocoa – Tips and techniques for iOS and Mac development

Success! We just saved ourselves a ton of time, and typing. Neat!

Learn more about SwiftInitializerGenerator (including complete installation instructions) at git.io/swiftig



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here