Array, Dictionary & Tuple
อยากเก็บของเยอะ ๆ ใช้ตัวแปรเดียว
Array
เมื่อเราต้องการเก็บข้อมูลประเภทเดียวกันแต่มีหลายอันเราจะใช้ Array ในการเก็บ
let stringArray: [String] = []
หรือ
let stringArray = [String]()
เราสามารถกำหนดค่าเริ่มต้นพร้อมกับประกาศตัวแปร เช่น เรามีลิสต์ของของที่ต้องซื้ออย่าง ปลา น้ำ และดอกไม้
var shoppingList: [String] = ["fish", "water", "flower", "cake"]
เนื่องจากของใน list เรามีแต่ String ทำให้เรา infer types แบบนี้
var shoppingList = ["fish", "water", "flower", "cake"]
เราสามารถอ้างถึงของใน Array ได้ด้วย index เป็น Int
โดยเริ่มจาก 0
แบบนี้
let item = shoppingList[1]
// item = "water"
รวมทั้งการเปลี่ยนค่าใน Array ด้วย
shoppingList[1] = "bottle of water"
Index สามารถใช้ range ได้ด้วย อย่างเราต้องการเปลี่ยนตั้งแต่ Index ที่ 1
ถึง 3
shoppingList[1...3] = ["Bananas", "Apples"]
// shoppingList = ["fish", "Bananas", "Apples"]
นอกจากนี้ ยังมีฟังก์ชันอื่น ๆ ให้ใช้ด้วย เช่น append
insert
remove
shoppingList.append("blue paint")
shoppingList.insert("Maple Syrup", at: 0)
let mapleSyrup = shoppingList.remove(at: 0)
Dictionary
สำหรับข้อมูลที่เก็บเป็นแบบ key
value
คู่กัน เราจะใช้ Dictionary หน้าตาแบบนี้
var occupations: [String: String] = [:]
หรือ
var occupations = [String:String]()
เช่น
var occupations: [String: String] = [
"Pop": "Developer",
"John": "Mechanic",
]
เราจะประกาศ Type คล้าย Array คืออยู่ใต้ [
และ ]
เพียงแต่ต้องระบุ Type ของ Key และ Value คั่นด้วย :
และเช่นเดิม เราสามารถละการประกาศ Type ได้ด้วยความสามารถ infer types
var occupations = [
"Pop": "Developer",
"John": "Mechanic",
]
เมื่อเราต้องการอ้างถึงจะคล้ายกับ Array เพียงแต่ว่าใช้ Key เป็น index ตาม Type ที่ประกาศ
let occupation = occupations["Pop"]
ขณะเดียวกันเราสามารถเพิ่มหรือเปลี่ยนค่าผ่าน Key เช่นกัน
occupations["Jane"] = "Public Relations"
occupations["John"] = "Manager"
เนื่องจาก dictionary เก็บเป็น Key value เราจึงอาจจะไม่ได้ค่า value ในกรณีที่ไม่มี key ที่ระบุเก็บไว้อยู่ เราสามารถระบุค่า default ให้ได้ แบบนี
let occupation = occupations["Joe", default: "Unknown"]
Tuple
ในบางครั้งเราต้องการเก็บของที่ Type ไม่เหมือนกัน แต่เป็นกลุ่มข้อมูลที่ใช้ด้วยกัน เราจะใช้ Tuple เช่น เรามี HTTP Error 404
let http404Error = (404, "Not found")
เราสามารถอ้างของที่อยู่ใน Tuple ด้วย index เป็น Int
ได้เหมือน Array เลย
print("Error code: \(http404Error.0)")
print("Error Message: \(http404Error.1)")
แต่จะเห็นว่า เวลาอ่านเราจะอ่านไม่รู้เรื่อง เราสามารถใช้ label กำกับได้ แบบนี้
let http404Error = (code: 404, message: "Not found")
print("Error code: \(http404Error.code)")
print("Error Message: \(http404Error.message)")
บางครั้งเราทำแบบนี้
let (code, message) = http404Error
print("Error code: \(code)")
print("Error Message: \(message)")
Last updated