ค่าคงที่ทั่วโลก (global constant) ในภาษา Swift

Wasith T. (Bai-Phai)
กูโค้ด
Published in
1 min readMar 2, 2020

ในภาษา Swift แนะนำว่าให้ประกาศ constant ไว้ใน enum เพราะว่าถ้าประกาศไว้ที่อื่นเช่น class, struct จะทำให้สร้าง object หรือ instance ที่ไม่ได้ใช้งาน หรือถ้าประกาศไว้ลอย ๆ ก็ไม่มีขอบเขตของ constant นั้น ๆ ระบุ

การสร้าง global constant ต้องใช้ static let โดยการประกาศเป็น let จะทำให้ไม่สามารถแก้ไขค่าได้ใน compile time

แนะนำ

enum Math {  static let e = 2.718281828459045235360287
static let root2 = 1.41421356237309504880168872
}
let hypotenuse = side * Math.root2

ต้องอยู่ใน enum ที่ไม่มี case เพราะว่าถ้ามี case อาจจะสร้าง instant ของ enum นั้น ๆ ได้

ไม่แนะนำ

let e = 2.718281828459045235360287 // ขยะใน global namespace
let root2 = 1.41421356237309504880168872

let hypotenuse = side * root2 // อะไรคือ root2 ?

การตั้งชื่อค่าคงที่

ในภาษาอื่น ๆ เช่น Java จะใช้ snake case all capitals แต่ใน Swift จะใช้ camel case และเลิกใช้ prefix แบบใน Objective-C แต่ให้ไปอยู่ใน enum เพื่อบอก scope แทน

อ้างอิง:

--

--

Wasith T. (Bai-Phai)
กูโค้ด

ตบมือเป็นกำลังใจให้ผมด้วยนะครับ 😘