Why isn't there a formSubtracting() method in Swift for Sets - swift

In Swift there is a Form... equivalent for the Sets methods intersection(), symmetricDifference() and union(), i.e. formIntersection(), formSymmetricDifference() and formUnion().
But for the method subtracting() there is no method called formSubtracting. Does anyone know why this is so, because it seams I now have to use something like mySet = mySet.subtracting(anotherSet)

subtract(_:) is what you are looking for:
Removes the elements of the given set from this set.
Example:
var mySet: Set = [1, 2, 3, 4, 5]
let anotherSet : Set = [2, 4, 6, 8]
mySet.subtract(anotherSet)
print(mySet) // [3, 1, 5]
There is also a variant which takes another sequence (of the same element type) as the argument, e.g. an array:
var mySet: Set = [1, 2, 3, 4, 5]
let anotherSequence = [2, 4, 6, 8]
mySet.subtract(anotherSequence)
print(mySet) // [3, 1, 5]

Related

Sorting with higher order functions: Giving precedence to one element

With an unordered array of Ints as such:
let numbers = [4, 3, 1, 5, 2]
Is it possible in Swift, using .sorted { }, to order the array with one item prioritised and placed in the first index of the array. So instead of returning [1, 2, 3, 4, 5] we could get [3, 1, 2, 4, 5]?
You can declare a function like this :
func sort(_ array: [Int], prioritizing n: Int) -> [Int] {
var copy = array
let pivot = copy.partition { $0 != n }
copy[pivot...].sort()
return copy
}
Which uses the partition(by:) function.
You could use it like so:
let numbers = [4, 3, 1, 5, 2]
let specialNumber = 3
sort(numbers, prioritizing: specialNumber) //[3, 1, 2, 4, 5]
Here are some test cases :
sort([3, 3, 3], prioritizing: 3) //[3, 3, 3]
sort([9, 4, 1, 5, 2], prioritizing: 3) //[1, 2, 4, 5, 9]
Here an alternative solution that uses sorted(by:) only :
let numbers = [4, 3, 1, 5, 2]
let vipNumber = 3
let result = numbers.sorted {
($0 == vipNumber ? Int.min : $0) < ($1 == vipNumber ? Int.min : $1)
}
print(result) //[3, 1, 2, 4, 5]

Attempting to Add Using Flatmap and Map in Swift

I'm attempting to add after transforming a two-dimensional array into a one dimensional array using the following code in a Playground:
let twoDimensionalArray = [[1, 3, 5], [2, 4, 6], [12, 15, 16]]
let oneDimensionalArray = twoDimensionalArray.flatMap { $0.map { $0 += 2 } }
print(oneDimensionalArray)
However I receive the error:
left side of mutating operator isn't mutable: '$0' is immutable
Also I see that the flatmap method is deprecated in the Apple Documentation so what should I be doing differently?
You almost right. All you need is remove =:
let twoDimensionalArray = [[1, 3, 5], [2, 4, 6], [12, 15, 16]]
let oneDimensionalArray = twoDimensionalArray.flatMap { $0.map { $0 + 2 } }
print(oneDimensionalArray) // [3, 5, 7, 4, 6, 8, 14, 17, 18]
You can apply changes to the value ($0) in closure by manipulating with it and something else, not by directly changing (i.e. $0 += 2).

Is it possible to match N elements with a coffeescript splat?

Is it possible to specify how many elements a splat should match? Something like:
foo = [1, 2, 3, 4, 5, 6]
[firstThree...(3), fourth, rest...] = foo
console.log firstThree // [1, 2, 3]
console.log forth // 4
console.log rest // [5, 6]
As far as I know there is no way of adding a limit to the amount of arguments a splat can take.
But you can use ranges(search for range in the Loops and Comprehensions Docs) to get a similar syntax in your destructuring assignment:
foo = [1, 2, 3, 4, 5, 6]
[firstThree, fourth, rest] = [foo[0..2], foo[3], foo[4..-1]]
firstThree
# => [1, 2, 3]
fourth
# => 4
rest
# => [5, 6]

Optimal Way to Remove Unique Values from Two Arrays

I have two arrays of [PFObjects].
For example (simplified):
arr1: [PFObject] = [1, 2, 3, 4, 5, 6, 7, 8]
arr2: [PFObject] = [1, 2, 3, 4, 5]
What is the optimal way to compare arr1 with arr2 and only keep the duplicates (remove unique values).
So that arr1 looks like:
arr1 = [1, 2, 3, 4, 5]
let array = arr1.filter { arr2.contains($0) }
voilĂ  !
First solution (Looping):
var arr1: [PFObject] = [1, 2, 3, 4, 5, 6, 7, 8]
var arr2: [PFObject] = [1, 2, 3, 4, 5]
var temp: [PFObject] = []
for element in arr1 {
if contains(arr2, element) {
temp.append(element)
}
}
arr1 = temp
You can loop over the first array, check if each element is contained in the array, if it is, you can add it to a temporary array. After looping over every element you can replace the value of the first array with your temporary array.
Second solution (Sets):
var arr1: [PFObject] = [1, 2, 3, 4, 5, 6, 7, 8]
var arr2: [PFObject] = [1, 2, 3, 4, 5]
let set1 = Set(arr1)
let set2 = Set(arr2)
var arr1= Array(set1.intersect(set2)) // [1, 2, 3, 4, 5]
What you do here is:
First you create sets from your arrays
Then you use the intersect method from sets to determine common elements
Finally you transform your set to an array before passing it back to arr1
Of course since you will be using sets, duplicate elements will be lost but I'm guessing that shouldn't be a problem in your case
Third solution (filter):
From the answer of Pham Hoan you can use filters to obtain a subset of arr1, the closure gives you the conditions, here it is that arr2 contains the value you are looking at.
let array = arr1.filter { arr2.contains($0) }
This is obviously the shorter solution in terms of code length.
I do not know which technique would be more efficient if you have very large arrays however.

Remove list element at index?

There is a serious lack of methods available to lists in Swift. It is really disappointing, coming from a Python background. For example, I want to remove the first element, something like this would work in Python:
mylist = mylist[1:]
How do I remove an element from a list (preferably by index, but I can do whatever method is easiest)?
Use removeAtIndex
var arr = [1, 2, 3]
arr.removeAtIndex(1)
If you want to remove a range of values, you can use removeRange:
var x = [1, 2, 3, 4, 5]
x.removeRange(1...2) // result is [1, 4, 5]
var x = [1, 2, 3, 4, 5]
x.removeRange(1..<2) // result is [1, 3, 4, 5]
Note that this method doesn't check for range bounds, so if you specify a range outside the array size, it will throw a runtime exception.