How to create range in Swift?

前端 未结 10 1499
时光说笑
时光说笑 2020-11-28 01:37

In Objective-c we create range by using NSRange

NSRange range;

So how to create range in Swift?

10条回答
  •  时光取名叫无心
    2020-11-28 02:26

    I want to do this:

    print("Hello"[1...3])
    // out: Error
    

    But unfortunately, I can't write a subscript of my own because the loathed one takes up the name space.

    We can do this however:

    print("Hello"[range: 1...3])
    // out: ell 
    

    Just add this to your project:

    extension String {
        subscript(range: ClosedRange) -> String {
            get {
                let start = String.Index(utf16Offset: range.lowerBound, in: self)
                let end = String.Index(utf16Offset: range.upperBound, in: self)
                return String(self[start...end])
            }
        }
    }
    

提交回复
热议问题