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

ios coder

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)
Leo Dabus

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I use contains function in Array extension in Swift?

Swift protocol extension self reference issues with init

How can I make a generic extension in Swift?

Swift - Can I use realm in Notification Service Extension?

SWIFT: How I can use subscriberCellularProviderDidUpdateNotifier with Swift

How to redefine default class init() in extension in Swift?

How to change self in NSDate extension Swift?

How can I generate an init call from strings in swift

How can I override convenience init in UIAlertController for swift?

how can i add data in a class object after i ran def __init__(self) function?

How to fix convenience init w/closure Extension of NSBezierPath to use CGPath that fails in Swift 5.0?

How can I make an extension for extracting keys of a Dictionary in Swift?

Swift - How can I override an extension method in a concrete subclass

How can I add a function to Swift as an extension to String to simplify usage

How to use Realm Swift Init

How can I use SslStream/AuthenticateAsServer with a self signed cert/key?

How can I use a docker container with a self signed certificate on osx?

How can I use Scala reflection to find the self type traits?

How can I use function with 2 arguments includes 'self' in Python?

How can I use 'self' when writing recursion in Python?

How can I use mapbox in JSQMessagesViewController swift

How can I use Chartboost with Cocoapods in Swift?

How can I use UserDefaults in Swift?

How can I use UIColorFromRGB in Swift?

How can I use swift in Terminal?

How can I use `syslog` in Swift

How can I use Realm with Swift 4?

How can I use precision in Swift?

How I can use duration in spriteKit(swift)?