Advertisement
Guest User

Untitled

a guest
Mar 6th, 2015
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. class Container<T:Any>{
  2.  
  3. var _memory:Any
  4. var memory:T {
  5. get {
  6. if let typed_value = self._memory as? T {
  7. return typed_value
  8. } else {
  9. return unsafeBitCast( self._memory, T.self )
  10. }
  11. }
  12. set {
  13. self._memory = newValue
  14. }
  15. }
  16.  
  17. init( memory:Any ){
  18. self._memory = memory
  19. }
  20.  
  21. }
  22.  
  23. var Static_Containers = [String:AnyObject]()
  24.  
  25. func static_var <T:Any>(
  26. value:T,
  27. file: StaticString = __FILE__,
  28. line: UWord = __LINE__,
  29. col: UWord = __COLUMN__,
  30. fun: StaticString = __FUNCTION__
  31. ) -> Container<T> {
  32.  
  33. let unique_key = "FUNC_(fun)__LINE(line)_COL(col)__FILE_(file)"
  34.  
  35. let needs_init = !contains( Static_Containers.keys, unique_key )
  36.  
  37. if needs_init {
  38. Static_Containers[unique_key] = Container<T>( memory:value )
  39. }
  40.  
  41. return Static_Containers[unique_key]! as! Container<T>
  42.  
  43. }
  44.  
  45. func test_with_nsstring( str:NSString, init_only:Bool ) -> NSString {
  46. var stat_str = static_var( str )
  47. if !init_only {
  48. stat_str.memory = str
  49. }
  50. return stat_str.memory
  51. }
  52. test_with_nsstring( "this should get set", true )
  53. test_with_nsstring( "this should be ignored", true )
  54. test_with_nsstring( "this should change the value", false )
  55. test_with_nsstring( "as should this", false )
  56.  
  57. func test_with_int( i:Int, init_only:Bool ) -> Int {
  58. var stat_int = static_var( i )
  59. if !init_only {
  60. stat_int.memory = i
  61. }
  62. return stat_int.memory
  63. }
  64. test_with_int( 0, true )
  65. test_with_int( 1, true )
  66. test_with_int( 2, false )
  67. test_with_int( 3, false )
  68.  
  69. func test_with_optstr( optstr:String?, init_only:Bool ) -> String? {
  70. var stat_optstr = static_var( optstr )
  71. if !init_only {
  72. stat_optstr.memory = optstr
  73. }
  74. return stat_optstr.memory
  75. }
  76. test_with_optstr( nil, true )
  77. test_with_optstr( "this should be ignored", true )
  78. test_with_optstr( "this should change the value", false )
  79. test_with_optstr( "as should this", false )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement