DEV Community

Zdeněk Topič
Zdeněk Topič

Posted on

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.

Top comments (0)