Simultaneous accesses to <Address>, but modification requires exclusive access - swift4

I want to specify the property which is an array for manipulation in the function myFunc, but I am getting this error. Here is my code sketch.
self.data = MyObject()
func myFunc(x: inout [Int], y: inout [[Int]]) {
//manipulation code to x and y
}
myFunc(x: &self.data.array1, y: &self.data.array2)
myFunc(x: &self.data.array3, y: &self.data.array4)
Any idea how to make it work? Is there a better pattern I should use for this use case? Thx for advance!

Very thoroughly explained in the Swift documentation:
https://docs.swift.org/swift-book/LanguageGuide/MemorySafety.html
Basically you are threatening to mutate / write to the same object in two different ways simultaneously. That’s incoherent and if the compiler doesn’t stop you the runtime will.

Related

Write a function that receives two Int’s at the input and changes their values, and at the same time doubles them

I ask for help, I’ve already broken my whole brain. It seems that I understand that it is not a very difficult task. I read the documentation and searched the Internet for a long time.
Write a function that receives two Int’s at the input and changes their values, and at the same time doubles them
I assume that changing their value means swapping them and then doubling. If that is the case, you can write your own function:
func swapAndDouble(a: Int, b: Int) -> (Int, Int) {
let returnTupple = (2*b, 2*a)
return returnTupple
}
Then with this call:
let (first, second) = swapAndDouble(a: 3, b: 7)
You have the result.
Alternatively, if you want to use the function later for other values there is a standard swap function in the standard Swift library.
func swap<T>(_ a: inout T, _ b: inout T)
Please, read the Apple Documentation for this.

why we have to make function explicitly mutating in Structures in Swift?

Why we have to make function explicitly mutating in Structures in Swift?
I want to understand behind the scene concept of this.
Can anyone explain how does it work?
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveBy(x: 2.0, y: 3.0)
print("The point is now at (\(somePoint.x), \(somePoint.y))")
// Prints "The point is now at (3.0, 4.0)"
As per Apple Documentation "if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method. The method can then mutate (that is, change) its properties from within the method, and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit self property, and this new instance will replace the existing one when the method ends."
Why it's not allowed to change properties of structures(value type) without mutating where as same is not the case with reference type?
Structs are value types and hence when you mutate any instance properties of a struct, you actually mutate the struct instance itself. This is why when you have a function that mutates any instance properties of the struct, you explicitly need to mark that function mutating, because calling the function mutates the struct instance itself too.
For more information, you should read the Methods chapter of the Swift Book, because it explains this behaviour in detail.

Swift 3 closure overload resolution

I'm confused by function overload resolution with closures in Swift 3.
For example, in the code:
func f<T>(_ a: T) {
print("Wide")
}
func f(_ a: (Int)->(Int)) {
print("Narrow")
}
f({(a: Int) -> Int in return a + 1})
I expect Narrow, not Wide, to be printed to the console. Can anyone explain why the more specific overload gets chosen for non-closure arguments but not for closures or is this a compiler bug?
Swift 2 exhibited the expected behavior.
This is probably due to the change in the default "escaping" behaviour for closure parameters.
If you change the specific function to:
func f(_ a:#escaping (Int)->Int)
{
print("Narrow")
}
it will print "Narrow" as expected (this is the same change that you probably had to make in several other places that were more obvious)

Are there any possible explicit uses of instances (values) of empty tuples (), i.e., of instances of typealias 'Void'?

Question:
Are there any possible explicit uses for the empty tuple (), as a value (and not as a type) in Swift 2.x?
I know that these empty tuples can be used in the standard sense to define void functions. When I mistakenly defined a variable with a empty tuple value var a = () (of type ()), I started wondering if these empty tuple values can be used in some context. Does anyone know of such an application?
Example: possible application with array and optionals?
As an example, we can create an optional array of empty tuples that, naturally, can only hold either nil or ():
/* Optionals */
var foo: ()? = ()
print(foo.dynamicType) // Optional<()>
var arr : [()?] = [foo]
for i in 2...8 {
if i%2 == 0 {
arr.append(nil)
}
else {
arr.append(foo)
}
}
print(arr) // [Optional(()), nil, Optional(()), ... ]
With the small memory footprint of empty tuple, this could seem neat for micro-memory-management for a "boolean nil/not nil", but since type Bool have the same small footprint, I can't really see any direct use here, even in the (unlike) scenario that we really need to go bit-low optimization on our operations.
Perhaps I'm just chasing my own tail with some narrow unusable applications, but anyway: are there any possible explicit uses for these void () beings (as instances, not types)?
There are lots of places that () can be useful when playing around with "CS" problems, which often have the form "implement X using Y even though you really already have X." So for instance, I might say, implement Set using Dictionary. Well, a Dictionary is a Key/Value pair. What should the type of the Value be? I've actually seen this done in languages that have Dictionaries but not Sets, and people often use 1 or true as the value. But that's not really what you mean. That opens up ambiguity. What if the value is false? Is it in the set or not? The right way to implement Set in terms of Dictionary is as [Key: ()], and then you wind up with lines of code like:
set[key] = ()
There are other, equivalent versions, like your Optional<()>. I could also implement integers as [()] or Set<()>. It's a bit silly, but I've done things like that to explore number theory before.
That said, these are all almost intentionally impractical solutions. How about a practical one? Those usually show up when in generic programming. For example, imagine a function with this kind of form:
func doThingAndReturn<T>(retval: T, f: () -> Void) -> T {
f()
return retval
}
This isn't as silly as it sounds. Something along these lines could easily show up in a Command pattern. But what if there's no retval; I don't care about the return? Well, that's fine, just pass a () value.
func doThing(f: () -> Void) {
doThingAndReturn((), f: f)
}
Similarly, you might want a function like zipMap:
func zipMap<T, U>(funcs: [(T) -> U], vals: [T]) -> [U] {
return zip(funcs, vals).map { $0($1) }
}
This applies a series of functions that take T to values of type T. We could use that even if T happens to (), but we'd have to generate a bunch of () values to make that work. For example:
func gen<T>(funcs: [() -> T]) -> [T] {
return zipMap(funcs, vals: Array(count: funcs.count, repeatedValue: ()))
}
I wouldn't expect this to come up very often in Swift because Swift is mostly an imperative language and hides its Void in almost all cases. But you really do see things like this show up in functional languages like Scala when they bridge over into imperative programming.
Suppose you have two functions overloading the same name:
func foo()
func foo() -> Int
The first doesn't return anything, the second returns some kind of value. Attempting to call either of these will in most cases get you a compiler error about ambiguity.
foo()
let a = foo()
You'd think that the compiler would know that the first call unambiguously refers to the first function, because it assumes no return value. But in actuality, the return type of a function with no declared return type is Void, or (). So the first call is actually more like this:
let _ = foo()
And absent a type annotation for the discarded lvalue, the compiler can't infer which foo to call. You can use explicit type annotations to disambiguate:
let b: Void = foo()
let c: Int = foo()
Okay, it's not a very great or common use case for Void, because it's a situation you'd tend to avoid getting into in the first place. But you asked for a use... and it is a use of () as a value and not just a type, because you can retrieve it from b after assignment (for all the good that does you).
Just beware, when you look deeply into the Void, the Void also looks into you. Or something like that.

How do I write a function that accepts Array<UInt8> or ArraySlice<UInt8>?

What I'm trying to do is to parse (part of) a binary protocol (MQTT) by writing a function like this:
func readString(bytes: Array<UInt8> OR ArraySlice<UInt8>) -> (string: String?, remainingBytes: ArraySlice<UInt8>?)
I know about polymorphism but I would prefer to have one function.
I have written a function (using generics), that accepts an Array or ArraySlice of UnsignedIntegerType but I only want UInt8. It seems like a straightforward thing to do but so far I haven't came up with a good solution...
What I would do is, first, forget about the return type and think just about what this function should accept as its parameter. In particular, think about what Array and Slice have in common and write a generic specifying that. They are both MutableCollectionType and Sliceable. And basically nothing else in the world is (nothing else that you are likely to use, that is).
Moreover, you want the element type to be UInt8.
So now just say that, the way a generic lets you say it:
func readString<T:MutableCollectionType
where T:Sliceable, T.Generator.Element == UInt8>(bytes: T) {
// ...
}
And here's a test:
let arr = [UInt8(1),UInt8(2),UInt8(3)]
readString(arr) // compiles
readString(arr[1...2]) // compiles
A nice thing about this formulation is that the compiler will test, if it can, to see if you are calling with legal integer types. For example, this compiles, because all the integers are small and positive:
readString([1,2,3])
But this doesn't even compile, because the compiler knows that a negative integer can't be a UInt8:
readString([-1,2,3])