在Swift 5中從原始文本建立字符串

從原始文本建立Swift字符串一般很痛苦。正確刪除原始文本中的任何引號或反斜槓字符是一種使人沮喪的練習。隨Xcode 10.2一塊兒發佈的Swift 5引入了一種新的語法,使其更容易使用原始文本。git

使用字符串文字建立字符串

從文本文本建立字符串時,使用雙引號(")做爲起始和結束分隔符,使用反斜槓(\)來轉義特殊字符。例如,要建立一個保留此文本中雙引號的String:github

let title1 = "Insert \"title\" here"
// Insert "title" here

複製代碼

自定義字符串轉義(Swift 5)

在Swift 5中,SE-0200容許您自定義分隔符和轉義序列。在處理可能包含分隔符或轉義序列的原始文本時,這很是有用。json

您可使用一個或多個「 #」字符填充開始,結束和轉義分隔符。這三個例子都產生了相同的結果:swift

let title2 = #"Insert "title" here"#
let title3 = ##"Insert "title" here"##
let title4 = ###"Insert "title" here"###
// Insert "title" here

複製代碼

請注意,咱們如今不須要轉義雙引號,由於它們再也不是分隔符。若是咱們的原始文本包含咱們選擇的分隔符,咱們可使用額外的「 #」 填充:api

// raw text is "#Hello#"
// start delimiter is ##"
// end delimiter is "## let regex1 = ##""#Hello#""## // "#Hello#"

複製代碼

若是咱們用一個或多個分隔符填充分隔符#,咱們還須要填充反斜槓轉義序列。例如,在插值時:bash

let name = "Tom"
let greeting1 = "Hello \(name)"    // Hello Tom

複製代碼

當使用單個填充時,#轉義序列變爲\#app

let greeting2 = #"Hello \#(name)"# // Hello Tom

複製代碼

當咱們想要保留轉義的原始文本時,自定義分隔符會頗有用。例如,從某些JSON建立String時。使用多行字符串文字彷佛是一個很好的方法:ui

let json1 = """ { "colors": ["red","green","blue"], "label": "Insert \"title\" here"
}
""" 複製代碼

當文本包含引號時,多行字符串文字很方便,但在這種狀況下會引入錯誤。問題是編譯器剝離了反斜槓,"title"致使一些無效的JSON:spa

{
  "colors": ["red","green","blue"],
  "label": "Insert "title" here"
}

複製代碼

若是咱們使用帶有多行字符串文字的自定義分隔符,咱們能夠在原始文本中保留轉義序列:code

let json2 = #"""
{
  "colors": ["red","green","blue"],
  "label": "Insert \"title\" here"
}
"""# 複製代碼

生成的String帶有保留的原始文本(請注意標題周圍的反斜槓轉義雙引號):

{
  "colors": ["red","green","blue"],
  "label": "Insert \"title\" here"
}
複製代碼

轉載自:www.jianshu.com/p/f1a7bbd8c…

相關文章
相關標籤/搜索