GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until February 9th.

Click to save your free spot now

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.