Is a static boolean reference type in Swift?

I make a few switches. There are several booleans in my MenuScene class that are boolean static variables to represent the states of these switches.

Are these destinations referenced types, so I can be sure that other objects can change their state with a unique reference to them?

Dream, in my dreamy pseudo-code, I hope that changes in iAmOn affect the state of myButtonABC_state

 class MenuScene { static var myButtonABC_state: Bool = false static var myButtonXYZ_state: Bool = false override onDidMoveToView { let buttonABC = Button(withState: MenuScene.myButtonABC_state) let buttonXYZ = Button(withState: MenuScene.myButtonXYZ_state) } } 

In the button class

 class Button { var iAmOn: Bool = false init(withState state: Bool){ iAmOn = state } override onTouchesBegun(... etc...){ if iAmOn { iAMOn = false } else { iAmOn = true} } } 
+5
source share
1 answer

Bool is a structure in Swift; structs are value types. It doesnโ€™t matter if it is static var , class var , let , var , etc., the type has a value, so no, Bool is the type of value.

I think you're not 100% full of terminology (mainly because Apple doesn't cover it very much in the documentation, as usual, lol).

There are "Swift Types" (Bool, Int, your classes / structures, etc.) and "Variable / Constant Types" (which store data in a memory register, such as references or actual values), as well as "Write / Read Types memory register "(variable vs vonstant, mutable vs immutable, var vs let ).

Donโ€™t be discouraged .. This is a bit confusing for everyone ... Especially at the beginning and without good documentation. (I tried to learn C ++ pointers from an early age, and that was on my head).

Here's some good reference material: (to the bottom) https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html

Basically, if you want to keep a reference to something, you need to use a memory register of type Reference. This means using an instance of the Static class does not matter:

 /* Test1: */ struct Hi { static var sup = "hey" } var z = Hi.sup Hi.sup = "yo" print(z) // prints "hey" /* Test 2: */ class Hi2 { static var sup = "hey" } var z2 = Hi2.sup Hi2.sup = "yo" print(z2) // Prints "hey" 

If you think you need a pointer to what is inside the class, you can use UnsafeMutablePointer or something similar from the OBJc code.

Or you can wrap a bool inside a class object (which is always referenced).

 final class RefBool { var val: Bool init(_ value: Bool) { val = value } } 

And here is some interesting behavior for reference types with let :

 let someBool: RefBool someBool = RefBool(true) someBool = RefBool(false) // wont compile.. someBool is a `let` someBool.val = false // will compile because of reference type and member is `var` 
+5
source

Source: https://habr.com/ru/post/1260053/


All Articles