Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีสร้างและใช้ Global Variable ใน Swift

Global Variables = ตัวแปรที่ประกาศนอก Function, Method, Closure, Type Context

วิธีสร้างและใช้ Global Variable ใน Swift

ตัวแปรใน Inner Circle (W) เข้าถึงได้แค่ใน Inner Circle ตัวแปรใน Outer Circle (A) เข้าถึงได้ทั้ง Inner และ Outer = Scope แบบ Global

การประกาศ Global Variable

ประกาศใน Class/Struct นอก Function:

class Student {
var section: String = "A" // global variable
func getStudentData() { }
}

ใช้ Access Modifier ได้:

private var name: String = "Aman"

วิธีที่ดีกว่า: ใช้ Struct

รวม Global Variables ใน Struct ใช้ได้ทุก Class:

struct Student {
static let name: String = "Aman"
static let age: Int = 22
}
class Employee {
func getData() {
print(Student.age)
print(Student.name)
}
}