jamiechoo

 

Swift筆記|static / shared

在練習串接API時會用到static及shared,之前都是直接照抄哈,這篇來認真研究一下static及shared的用法。

static

這邊建立一個Drink類別,裡面包含使用及不使用static的兩種變數。

class Drink {
var name = "chocolate"
static var temperature = "hot"
}print(Drink().name)
print(Drink.temperature)

在其他地方要呼叫時:

  • 不使用static的變數 → 需要先建立Instance才能呼叫Drink().name
  • 使用static的變數 → 可以直接用Drink.temperature來呼叫

若將用法反過來寫的話則會出現Error,如下。

print(Drink.name)          // Error
print(Drink().temperature) // Error
 

shared

利用static可以在不另外建立Instance的情況下呼叫類別(Class)中變數的特性,可以在Class中建立static的shared變數來存放該類別的Instance,方便之後進行呼叫。

⭐️ 不使用shared時

假設建立了一個Coffee類別,並在裡面存放了咖啡種類變數name,在其他地方要呼叫時必須先定義coffee = Coffee(),才可以用coffee.name來呼叫。

class Coffee {
let name = "Latte"
}let coffee = Coffee()
print(coffee.name)

也可以不先定義coffee=Coffee(),直接用Coffee().name來呼叫

print(Coffee().name)

⭐️ 使用shared時

如果在Coffee類別中加入static let shared = Coffee(),則在其他地方呼叫時只需要使用Coffee.shared.name即可取得咖啡種類名稱。

class Coffee {
static let shared = Coffee()
let name = "Latte"
}print(Coffee.shared.name)

使用shared時呼叫到的是同一個Instance

class Coffee {
static let shared = Coffee()
var name = "Latte"
}let coffee1 = Coffee.shared
let coffee2 = Coffee.shared
coffee2.name = "Cappucinno"
print(coffee2.name) // Cappucinno
print(coffee1.name) // Cappucinno

從上面的範例可以知道,在變更coffee2.name的值後,coffee1.name也改變了,因為兩者其實指到同一個Instance。

反之在不使用shared的情況,當coffee2.name變更後,coffee1.name並不會跟著改變,如下。

class Coffee {
var name = "Latte"
}
let coffee1 = Coffee()
let coffee2 = Coffee()
coffee2.name = "Cappucinno"
print(coffee2.name) // Cappucinno
print(coffee1.name) // Latte
 

posted on 2024-06-05 16:13  jamiechoo  阅读(4)  评论(0)    收藏  举报

导航