NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

SOLVED: Small question about initialisation

Forums > Swift

I want to be able to init my type multiple ways (blank, or with info). Is this the correct way to do that, or is there a better way? (I always get confused with initialisers)

import UIKit

class ProjectsController {
    //MARK: - Types
    struct Project: Codable, Hashable {
        let identifier: UUID
        let createDate: Date
        var lastEdited: Date
        var title: String
        var comment: String
        var iconImageURL: String?

        init(title: String, comment: String = "") {
            self.title = title
            self.comment = comment
            self.identifier = UUID()
            self.createDate = Date()
            self.lastEdited = Date()
            self.iconImageURL = nil

        init() {
            self.init(title: "", comment: "")

let project = Project()
let Project2 = Project(title: "Bla", comment: "BlaBla")


@twostraws  Site Admin

You can remove the empty init() and adjust your other initializer to this:

init(title: String = "", comment: String = "") {


Initialisers confuse the heck out of me too. I should have "got it" by now but I guess practise will make perfect.

Ooooooh, doesn't that gold badge look nice.




@twostraws Dang! I was nearly there 🤓 Thanks!


Hacking with Swift is sponsored by Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

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

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

Not logged in

Log in

Link copied to your pasteboard.