String, substring, Range, NSRange in Swift 4

こ雲淡風輕ζ 提交于 2019-12-09 02:30:02

问题


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?


回答1:


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]
    }
}



回答2:


With Swift 4 we can get substrings this way.

  1. Substring from index

    let originStr = "Test"
    let offset = 1
    let str = String(originStr.suffix(from: String.Index.init(encodedOffset: offset)))
    
  2. Substring to index

    let originStr = "Test"
    let offset = 1
    String(self.prefix(index))
    


来源:https://stackoverflow.com/questions/45449186/string-substring-range-nsrange-in-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!