LoginSignup
0
0

More than 5 years have passed since last update.

字串合併 (String Appending) - Swift 3 調整記

Posted at

Xcode 8 beta 6 出來了,
Swift 改了一個 String 中我很想要它被改掉的東西

就是 append

這個 method

準備

先準備一個字串物件

var priceString = "售價: "

現在想要讓他變成

售價: 100

所以現在要在後面加上 100 這個字串。

這個範例直接在 Xcode 裡面的 playground 執行即可。

Before

(這一段是在 Xcode 7.3.1 中的 playground 執行)

假如我現在有個固定的字串,需要在後面加上另外一個字串,我在 Swift 2.x 之前要這樣寫:

priceString.append("100" as UnicodeScalar)

如果照直覺寫這樣:

priceString.append("100")

Xcode 原先會抱怨說

Ambiguous use of 'append'

畢竟原本的 append 需要塞入一個 UnicodeScalar 的物件,而不是 String 物件
不然就是要用更長的一個方法:

priceString.appendContentsOf("100")

嘶 ... 好長好囉唆,
所以一碰到要組合字串都會覺得不漂亮、很麻煩。

如果有寫過其他語言(如 Ruby)
就會覺得這麼長根本不合理。

After

(這一段是在 Xcode 8 beta 6 中的 playground 執行)

這時候,簡化多了,也比較合理:

priceString.append("100")

就這樣就好,也不需要轉型,
已經可以直接稼接上一個字串物件。

乾淨而且直覺、合理、易讀多了。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0