Skip to content

Instantly share code, notes, and snippets.

@raygun101
Last active September 24, 2020 06:36
Show Gist options
  • Save raygun101/61df142e648772340731029db51f539e to your computer and use it in GitHub Desktop.
Save raygun101/61df142e648772340731029db51f539e to your computer and use it in GitHub Desktop.
🍰 Layered Cakewalk [Swift] - Generic<> stored static fields workaround. (Swift)
import UIKit
// πŸ°πŸ‘» Generic<> stored static fields workaround.
//
private var _MyClass_static: [ObjectIdentifier : Any] = [:] // need some global space
//
class MyClass<T>
{
typealias StaticClass = MyClassStatic<Self>
static var `static`: StaticClass
{
let key = ObjectIdentifier(Self.self)
return
(_MyClass_static[key] as! StaticClass?)
??
{
let result = StaticClass()
_MyClass_static[key] = result
return result
}()
}
}
class MyClassStatic<TMyClass>
{
var staticValue: String = ""
}
MyClass<String>.`static`.staticValue = "wolly"
MyClass<Int>.`static`.staticValue = "fred"
print(MyClass<String>.`static`.staticValue) // wolly
print(MyClass<Int>.`static`.staticValue) // fred
@raygun101
Copy link
Author

raygun101 commented Sep 24, 2020

πŸ°β›± Usage Example

Copy into a playground, and play...
MyClass<String>.`static`.staticValue = "wolly"
MyClass<Int>.`static`.staticValue    = "fred"

print(MyClass<String>.`static`.staticValue) // wolly
print(MyClass<Int>.`static`.staticValue)    // fred

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment