How to convert Range to NSRange and Viceversa - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

20 Nov 2017

How to convert Range to NSRange and Viceversa

NSRange contains two properties.

1. location
2. length

How to convert Range to NSRange and Viceversa

For example:

Get the range of word "find" from the following string.

let originalString = "Hello let's find range"

"find" located at position 12, and is length of 4. So range should be as follow:

let range = NSMakeRange(12, 4)

Range:

For getting range we have built in method as follow:

let originalString = "Hello let's find range"
let range = originalString.range(of: "find")

Convert Range to NSRange:

Add the following string extension for converting Range to NSRange:

extension String {
    func nsRange(from range: Range) -> NSRange {
        let startPos = self.distance(from: self.startIndex, to: range.lowerBound)
        let endPos = self.distance(from: self.startIndex, to: range.upperBound)
        return NSMakeRange(startPos, endPos - startPos)
    }
}

Use as follow:

let nsRange = originalString.nsRange(from: range!)

Convert NSRange to Range:

Add the following string extension for converting NSRange to Range:

extension String { 
    func range(from nsRange: NSRange) -> Range? {
        guard
            let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
            let to16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location + nsRange.length, limitedBy: utf16.endIndex),
            let from = from16.samePosition(in: self),
            let to = to16.samePosition(in: self)
            else { return nil }
        return from ..< to
    }
}

Use as follow:

let newRange = originalString.range(from: nsRange)

2 comments:

  1. บริการเกมสล็อตออนไลน์ปี 2022 เกมให้เลือกเล่นมากกว่า 1,000 เกมซุปเปอร์สล็อตเล่นผ่านเว็บ f

    ReplyDelete
  2. บริการเกมสล็อตออนไลน์ปี 2022 เกมให้เลือกเล่นมากกว่า 1,000 เกมสล็อตออนไลน์ d

    ReplyDelete

Post Top Ad