Swift 5 字符串转义字符处理更新

增加了 # 符号,使得写字符串更加简单。

  • 在字符串中包含 " 时不必再加 \

      //before
     let rain = "The is\"new\"string" 
      //after
      let rain = #"The is"new"string"#
    
  • 包含 \ 反斜杠也不需要再加转义符

       //before
      let rain = "The is\\new string" 
      //after
      let rain = #"The is \new string"#
    
  • 由于反斜杠作为字符串中的字符,所以在插入值的时候需要在后面再加个 #

  •     //before
       let age = 26
       let dontpanic = "myAge is \(age)"
       // after
       let answer = 26
       let dontpanic = #"myAge is \#(age)"#
    

    *当字符串包含 # 时, 前后应用 ## 包裹字符串

       let str = ##"this is "a"#good ideal"##   
    

*用 #""" 开头 """#结尾 来表示多行字符串

  let multiline = #"""
  The answer to life,
  the universe,
  and everything is \#(answer).
  """#
  • 由于不用反斜杠转义 使得正则表达式更加简洁明了

       //before
       let regex1 = "\\\\[A-Z]+[A-Za-z]+\\.[a-z]+"
      //after
       let regex2 = #"\\[A-Z]+[A-Za-z]+\.[a-z]+"#
    

你可能感兴趣的:(Swift 5 字符串转义字符处理更新)