String, substring, Range, NSRange in Swift 4

前端 未结 2 367
情话喂你
情话喂你 2021-01-07 23:54

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

func substring(with nsrange: NSRange) -> String? {
             


        
相关标签:
2条回答
  • 2021-01-08 00:18

    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))
      
    0 讨论(0)
  • 2021-01-08 00:33

    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]
        }
    }
    
    0 讨论(0)
提交回复
热议问题