[Swift][Extension]String中取代特定文字或符號(replace characters on Swift String)

維克多的程式探險
1 min readOct 25, 2017

--

有些時候當我們獲得一個String,但內容跟我們要呈現在畫面上的不符合(通常是從網路獲取資料時),這時候我們就可以透過以下程式碼來取代String中特定的文字或符號

extension String{
func replace(target: String, withString: String) -> String

{

return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
}

}

使用方法:

let str = “2017–10–21”
let newStr = str.replace(target:”-”,withString: “/”)
print(newStr)

印出來的String 就是 2017/10/21

--

--

維克多的程式探險

English Major but now is an iOS developer. A quick learner who is curious about everything