What trouble could bring assining reversed() to a swift array? - arrays

I'm wondering about the reversed() method on a swift Array:
var items = ["a", "b", "c"]
items = items.reversed()
the signature of the reversed method from the Apple doc says that it returns a
ReversedRandomAccessCollection<Array<Element>>
could that be assigned back to items without doing what the apple doc say which is
For example, to get the reversed version of an array, initialize a new Array instance from the result of this reversed() method.
or would it give problem in the future? (since the compiler doesn't complain)

There are 3 overloads of reversed() for an Array in Swift 3:
Treating the Array as a RandomAccessCollection,func reversed() -> ReversedRandomAccessCollection<Self> (O(1))
Treating the Array as a BidirectionalCollection,func reversed() -> ReversedCollection<Self> (O(1))
Treating the Array as a Sequence,func reversed() -> [Self.Iterator.Element] (O(n))
By default, reversed() pick the RandomAccessCollection's overload and return a ReversedRandomAccessCollection. However, when you write
items = items.reversed()
you are forcing the RHS to return a type convertible to the LHS ([String]). Thus, only the 3rd overload that returns an array will be chosen.
That overload will copy the whole sequence (thus O(n)), so there is no problem overwriting the original array.
Instead of items = items.reversed(), which creates a copy of the array, reverse that and copy it back, you could reach the same effect using the mutating function items.reverse(), which does the reversion in-place without copying the array twice.

Related

Reducing a Swift array to [Int:Int?] with nil initializer is empty

Why does reducing an array into a hash with the keys as array values and the value as nil give an empty result?
[1,2,3].reduce(into: [Int:Int?](), { $0[$1] = nil })
[1,2,3].reduce(into: [Int:Int?](), { $0[$1] = 1 })
Both of these should have 3 entries, right?
In Swift, setting a dictionary value to nil like you did in the question removes that value from the dictionary entirely. However there are some odd caveats to this.
In your example, you use a Dictionary with type [Int:Int?]:
var dictionary: [Int:Int?] = [1: 1, 2: 1, 3: 1]
Setting a value to nil in the following way removes it:
dictionary[1] = nil
Setting a value to nil with type Int? will assign nil instead:
dictionary[1] = nil as Int?
Likewise, using the updateValue(_:forKey:) function will do the same:
dictionary.updateValue(nil, forKey: 1)
Printing the dictionary after performing either of these operations would show the following:
[1: nil, 2: Optional(1), 3: Optional(1)]
So the behavior is a bit odd but it is possible to achieve your intended result. I don't really recommend it because of how unnatural it is; it is possible, though.
The behaviour is not at all odd actually, and it's a really natural outcome if you understand some fundamental features of Swift's dictionaries and optionals.
Nested optionals
Firstly, optionals are composable. You can have nested optionals, like Optional<Optional<Int>> (a.k.a. Int??). A nested optional like this has possible three values. To illustrate their difference, imagine the result of array.first, where array has type Array<Optional<Optional<Int>>:
Optional.some(Optional.some(someWrappedValue)), which is just the "non-nil" case, with a payload of someWrappedValue. In the context of array.first, that means the array is non-empty, and the first element is non-nil value someWrappedValue (of type Int).
Optional.some(Optional.none), which is a non-nil optional containing a nil. In the context of array.first, that means ten array is non-empty, and the first element is itself nil.
Optional.none, which is just a nil optional. In the context of array.first, that means the array is empty, and there is no first element.
Note the different between case 2 and case 3. "Where" the nil is "found" along the chain has a semantic difference. Optional.none (a.k.a. nil) means there are no elements, which is semantically different to Optional.some(Optional.none), which means there are elements, but the first of them is actually nil.
The precise meaning of nil
Secondly, nil is a shorthand for Optional<T>.none, where T is inferred from the context. For example, that's why let x = nil is illegal, because the type inference system has no clues as to what value of T is appropriate.
Note that nil on its own is inferred to a none at the "earliest" ("outermost") level of optionality. (Case 3, in the list above)
Assign nil through a dictionary subscript
Thirdly, assigning nil to a Dictionary through a subscript erases the value for the given key.
Putting it together
Given these three points, we can consider your example. The subscript of a dictionary is "one layer more optional" than the Value generic type of the dictionary. E.g. for a dict of type [Int: Int], the return type of the subscript operator is V?, and correspondingly, you can assign Int?.
Now consider your dictionary, of type [Int: Int?]. The subscript takes/returns an Int??. Let's consider the three possible cases in context, as before:
Assigning a value of type Optional.some(Optional.some(someWrappedValue)) makes the dict store a value of someWrappedValue for the key, as an Int?. This is what's happening when you write $0[$1] = 1 (Swift is implicitly promoting 1 to Optional.some(Optional.some(1)).
Assigning a value of type Optional.some(Optional.none) makes the dict store a value of nil for the key, as an Int?. This is the part you were missing.
Assigning a value of type Optional.none makes the dict erase any value that might have existed for the key. This is what's happening when you write $0[$1] = nil
So to make this code give your designed outcome, you need to supply a value of the second type. You can do this with:
[1,2,3].reduce(into: [Int:Int?]()) { $0[$1] = Optional.some(nil) }

How to merge 2 arrays of equal length into a single dictionary with key:value pairs in Godot?

I have been trying to randomize the values in an ordered array (ex:[0,1,2,3]) in Godot. There is supposed to be a shuffle() method for arrays, but it seems to be broken and always returns "null". I have found a workaround that uses a Fisher-Yates shuffle, but the resulting array is considered "unsorted" by the engine, and therefore when I try to use methods such as bsearch() to find a value by it's position, the results are unreliable at best.
My solution was to create a dictionary, comprised of an array containing the random values I have obtained, merged with a second array of equal length with (sorted) numbers (in numerical order) which I can then use as keys to access specific array positions when needed.
Question made simple...
In GDScript, how would you take 2 arrays..
ex: ARRAY1 = [0,1,2,3]
ARRAY2 = [a,b,c,d]
..and merge them to form a dictionary that looks like this:
MergedDictionary = {0:a, 1:b, 2:c, 3:d}
Any help would be greatly appreciated.
Godot does not support "zip" methodology for merging arrays such as Python does, so I am stuck merging them manually. However... there is little to no documentation about how to do this in GDScript, despite my many hours of searching.
Try this:
var a = [1, 2, 3]
var b = ["a", "b", "c"]
var c = {}
if a.size() == b.size():
var i = 0
for element in a:
c[element] = b[i]
i += 1
print("Dictionary c: ", c)
If you want to add elements to a dictionary, you can assign values to the keys like existing keys.

Return only the first and last items of an array in Ruby

I need to create a method named first_and_last. It should use one argument, an Array, and return a new Array with only the first and last objects of the argument.
Here is what I have so far, but the method seems to ignore the initial argument and just create a new array.
def first_and_last(a)
arr = Array.new
arr = ["a", "b", "c"]
end
You can use the values_at() method to get the first and last elements in an array like this:
def first_and_last(input_array)
input_array.values_at(0,-1)
end
Depending on what behavior you're looking for, it might not work on arrays with 1 or 0 elements. You can read more about the method here.
You can also use .first for the first element in the array, and .last for the last element in an array.
def first_and_last(arr)
[arr.first, arr.last]
end
p first_and_last([1,2,3,4,5,6])
Or....
def first_and_last(arr)
[arr[0], arr[-1]]
end
p first_and_last([1,2,3,4,5,6])

Array operations that changes the order of element in scala

In scala documentation it states that Lists are immutable and "you can rely on the fact that accessing the same collection value repeatedly at different points in time will always yield a collection with the same elements" On the other hand in arrays (mutable) some operations can change the element. Can you give me some array examples for those operations that changes element by comparing with example on lists?
val arr = Array(3,5,7)
arr(1) = 0 // arr is now Array(3,0,7)
val lst = List(3,5,7)
lst(1) = 0 // error: value update is not a member of List[Int]

Cannot use "find()" method with an array of type UIView

When I try to use this method the compiler shows the next error: "Type 'UIView' does not conform to protocol 'IntegerLiteralConvertible'"
if find(_views, 1) {
}
That method signature is:
find(domain: C, value: C.Generator.Element) -> C.Index?
Where C is a typed array, C.Generator.Element is the type of the elements in that array, and C.Index? is an optional that will contain the index the element is found at, if found at all.
So the error you are getting is because it looking at the instances in your array UIView and trying to compare them to 1 which is an IntegerLiteral. And UIView is not IntegerLiteralConvertible because it would make no sense to convert a view to an integer.
So find will return the index where some instances can be found in an array of those instances.
var strings: [String] = ["A", "B", "C"]
find(strings, "C")! // 2
But you don't seem to want the index. if find(views, 1) seems to indicate to me that you want to check if index 1 exists in the array. If this is really what you want, you can do this very simply by checking the count.
if _views.count > 1 {
println("index 1 exists in this array")
}

Resources