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")

4      

@twostraws  Site AdminHWS+

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

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

4      

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.

3      

😎👍

3      

@twostraws Dang! I was nearly there 🤓 Thanks!

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.