Can 'mutating' be inferred for functions inside structs? - swift

Why should we be required to specify mutating for a function in a struct explicitly? Can't it be inferred automatically from the function body while compiling? If it can't, can you please give me an example where it can't...

There are some special examples when the compiler cannot infer mutability because it's the programmer decision to say whether the behavior should be considered as mutable.
For example, when the struct is backed up by a class:
struct MyArray<T : AnyObject> {
let buffer: NSMutableArray = NSMutableArray()
func append(item: T) {
buffer.addObject(item)
}
}
let myArray = MyArray<NSString>()
myArray.append("something")
Note that the append function is modifying the struct but it doesn't have the mutating attribute, so you can use it even on constant variables. If you want to prevent that, you need to add the mutating attribute.
I didn't choose the array example accidentally. The dictionaries and arrays in Swift are backed up by classes and they had to choose which methods would be mutating and which wouldn't.

Related

Swift issue when storing Object inside a struct

I am confused of how memory is managed here, lets say there is a scenario:
import Foundation
class SomeObject {
deinit {
print("deinitCalled")
}
}
struct SomeStruct {
let object = SomeObject()
var closure: (() -> Void)?
}
func someFunction() {
var someStruct = SomeStruct()
someStruct.closure = {
print(someStruct)
}
someStruct.closure?()
}
someFunction()
print("the end")
What I would expect here is:
Optional(test.SomeStruct(object: test.SomeObject, closure: Optional((Function))))
deinitCalled
the end
However what I get is this:
SomeStruct(object: test.SomeObject, closure: Optional((Function)))
the end
And if I look at memory map:
retain cycle
How do I manage memory in this case
First, you should be very, very careful about putting reference types inside of value types, and especially a mutable reference type that is visible to the outside world. Structs are always value types, but you also want them to have value semantics, and it's challenging to do that while containing reference types. (It's very possible, lots of stdlib types do it in order to implement copy-on-write; it's just challenging.)
So the short version is "you almost certainly don't want to do what you're doing here."
But if you have maintained value semantics in SomeStruct, then the answer is to just make a copy. It's always fine to make a copy of a value type.
someStruct.closure = { [someStruct] in
print(someStruct)
}
This gives the closure it's own immutable value that is a copy of someStruct. Future changes to someStruct won't impact this closure.
If you mean for future changes to someStruct to impact this closure, then you may be violating value semantics, and you should redesign (likely by making SomeStruct a class, if you mean it to have reference semantics).

Cannot assign to property: 'self' is immutable, I know how to fix but needs understanding

I have a struct :
public struct MyStruct {
public var myInt: Int = 0
...
}
I have a extension of MyStruct:
extension MyStruct {
public func updateValue(newValue: Int) {
// ERROR: Cannot assigned to property: 'self' is immutable
self.MyInt = newValue
}
}
I got the error showing above, I know I can fix the error by several ways, e.g. add a mutating keyword before func.
I am here not asking how to fix the error, but ask why swift doesn't allow this kind of value assignment ? I need an explanation besides a fix.
struct is a value type. For value types, only methods explicitly marked as mutating can modify the properties of self, so this is not possible within a computed property.
If you change struct to be a class then your code compiles without problems.
Structs are value types which means they are copied when they are passed around.So if you change a copy you are changing only that copy, not the original and not any other copies which might be around.If your struct is immutable then all automatic copies resulting from being passed by value will be the same.If you want to change it you have to consciously do it by creating a new instance of the struct with the modified data. (not a copy)
A tricky one: mark it as #State
Because a Struct is a value type, and therefore should be immutable

Swift: why mutating function can not be static

I have a theoretical question, I did not find related topics.
At some point, I decided that it would be nice to have a small extension for an array:
var array = [Int]()
array += 1
The code is quite simple:
extension Array {
mutating static func +=(lhs: Array, rhs: Element) {
lhs.append(rhs)
}
}
To achieve this we align with two factors that make perfect sense to me:
Array is a struct and this operation requires a mutation
Infix operator reload requires a static function
Unfortunately, it is impossible due Swift does not allow mutating functions to be static. And this is the part I don't quite understand.
Your += mutates the first argument, not the Array type.
Therefore it must not be declared mutating (which makes no
sense for a static method because you cannot mutate the type), but the first parameter must be inout:
extension Array {
static func +=(lhs: inout Array, rhs: Element) {
lhs.append(rhs)
}
}
var array = [Int]()
array += 1
print(array) // [1]
Because mutating doesn't mean "mutates anything", but rather, "mutates self". Your function attempts to mutate lhs, not self.
Your current code won't work because lhs is being passed by value. The lhs parameter is a local copy of whatever argument the caller supplied to it, thus any changes your function makes will be local to the function and won't persist. You'll need to instead have lhs be passed by reference, by delcaring it as a inout Array.
By using static keyword before method name means, we call method by struct/class name (Not by an object) so we don't have any object here.
By using mutating keyword, we are mutating 'self' object.
So while using static we don't have any object to mutate.

Swift constants: Struct or Enum

I'm not sure which of both are better to define constants. A struct or a enum. A struct will be copied every time i use it or not? When i think about a struct with static let constants it makes no sense that it will copied all the time, in my opinion. But if it won't copied then it doesn't matter what I take?
What advantages does the choice of a struct or enum?
Francescu says use structs.
Ray Wenderlich says use enums. But I lack the justification.
Both structs and enumerations work. As an example, both
struct PhysicalConstants {
static let speedOfLight = 299_792_458
// ...
}
and
enum PhysicalConstants {
static let speedOfLight = 299_792_458
// ...
}
work and define a static property PhysicalConstants.speedOfLight.
Re: A struct will be copied every time i use it or not?
Both struct and enum are value types so that would apply to enumerations as well. But that is irrelevant here
because you don't have to create a value at all:
Static properties (also called type properties) are properties of the type itself, not of an instance of that type.
Re: What advantages has the choice of a struct or enum?
As mentioned in the linked-to article:
The advantage of using a case-less enumeration is that it can't accidentally be instantiated and works as a pure namespace.
So for a structure,
let foo = PhysicalConstants()
creates a (useless) value of type PhysicalConstants, but
for a case-less enumeration it fails to compile:
let foo = PhysicalConstants()
// error: 'PhysicalConstants' cannot be constructed because it has no accessible initializers
Here's a short answer: Do your constants need to be unique? Then use an enum, which enforces this.
Want to use several different constants to contain the same value (often useful for clarity)? Then use a struct, which allows this.
One difference between the two is that structs can be instantiated where as enums cannot. So in most scenarios where you just need to use constants, it's probably best to use enums to avoid confusion.
For example:
struct Constants {
static let someValue = "someValue"
}
let _ = Constants()
The above code would still be valid.
If we use an enum:
enum Constants {
static let someValue = "someValue"
}
let _ = Constants() // error
The above code will be invalid and therefor avoid confusion.
Using Xcode 7.3.1 and Swift 2.2
While I agree with Martin R, and the Ray Wenderlich style guide makes a good point that enums are better in almost all use cases due to it being a pure namespace, there is one place where using a struct trumps enums.
Switch statements
Let's start with the struct version:
struct StaticVars {
static let someString = "someString"
}
switch "someString" {
case StaticVars.someString: print("Matched StaticVars.someString")
default: print("Didn't match StaticVars.someString")
}
Using a struct, this will match and print out Matched StaticVars.someString.
Now lets consider the caseless enum version (by only changing the keyword struct to enum):
enum StaticVars {
static let someString = "someString"
}
switch "someString" {
case StaticVars.someString: print("Matched StaticVars.someString")
default: print("Didn't match StaticVars.someString")
}
You'll notice that you get a compile time error in the switch statement on the case StaticVars.someString: line. The error is Enum case 'someString' not found in type 'String'.
There's a pseudo-workaround by converting the static property to a closure that returns the type instead.
So you would change it like this:
enum StaticVars {
static let someString = { return "someString" }
}
switch "someString" {
case StaticVars.someString(): print("Matched StaticVars.someString")
default: print("Didn't match StaticVars.someString")
}
Note the need for parentheses in the case statement because it's now a function.
The downside is that now that we've made it a function, it gets executed every time it's invoked. So if it's just a simple primitive type like String or Int, this isn't so bad. It's essentially a computed property. If it's a constant that needs to be computed and you only want to compute it once, consider computing it into a different property and returning that already computed value in the closure.
You could also override the default initializer with a private one, and then you'll get the same kind of compile time error goodness as with the caseless enum.
struct StaticVars {
static let someString = "someString"
private init() {}
}
But with this, you'd want to put the declaration of the struct in its own file, because if you declared it in the same file as, say, a View Controller class, that class's file would still be able to accidentally instantiate a useless instance of StaticVars, but outside the class's file it would work as intended. But it's your call.
In the Combine framework, Apple has chosen to prefer enums for namespaces.
enum Publishers
A namespace for types that serve as publishers.
enum Subscribers
A namespace for types that serve as subscribers.
enum Subscriptions
A namespace for symbols related to subscriptions.

Get the class or struct that conforms to a protocol for use in function using Generics

My question if you have an Array of objects that conforms to a protocol. I want to iterate over the array calling a method on each member in the array. However the method I want to call is static and uses generics. I need to get the class of the element in the array to do this. how do you get the class of that object? Is it possible?
I am writing a library of generic functions in Swift.
I have a protocol called DBAble which has as function:
static func get<T: DBable >(id:Int) -> T?
I have an array of objects that conform to DBAble:
let objs:[DBAble] = []
I want to iterate over the array and call:
for obj in objs {
obj.get(id: anInt)
}
however I am getting this message:
Static member 'get' cannot be used on instance of type 'DBable.Protocol'
Is there a way of finding the class (or type of struct) of the object that conforms to the protocol? I understand that I can do:
if obj is User {
}
however this is not the solution I am looking for.
The problem with the application approach it that the type T in the bellow method
static func get<T: DBable >(id:Int) -> T?
has to be known at compile time, whereas the the dynamicType will give you the type at run time.
For anyone else considering this question the answer is no it is not possible to find the type for use in a generic function at runtime. As explained in the comments by #hamish
"element.dynamicType is the actual type of a given element in your array. Your get(_:) method has a generic parameter T that must be known at compile time"