Home > Software design >  How to create a default instance object of custom class with SwiftUI
How to create a default instance object of custom class with SwiftUI

Time:11-09

I have a class ScanItem defined as follows:

class ScanItem {
    let title: String
    let content: String

    init(title: String, content: String) {
        self.title = title
        self.content = content
    }
}

I often need a default object of this class. I know I can pass default value to each variable of the class, but my question is: is there a mean to create default instance of this class, that could be used like this:

let newScan = ScanItem.defaultInstance

CodePudding user response:

Create a static property that returns a default instance

extension ScanItem {
    static var defaultInstance {
        let item = ScanItem()
        item.title = "<default title>"
        item.content = "<default content>"
        
        return item
    }
)
  • Related