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

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 AdminHWS+

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 Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn 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.