DEV Community

Zdeněk Topič
Zdeněk Topič

Posted on

3 1

Swift Tip: Initializing & configuring properties

This article is also published on my blog.

Sometimes, you need to do more than just assign a value to a property on initialization.

class Foo {
    let formatter = DateFormatter()
}
Enter fullscreen mode Exit fullscreen mode

You might need to configure some of the properties. The first thing that comes to your mind is probably doing it in an initializer.

class Foo {
    let formatter = DateFormatter()

    init() {
        formatter.dateStyle = .short
    }
}
Enter fullscreen mode Exit fullscreen mode

There are more ways how to configure your properties without putting the code in the initializer.

class Foo {
    let formatter: DateFormatter = {
        $0.dateStyle = .short
        return $0
    }(DateFormatter())
}
Enter fullscreen mode Exit fullscreen mode

In the example above, you can see that the property Foo.formatter is constructed with a closure which takes the instance of DateFormatter as a parameter. You can do the same with initializing the DateFormatter directly in the closure:

class Foo {
    let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .short
        return formatter
    }()
}
Enter fullscreen mode Exit fullscreen mode

You can also use a function or a static method to construct the property.

func dateFormatter() -> DateFormatter {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    return formatter
}

class Foo {
    let formatter: DateFormatter = dateFormatter()
}
Enter fullscreen mode Exit fullscreen mode
class Foo {
    let formatter: DateFormatter = Foo.dateFormatter()

    static func dateFormatter() -> DateFormatter {
        let formatter = DateFormatter()
        formatter.dateStyle = .short
        return formatter
    }
}
Enter fullscreen mode Exit fullscreen mode

All these options work for local variables too.

Get in touch on Twitter @zdnkt for comments, discussion feedback or ideas!

This article is also published on my blog.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay