Is a static boolean a reference type in Swift? - swift

I'm making some switches. In my MenuScene class there's some booleans that are static variables, booleans, to represent the states of these switches.
Are these addressable as reference types, so I can be sure that other objects are able to change their state with a unique reference to them?
The dream, in my dreamy pseudo code, I'm hoping changes to iAmOn impact 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 a button class
class Button {
var iAmOn: Bool = false
init(withState state: Bool){
iAmOn = state
}
override onTouchesBegun(... etc...){
if iAmOn { iAMOn = false }
else { iAmOn = true}
}
}

Bool is a struct in Swift; structs are value types. It doesn't matter if it's static var, class var, let, var, etc., the type is what matters--so no, Bool is value type.
I think you are not 100% on all of the terminology (mostly because Apple doesn't really cover it much in documentation as usual, lol).
There are "Swift Types" (Bool, Int, your classes/structs, etc), and "Variable/Constant Types" (which hold data in a memory register, such as references or actual-values), as well as "Memory Register Write/Read Types" (variable vs vonstant, mutable vs immutable, var vs let).
Don't be frustrated.. It's a bit confusing for everyone... Especially at first and without great documentation. (I tried learning C++ pointers early age and it was way over my head).
Here's a good reference material: (towards the bottom)
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html
Basically, if you want to hold a reference to something, you have to use a Reference Type memory register. This means using a class instance Static makes no difference:
/* 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 feel like you need a pointer to something that isn't inside of a class, then you can use UnsafeMutablePointer or something like that from OBJc code.
Or, you can wrap a bool inside of a class object (which are always references).
final class RefBool {
var val: Bool
init(_ value: Bool) { val = value }
}
And here is some interesting behavior for reference types using 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`

Related

Accessing a lazy property on a struct mutates the struct

I have a lazy property in a struct and every time I access it, it mutates the struct.
var numbers = [1,2,3]
struct MyStruct {
lazy var items = numbers
}
class MyClass {
var myStructPropery: MyStruct = MyStruct() {
didSet {
print(myStructPropery)
}
}
}
var myClass = MyClass()
myClass.myStructPropery.items
myClass.myStructPropery.items
myClass.myStructPropery.items
Result:
Print (didSet) will be called every time.
The ideal behaviour should be first time mutation only (since that's how lazy variables behave). Is this a bug in Swift or am I doing something wrong?
What you are seeing is is that the observed property items has notified its observer that it has been mutated because it was accessed, and a lazy variable is by definition mutating since it will be set at a later time. Therefore didSet gets called to handle this.
The lazy variable is actually only set once even though it signals that it has mutated and the property myStructPropery is only mutated once when the variable is first set but is the same instance after that.
Here is how we can verify this, first change the lazy var declaration so it's more like how we usually declare such a variable
lazy var items: [Int] = { numbers }()
and then add a print statement
lazy var items: [Int] = {
print("inside lazy")
return numbers
}()
If we now run the test code
var myClass = MyClass()
myClass.myStructProperty.items
myClass.myStructProperty.items
myClass.myStructProperty.items
we see that "inside lazy" only prints once. To verify that the property myStructProperty isn't changed we can make the struct conform to Equatable and perform a simple check inside didSet
didSet {
if oldValue != myStructProperty {
print(myStructProperty)
}
}
Now running the test we see that the print inside didSet is never executed so myStructProperty is never changed.
I have no idea if this behaviour is a bug but personally it feels like it might be complicate for the property observer to stop observing a lazy property once it was accessed or for a lazy var to not be defined as mutating once it is set.
I started debugging this with following set up -
var numbers = [1,2,3]
struct MyStruct {
lazy var items = numbers
}
class MyClass {
var myStructPropery: MyStruct = MyStruct() {
didSet {
// Changed this to make sure we are not invoking getter here
print("myStructPropery setter called")
}
}
}
let myClass = MyClass()
myClass.myStructPropery.items
myClass.myStructPropery.items
myClass.myStructPropery.items
I can reproduce the problem on Xcode 12.5 using Swift 5.4.
Attempt 1 : Turn var numbers into let numbers - Does NOT work.
let numbers = [1,2,3]
Attempt 2 : Assign the value inline without using an extra variable - Does NOT work.
struct MyStruct {
lazy var items = [1,2,3]
}
Attempt 3 : Assign the value inline using the full blown getter syntax - Does NOT work.
struct MyStruct {
lazy var items: [Int] = {
return [1,2,3]
}()
}
At this point, we are out of options to try. Even though we can clearly see that return [1,2,3] in the last attempt is executed exactly once, the MyClass.myStructPropery.modify is called repeatedly on access to items.
Maybe Swift Forums is a better place to discuss this.

Swift memoizing/caching lazy variable in a struct

I drank the struct/value koolaid in Swift. And now I have an interesting problem I don't know how to solve. I have a struct which is a container, e.g.
struct Foo {
var bars:[Bar]
}
As I make edits to this, I create copies so that I can keep an undo stack. So far so good. Just like the good tutorials showed. There are some derived attributes that I use with this guy though:
struct Foo {
var bars:[Bar]
var derivedValue:Int {
...
}
}
In recent profiling, I noticed a) that the computation to compute derivedValue is kind of expensive/redundant b) not always necessary to compute in a variety of use cases.
In my classic OOP way, I would make this a memoizing/lazy variable. Basically, have it be nil until called upon, compute it once and store it, and return said result on future calls. Since I'm following a "make copies to edit" pattern, the invariant wouldn't be broken.
But I can't figure out how to apply this pattern if it is struct. I can do this:
struct Foo {
var bars:[Bar]
lazy var derivedValue:Int = self.computeDerivation()
}
which works, until the struct references that value itself, e.g.
struct Foo {
var bars:[Bar]
lazy var derivedValue:Int = self.computeDerivation()
fun anotherDerivedComputation() {
return self.derivedValue / 2
}
}
At this point, the compiler complains because anotherDerivedComputation is causing a change to the receiver and therefore needs to be marked mutating. That just feels wrong to make an accessor be marked mutating. But for grins, I try it, but that creates a new raft of problems. Now anywhere where I have an expression like
XCTAssertEqaul(foo.anotherDerivedComputation(), 20)
the compiler complains because a parameter is implicitly a non mutating let value, not a var.
Is there a pattern I'm missing for having a struct with a deferred/lazy/cached member?
Memoization doesn't happen inside the struct. The way to memoize is to store a dictionary off in some separate space. The key is whatever goes into deriving the value and the value is the value, calculated once. You could make it a static of the struct type, just as a way of namespacing it.
struct S {
static var memo = [Int:Int]()
var i : Int
var square : Int {
if let result = S.memo[i] {return result}
print("calculating")
let newresult = i*i // pretend that's expensive
S.memo[i] = newresult
return newresult
}
}
var s = S(i:2)
s.square // calculating
s = S(i:2)
s.square // [nothing]
s = S(i:3)
s.square // calculating
The only way I know to make this work is to wrap the lazy member in a class. That way, the struct containing the reference to the object can remain immutable while the object itself can be mutated.
I wrote a blog post about this topic a few years ago: Lazy Properties in Structs. It goes into a lot more detail on the specifics and suggest two different approaches for the design of the wrapper class, depending on whether the lazy member needs instance information from the struct to compute the cached value or not.
I generalized the problem to a simpler one: An x,y Point struct, that wants to lazily compute/cache the value for r(adius). I went with the ref wrapper around a block closure and came up with the following. I call it a "Once" block.
import Foundation
class Once<Input,Output> {
let block:(Input)->Output
private var cache:Output? = nil
init(_ block:#escaping (Input)->Output) {
self.block = block
}
func once(_ input:Input) -> Output {
if self.cache == nil {
self.cache = self.block(input)
}
return self.cache!
}
}
struct Point {
let x:Float
let y:Float
private let rOnce:Once<Point,Float> = Once {myself in myself.computeRadius()}
init(x:Float, y:Float) {
self.x = x
self.y = y
}
var r:Float {
return self.rOnce.once(self)
}
func computeRadius() -> Float {
return sqrtf((self.x * self.x) + (self.y * self.y))
}
}
let p = Point(x: 30, y: 40)
print("p.r \(p.r)")
I made the choice to have the OnceBlock take an input, because otherwise initializing it as a function that has a reference to self is a pain because self doesn't exist yet at initialization, so it was easier to just defer that linkage to the cache/call site (the var r:Float)

Are let definitions in a Swift class allocated only once, or per instance?

Let's say I have the following simple Swift class:
class Burrito {
enum Ingredients {
case beans, cheese, lettuce, beef, chicken, chorizo
}
private let meats : Set<Ingredients> = [.beef, .chicken, .chorizo]
var fillings : Set<Ingredients>
init (withIngredients: Set<Ingredients>) {
fillings = withIngredients
}
func isVegetarian() -> Bool {
if fillings.intersect(meats).count > 0 {
return false
}
else {
return true
}
}
}
If I create multiple instances of Burrito in an application, is the Set meats defined in memory once, separate from the memory allocated for each instance? I would assume that the compiler would optimize that way, but I haven't been able to find an answer on this yet.
EDIT
With the great help from the accepted answer, and the comments about the logic in the isVegetarian() method, here is the modified class. Thanks everybody!
class Burrito {
enum Ingredients {
case beans, cheese, lettuce, beef, chicken, chorizo
}
private static let meats : Set<Ingredients> = [.beef, .chicken, .chorizo]
var fillings : Set<Ingredients>
init (withIngredients: Set<Ingredients>) {
fillings = withIngredients
}
func isVegetarian() -> Bool {
return fillings.intersect(Burrito.meats).isEmpty
}
// All burritos are delicious
func isDelicious() -> Bool {
return true
}
}
meats is an instance variable of the class. A new instance of meats will be made for every new instance (object) made from the class.
You can use the static keyword to make it a static variable, which will make it so there is only one instance of the meats variable, which is shared among all members of the class.
Immutable instance variables are typically used to be object-wide constants (rather than class-wide, like immutable static variables), which can have independent definitions for each object. In this case, the definition is static, so a smart compiler could optimize it into a static variable. Regardless, you should explicitly mark this static to communicate to users the intent of this variable.

Swift Variable Initialization via Type Instance

I want to declare some variables at the beginning of a class and have their values be modified later and elsewhere. I'd rather not assign an initial garbage value to these to keep things concise.
Can I declare variables of basic types by declaring them as instances of the type? An example of what I mean is this:
class foo() {
var isCool = Bool()
var someInteger = Int()
func gotTheFunc() -> Bool {
isCool = true
return isCool
}
}
The compiler lets me do this, but is it something I actually can / should do when declaring class properties like this?
Thanks!
You should set the properties in an init method, then you do not have to assign a value at declaration. For example:
init(someInt: Int, isCool: Bool) {
self.isCool = isCool
self.someInteger = someInt
}
The self keyword is not necessary, but makes it clear which is the class's property.
You can do that but when you declare variables with basic type initializers
var isCool = Bool()
var someInteger = Int()
the complier does this
var isCool = false
var someInteger = 0
If you want to declare variables with no value, you have to use optionals
var isCool : Bool?
var someInteger : Int?
but I would avoid optionals as much as possible.
Side note: class names should begin always with a capital letter
class Foo {}

Example of dispatch_once in Swift

Is there an example of how dispatch_once should be used in Swift? (Preferably one from Apple.)
Note: In this case, I'm not using it for a singleton; I want to run arbitrary code exactly once.
Update: I'm mainly interested in the convention recommended when using this in an instance method, but usage in a class method, function, and in the global context would be useful for completeness sake.
dispatch_once_t is type alias (Int). Header documentation:
/*!
* #typedef dispatch_once_t
*
* #abstract
* A predicate for use with dispatch_once(). It must be initialized to zero.
* Note: static and global variables default to zero.
*/
typealias dispatch_once_t = Int
And here's the quote from dispatch_once documentation:
The predicate must point to a variable stored in global or static
scope. The result of using a predicate with automatic or dynamic
storage (including Objective-C instance variables) is undefined.
Token variable must be stored in global / static scope and must be initialized to zero, which leads to this code:
import Foundation
var token: dispatch_once_t = 0
dispatch_once(&token) { () -> Void in
print("Called once")
}
It doesn't work if you omit = 0 (token initialization), because compiler yields error Address of variable 'token' taken before it is initialized despite the fact that statics and globals default to zero. Tested in Xcode 7B2.
More examples based on comment. If you're inside class method you have several possibilities.
You can't declare static property inside method otherwise compiler yields Static properties may only be declared on a type error. This doesn't work:
class func doItOnce() {
static var token: dispatch_once_t = 0
...
}
Must be declared on a type. This was introduced in Swift 1.2 (Xcode 6.3 IIRC).
“static” methods and properties are now allowed in classes (as an
alias for “class final”). You are now allowed to declare static stored
properties in classes, which have global storage and are lazily
initialized on first access (like global variables). Protocols now
declare type requirements as “static” requirements instead of
declaring them as “class” requirements. (17198298)
So, what we can do if we don't like globals?
Static variable on a type
class MyClass {
private static var token: dispatch_once_t = 0
class func doItOnce() {
dispatch_once(&token) {
print("Do it once")
}
}
}
Static in a method wrapped in struct
Don't like static property on yur class? Would like to have it in your method? Wrap it in struct like this:
class func doItOnce() {
struct Tokens { static var token: dispatch_once_t = 0 }
dispatch_once(&Tokens.token) {
print("Do it once")
}
}
Actually I'm not aware of any Apple recommendation, best practice, ... how to do it for dispatch_once. Simply use whatever you like most, feels good to you and just meet criteria global / static scope.
For those of you who are curious, for me this approach has been useful for this purpose:
class SomeVC : UIViewController {
private var token: dispatch_once_t = 0
public override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
dispatch_once(&token) { () -> Void in
self.doSomethingOnce()
}
}
}
By not declaring a static var it has the expected behaviour. That being said, this is definitely NOT RECOMMENDED for any serious project, since in the Docs (as your well said) it states:
The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage (including Objective-C instance variables) is undefined.
If we don't want to run into any future weird bugs and undefined behaviour I would just stick to what Apple says. But it's still nice to play around with these things, isn't it? =)
the robertvojta's answer is probably the best. because i try always to avoid import Foundation and use 'pure' Swift solution (with Swift3.0 i could change my opinion), I would like to share with you my own, very simple approach. i hope, this code is self-explanatory
class C {
private var i: Int?
func foo()->Void {
defer {
i = 0
}
guard i == nil else { return }
print("runs once")
}
}
let c = C()
c.foo() // prints "runs once"
c.foo()
c.foo()
let c1 = C()
c1.foo() // prints "runs once"
c1.foo()
class D {
static private var i: Int?
func foo()->Void {
defer {
D.i = 0
}
guard D.i == nil else { return }
print("runs once")
}
}
let d = D()
d.foo() // prints "runs once"
d.foo()
let d2 = D()
d.foo()