Class vs Structในภาษา Swift ต่างกันอย่างไร

ODENZA
1 min readJul 31, 2021

--

หลังจากที่เราได้เรียนพื้นฐานสำหรับการเขียนแอพด้วยภาษา swift กันเบื้องต้นแล้วหลายคนอาจจะมีความสงสัยว่า class และ struct จริงๆแล้ว แตกต่างกันอย่างไร เดี๋ยวผมจะเล่าให้ฟังครับ

ถ้าพูดกันง่ายๆเลยก็คือ

class จะมีการเข้าถึงข้อมูลต่างๆแบบ Reference type
struct จะมีการเข้าถึงข้อมูลแบบ Value type

แล้ว Reference type และ Value type มันคืออะไรหล่ะ

Reference type

Reference type จะเป็นการแชร์ข้อมูลชุดข้อมูลชุดเดียว และหากมีการเปลี่ยนแปลงค่าที่ทำการ copy ไป ก็จะทำให้ค่าเดิมเปลี่ยนแปลงไปด้วย

ตัวอย่าง

class Car {
var color: String
init(color: String) {
self.color = color
}
}
let myCar = Car(color: "white")// 1. myCar is copied to yourCar
let yourCar = myCar
// 2. change the instance
myCar.color = "black"
print(myCar.color)
print(yourCar.color)

จาก code ข้างบนผมได้ทำการประกาศให้ สีของ myCar = white แล้ว
1. Copy ค่าของ myCar ไปที่ yourCar (ในตอนนี้ สีของ yourCar ก็ = white เช่นกัน)
2. ผมทำการเปลี่ยนสีของ myCar = black (ทำให้ค่าของ yourCar เปลี่ยนไปด้วย เพราะการใช้ class เป็นการใช้ข้อมูลแบบ reference type นั่นเอง)

ค่าจาก print

black
black

Value type

ส่วน Value type ก็จะแตกต่างจาก reference type นั่นเอง คือ หากมีการ copy ข้อมูลนั้นไปใช้ และ มีการเปลี่ยนค่า ก็จะไม่ได้ทำให้ค่าเริ่มต้นเปลี่ยนไป

Value type ในภาษา Swift นั้นมีหลายประเภท เช่น struct, enum or tuples

ตัวอย่าง

struct Car {
var color: String
init(color: String) {
self.color = color
}
}
var myCar = Car(color: "white")// 1. myCar is copied to yourCar
let yourCar = myCar
// 2. change the instance
myCar.color = "black"
print(myCar.color)
print(yourCar.color)

Results

black
white

จากผลลัพธ์จะเห็นว่า ค่าของ yourCar ไม่ได้เปลี่ยนไป เพราะค่าจะถูกเปลี่ยนแค่ myCar นั่นเอง

ใน SwiftUI จะเห็นได้ว่า View ต่างๆจะใช้ struct เพราะไม่ได้ต้องการให้ค่าต่างๆของแต่ละหน้าเปลี่ยนค่าไปเหมือนกันทั้งหมดนั่นเอง

--

--

ODENZA
ODENZA

No responses yet