Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use self for init in extension in Swift?

I want use self for having default value, but Xcode cannot find it! how can I solve the issue? I want to have a default value also an option to chose the range in case.

extension Array {
    func printItemsIn(range: Range<Int> = self.indices) {
        range.forEach { index in
            print(self[index])
        }
    }
}

use case:

[10, 20, 30, 40].printItemsIn(range: 0..<1)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t. What you can do is declare your parameter as optional and set its default value to nil.

extension Array {
    func printItems(in range: Range<Int>? = nil) {
        let range = range ?? indices
        range.forEach { index in
            print(self[index])
        }
    }
}

[10, 20, 30, 40].printItems(in: 0..<1)  // 10
[10, 20, 30, 40].printItems()           // 10, 20, 30, 40
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading