转换swift 3中的代码

时间:2016-09-19 16:37:18

标签: swift3

let string = "/Date(1268123281843)/"
if let startRange = string.rangeOfString("("),endRange = string.rangeOfString(")") {
  let substring = string[startRange.endIndex..<endRange.startIndex]
  print(substring)
} 

注意:我需要在swift 3中使用此代码。请帮助我。谢谢!

2 个答案:

答案 0 :(得分:1)

rangeOfString应该包含。 检查这个artile。 https://www.hackingwithswift.com/swift3

let startRange = string.contains("(")

答案 1 :(得分:0)

在xcode 8(Swift 3)中测试:

extension String {
  func subString(from leftCharacter: String, to rightCharacter: String) -> String? {
    guard leftCharacter.characters.count > 0 && rightCharacter.characters.count > 0 else {
      return nil
    }

    let left = Character(leftCharacter)
    let right = Character(rightCharacter)

    let leftIndex = string.characters.index(of: left)
    let rightIndex = string.characters.index(of: right)

    if let leftIndex = leftIndex, let _ = rightIndex {
      string.removeSubrange(string.startIndex...leftIndex)
      if let rightIndex = string.characters.index(of: right) {
        string.removeSubrange(rightIndex..<string.endIndex)
        return string
      }

      return nil
    }

    return nil
  }
}
var string = "/Date(1268123281843)/"

let leftCharacter = "("
let rightCharacter = ")"

if let subtractedString = string.subString(from: leftCharacter, to: rightCharacter) {
  print(subtractedString) //1268123281843
}