2015-09-14 4 views
5

Sono Xcode 7 gm, con rapida 2.0 qual è espression equivalente di:Swift 2.0 substringwithrange

Let myNSString = "full text container" 
myNSString.substringWithRange(NSRange(location: 0, length: 3)) 

Con la nuova classe string?

risposta

8

Prova questo:

let myString = "full text container" 
myString[myString.startIndex..<myString.startIndex.advancedBy(3)] 
5

È possibile utilizzare queste estensioni:

Swift 2

extension String 
{ 
    func substringWithRange(start: Int, end: Int) -> String 
    { 
     if (start < 0 || start > self.characters.count) 
     { 
      print("start index \(start) out of bounds") 
      return "" 
     } 
     else if end < 0 || end > self.characters.count 
     { 
      print("end index \(end) out of bounds") 
      return "" 
     } 
     let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(end)) 
     return self.substringWithRange(range) 
    } 

    func substringWithRange(start: Int, location: Int) -> String 
    { 
     if (start < 0 || start > self.characters.count) 
     { 
      print("start index \(start) out of bounds") 
      return "" 
     } 
     else if location < 0 || start + location > self.characters.count 
     { 
      print("end index \(start + location) out of bounds") 
      return "" 
     } 
     let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(start + location)) 
     return self.substringWithRange(range) 
    } 
} 

Swift 3

extension String 
{ 
    func substring(start: Int, end: Int) -> String 
    { 
     if (start < 0 || start > self.characters.count) 
     { 
      print("start index \(start) out of bounds") 
      return "" 
     } 
     else if end < 0 || end > self.characters.count 
     { 
      print("end index \(end) out of bounds") 
      return "" 
     } 
     let startIndex = self.characters.index(self.startIndex, offsetBy: start) 
     let endIndex = self.characters.index(self.startIndex, offsetBy: end) 
     let range = startIndex..<endIndex 

     return self.substring(with: range) 
    } 

    func substring(start: Int, location: Int) -> String 
    { 
     if (start < 0 || start > self.characters.count) 
     { 
      print("start index \(start) out of bounds") 
      return "" 
     } 
     else if location < 0 || start + location > self.characters.count 
     { 
      print("end index \(start + location) out of bounds") 
      return "" 
     } 
     let startIndex = self.characters.index(self.startIndex, offsetBy: start) 
     let endIndex = self.characters.index(self.startIndex, offsetBy: start + location) 
     let range = startIndex..<endIndex 

     return self.substring(with: range) 
    } 
} 

E sarà più semplice:

let substring = myNSString.substringWithRange(0, location: 3)