2015-09-14 30 views
5

Mam Xcode 7 GM, z swift 2.0, co jest równoznaczne z espression:Swift 2.0 substringwithrange

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

z nowymi klasy string?

Odpowiedz

8

Spróbuj tego:

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

Można użyć tych rozszerzeń:

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

To będzie łatwiejsze:

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