[Swift] Tip ง่ายๆกับการต่อ String ด้วย joinedWithSeparator

Suraphan Laokondee
Feb 24, 2017 · 2 min read

เขียนไว้กันลืมสักหน่อย กับ Swift Array function ที่ชื่อ
public func joined(separator: String = default) -> String

เรามักจะเจอ Design ที่แสดงผลโดยการนำข้อความมาต่อกันแล้วขั้นด้วย , เช่น

เบอร์โทรศัพท์หลายๆเบอร์ “081XXXXXXX, 082XXXXXXX, 084XXXXXXX” หรือ อยากจะแสดงผล รายชื่อหุ้นเรียงต่อกัน “PTT, CPALL, BBL”

ถ้าคิดอะไรไม่ออก เราก็อาจจะ run for loop ไป แต่ว่า Swift นั้นมี function ที่ช่วยเราให้ทำงานง่ายขึ้นมากๆ

โดย function นี้จะสามารถใช้งานได้ก็ต่อเมื่อ Array ของเรานั้นมี Element เป็น String เท่านั้น — > Array where Element == String

สมมุติว่า ผมมี Struct ตัวนึง ไว้เก็บค่า เบอร์โทรศัพท์ และ Status ว่าสามารถใช้งานได้หรือไม่

มี Array ชื่อ mobiles เก็บ Struct Mobile นั้นไว้

เราต้องการแสดงผลเบอร์โทรศัพท์ที่ สามารถใช้งานได้
เราก็แค่ filter มันออกมา พร้อมกับ map เอาเฉพาะชื่อออกมา

หลังจากนั้นใช้ joined with separator “, ” เราก็จะได้
“081XXXXXXX, 082XXXXXXX, 084XXXXXXX” ออกมาแล้ว ง่ายมาๆเลย :)

https://gist.github.com/rpzzzzzz/e3a26b518c02cf71204da345cd74b2c5

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade