[英]Swift 3 lazy caching with enums
我正在用Swift 3開發游戲,我想知道將枚舉(或結構)中的SKTexture延遲緩存的最佳實踐是什么。 我想要的是僅一次創建SKTexture,並且僅在需要時才創建。 我可以創建一個具有(Dictionary / Set / Cache / ...)變量的Singleton,並且僅在該鍵不存在的情況下才向該變量附加一個新的SKTexture,或者如果該鍵存在則返回值,但是我有感覺到枚舉也應該是可能的。
對於struct
,您可以簡單地使用SKTexture
的lazy
屬性:
struct Foo {
lazy var myTexture: SKTexture = {
/* some logic to construct texture only
ever (at most) once _per Foo instance_ */
return someInitializedSKTextureInstance
}()
/* or, as an immutable
lazy var myTexture: SKTexture = ... */
}
對於Foo
的實例 , theFooInstance.myTexture
將最多實例化一次,但是上面僅執行了一次閉包。
但是,枚舉不能使用存儲的屬性,這意味着您不能使用上述方法。 但是,您可以在enum
使用static
屬性:默認情況下,它們是惰性的,並且在第一次調用它們時最多(僅)實例化一次。 此處的區別自然是(由於static
)(由於static
),這種一次實例化將在enum
_type)全局保存,而不是在enum
實例。
enum Foo {
case bar, baz
static var texture: SKTexture = {
/* logic to construct some texture ... */
return someInitializedSKTextureInstance
}()
}
自然,靜態方法也可以用於struct
案例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.