NSRange to Range

前端 未结 13 1410
失恋的感觉
失恋的感觉 2020-11-22 11:59

How can I convert NSRange to Range in Swift?

I want to use the following UITextFieldDelegate method:

13条回答
  •  星月不相逢
    2020-11-22 12:25

    This answer by Martin R seems to be correct because it accounts for Unicode.

    However at the time of the post (Swift 1) his code doesn't compile in Swift 2.0 (Xcode 7), because they removed advance() function. Updated version is below:

    Swift 2

    extension String {
        func rangeFromNSRange(nsRange : NSRange) -> Range? {
            let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
            let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
            if let from = String.Index(from16, within: self),
                let to = String.Index(to16, within: self) {
                    return from ..< to
            }
            return nil
        }
    }
    

    Swift 3

    extension String {
        func rangeFromNSRange(nsRange : NSRange) -> Range? {
            if let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
                let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
                let from = String.Index(from16, within: self),
                let to = String.Index(to16, within: self) {
                    return from ..< to
            }
            return nil
        }
    }
    

    Swift 4

    extension String {
        func rangeFromNSRange(nsRange : NSRange) -> Range? {
            return Range(nsRange, in: self)
        }
    }
    

提交回复
热议问题