Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String, substring, Range, NSRange in Swift 4

I am using the following code to get a String substring from an NSRange:

func substring(with nsrange: NSRange) -> String? {
    guard let range = Range.init(nsrange)
        else { return nil }
    let start = UTF16Index(range.lowerBound)
    let end = UTF16Index(range.upperBound)
    return String(utf16[start..<end])
}

(via: https://mjtsai.com/blog/2016/12/19/nsregularexpression-and-swift/)

When I compile with Swift 4 (Xcode 9b4), I get the following errors for the two lines that declare start and end:

'init' is unavailable
'init' was obsoleted in Swift 4.0

I am confused, since I am not using an init.

How can I fix this?

like image 992
koen Avatar asked Aug 01 '17 23:08

koen


People also ask

What is Nsrange in Swift?

A structure used to describe a portion of a series, such as characters in a string or objects in an array. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+

How do you slice a string in Swift?

In Swift 4 you slice a string into a substring using subscripting. The use of substring(from:) , substring(to:) and substring(with:) are all deprecated.

How do you create a range in Swift?

Ranges with Strings< range operators are a shorthand way of creating ranges. For example: let myRange = 1..<3. let myRange = CountableRange<Int>(uncheckedBounds: (lower: 1, upper: 3)) // 1..<3.


1 Answers

Use Range(_, in:) to convert an NSRange to a Range in Swift 4.

extension String {
    func substring(with nsrange: NSRange) -> Substring? {
        guard let range = Range(nsrange, in: self) else { return nil }
        return self[range]
    }
}
like image 174
Charles Srstka Avatar answered Sep 21 '22 08:09

Charles Srstka