0

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
2
  • Related: stackoverflow.com/q/24024549/1187415 Commented Nov 8, 2021 at 9:51
  • What exactly do you mean by a default instance? A scan item with an empty string title and content? Commented Nov 8, 2021 at 12:08

1 Answer 1

1

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
    }
)
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect ! I just had to change "static let" to "static var". Thank you !
Yes, sorry that was a typo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.