According to Apple's official book "The Swift Programming Language (Swift 2.1)":
AnyObject can represent an instance of any class type.
Any can represent an instance of any type at all, including function types.
Knowing that, I wanted to emulate Python-like nested list using an Any array.
let array = [1, 2, [3, 4], [5, 6, [7, 8]], 1]
Since Int and Array are value types, I supposed that array would be typed as [Any]
But this wasn't the case here :
func flatten(list:[Any]) -> [Any] {
var new = [Any]()
for element in list {
if let array = element as? [Any] {
// this code never runs
let flattened = flatten(array)
for x in flattened {
new.append(y)
}
}else{
new.append(element)
}
}
return new
}
Note: calling this function gave me EXC_BAD_INSTRUCTION error at first until I did this tweak :
let array : [Any] = [1, 2, [3, 4], [5, 6, [7, 8]], 1]
Output : [1, 2, [3, 4], [5, 6, [7, 8]], 1]
Expected : [1, 2, 3, 4, 5, 6, 7, 8, 1]
Unexplained Solution:
I replaced everywhere in this example Any by AnyObject
Numbers now are of type NSNumber
func flatten(list:[AnyObject]) -> [AnyObject] {
var new = [AnyObject]()
for element in list {
if let array = element as? [AnyObject] {
let flattened = flatten(array)
for x in flattened {
new.append(y)
}
}else{
new.append(element)
}
}
return new
}
Output : [1, 2, 3, 4, 5, 6, 7, 8, 1]
Expected : [1, 2, 3, 4, 5, 6, 7, 8, 1]
Question :
Why is it working with [AnyObject] / NSArray and not with [Any], despite the fact that integer literals are mainly of type Int not NSNumber and array literals are of type Array and not NSArray? Is something wrong with my example?
When you use Any, Swift will wrap your nested array elements into NSArray and not into Swift arrays (which can't hold all Objective-C types). So your test if let array = element as? [Any] { will not be true if you use Any because the resulting array isn't of type [Any] but NSArray.
So if you want a function that manages Any you can change your test for:
if let nestedArray = element as? NSArray {
You then have to define a new flattenArray() function with an NSArray prototype:
func flattenArray(array: NSArray) -> [Any] {
var flattenedArray: [Any] = []
for element in array {
// We have an array
if let nestedArray = element as? NSArray {
flattenedArray = flattenedArray + flattenArray(nestedArray)
} else {
// We have a single element
flattenedArray.append(element)
}
}
return flattenedArray
}
func flattenArray(array: [Any]) -> [Any] {
var flattenedArray: [Any] = []
for element in array {
// We have an array
if let nestedArray = element as? NSArray {
flattenedArray = flattenedArray + flattenArray(nestedArray)
} else {
// We have a single element
flattenedArray.append(element)
}
}
return flattenedArray
}
and it will do the trick.
We could probably imagine a more elegant solution but with this example you get the idea behind this issue.
Related
Let's say that I have some code like this:
let arr = [[1, 2], [3, 4, 5], [6, 7, 8, 9, 10]]
How would I define a function that it takes in a number i such that it goes to the ith array in arr and it prints the number of elements?
For example, let's say the function is called arrcount. Then,
arrcount(1) = 2, arrcount(2) = 3, and arrcount(3) = 5.
You don't actually need a function to achieve this:
arr[2].count // will return 5
Something along these lines should work
func countNumberOfItems(at index: Int, from arr: [Array<Any>]) -> Int? {
if index < arr.count, let temp = arr[index] as? Array {
return temp.count
} else {
return nil
}
}
let's say I have an array this way : [1,4,7,4,2,2,4,7,1,2].
I need a function that divides this array into arrays with the same elements so it shows a result as this in swift :
result = [[1,1],[4,4,4],[7,7],[2,2,2]] .
How to do that in swift ? Thanks in advance
You can use a helper dictionary to categorize the values of your array into the appropriate bins. E.g.:
let arr = [1, 4, 7, 4, 2, 2, 4, 7, 1, 2]
var dict: [Int: [Int]] = [:]
arr.forEach { dict[$0] = (dict[$0] ?? []) + [$0] }
let inBins = dict.map{ $1 }.sorted{ $0.first ?? 0 < $1.first ?? 0 }
print(inBins) // [[1, 1], [2, 2, 2], [4, 4, 4], [7, 7]]
Or, make use of the general Sequence extension for the categorising part, as described in the accepted answer in thread linked to by #Hamish:
How to group by the elements of an array in Swift
E.g.:
/* from https://stackoverflow.com/a/39388832/4573247:
#mientus's Swift 3 translation of #oisdk's accepted answer */
public extension Sequence {
func categorise<U : Hashable>(_ key: (Iterator.Element) -> U) -> [U:[Iterator.Element]] {
var dict: [U:[Iterator.Element]] = [:]
for el in self {
let key = key(el)
if case nil = dict[key]?.append(el) { dict[key] = [el] }
}
return dict
}
}
let arr = [1, 4, 7 ,4, 2, 2, 4, 7, 1, 2]
let inBins = arr.categorise{ $0 }.map{ $1 }.sorted{ $0.first ?? 0 < $1.first ?? 0 }
print(inBins) // [[1, 1], [2, 2, 2], [4, 4, 4], [7, 7]]
No need for the bins to be sorted (as above)? The two options above are then reduced to (simply dropping the last sortin part):
// ... first alternative above
let inBins = dict.map{ $1 }
// ... 2nd alternative above
let inBins = arr.categorise{ $0 }.map{ $1 }
Another option could be to create an NSCountedSet:
let array = [1,4,7,4,2,2,4,7,1,2]
let countedSet = NSCountedSet(array: array)
You could then easily get the count of each unique element:
let countForOne = countedSet.count(for: 1)
As far as I know there is no native Swift equivalent of NSCountedSet yet.
Basically I need a version of appendContentsOf: which does not append duplicate elements.
Example
var a = [1, 2, 3]
let b = [3, 4, 5]
a.mergeElements(b)
//gives a = [1, 2, 3, 4, 5] //order does not matter
Simply :
let unique = Array(Set(a + b))
Swift 5
Updated
In case you need to combine multiple arrays.
func combine<T>(_ arrays: Array<T>?...) -> Set<T> {
return arrays.compactMap{$0}.compactMap{Set($0)}.reduce(Set<T>()){$0.union($1)}
}
Usage examples:
1.
let stringArray1 = ["blue", "red", "green"]
let stringArray2 = ["white", "blue", "black"]
let combinedStringSet = combine(stringArray1, stringArray2)
// Result: {"green", "blue", "red", "black", "white"}
let numericArray1 = [1, 3, 5, 7]
let numericArray2 = [2, 4, 6, 7, 8]
let numericArray3 = [2, 9, 6, 10, 8]
let numericArray4: Array<Int>? = nil
let combinedNumericArray = Array(combine(numericArray1, numericArray2, numericArray3, numericArray4)).sorted()
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
This is commonly called a union, which is possible in Swift using a Set:
let a = [1, 2, 3]
let b = [3, 4, 5]
let set = Set(a)
let union = set.union(b)
Then you can just convert the set into an array:
let result = Array(union)
Swift 4.0 Version
extension Array where Element : Equatable {
public mutating func mergeElements<C : Collection>(newElements: C) where C.Iterator.Element == Element{
let filteredList = newElements.filter({!self.contains($0)})
self.append(contentsOf: filteredList)
}
}
As mentioned: The array passed to the function is the array of object that will be omitted from the final array
Swift 3.0 version of the accepted answer.
extension Array where Element : Equatable{
public mutating func mergeElements<C : Collection>(newElements: C) where C.Generator.Element == Element{
let filteredList = newElements.filter({!self.contains($0)})
self.append(contentsOf: filteredList)
}
}
Note: Worth saying here that the array passed to the function is the array of object that will be omitted from the final array. Important if your merging an array of objects where the Equatable property may be the same but others may differ.
An Array extension can be created to do this.
extension Array where Element : Equatable{
public mutating func mergeElements<C : CollectionType where C.Generator.Element == Element>(newElements: C){
let filteredList = newElements.filter({!self.contains($0)})
self.appendContentsOf(filteredList)
}
}
Of course, this is useful for only Equatable elements.
I combined my extension of Sequence and Array with this answer to provide easy syntax when merging arrays with custom objects by a single property:
extension Dictionary {
init<S>(_ values: S, uniquelyKeyedBy keyPath: KeyPath<S.Element, Key>) where S : Sequence, S.Element == Value {
let keys = values.map { $0[keyPath: keyPath] }
self.init(uniqueKeysWithValues: zip(keys, values))
}
}
// Unordered example
extension Sequence {
func merge<T: Sequence, U: Hashable>(mergeWith: T, uniquelyKeyedBy: KeyPath<T.Element, U>) -> [Element] where T.Element == Element {
let dictOld = Dictionary(self, uniquelyKeyedBy: uniquelyKeyedBy)
let dictNew = Dictionary(mergeWith, uniquelyKeyedBy: uniquelyKeyedBy)
return dictNew.merging(dictOld, uniquingKeysWith: { old, new in old }).map { $0.value }
}
}
// Ordered example
extension Array {
mutating func mergeWithOrdering<U: Hashable>(mergeWith: Array, uniquelyKeyedBy: KeyPath<Array.Element, U>) {
let dictNew = Dictionary(mergeWith, uniquelyKeyedBy: uniquelyKeyedBy)
for (key, value) in dictNew {
guard let index = firstIndex(where: { $0[keyPath: uniquelyKeyedBy] == key }) else {
append(value)
continue
}
self[index] = value
}
}
}
Test:
#testable import // Your project name
import XCTest
struct SomeStruct: Hashable {
let id: Int
let name: String
}
class MergeTest: XCTestCase {
let someStruct1 = SomeStruct(id: 1, name: "1")
let someStruct2 = SomeStruct(id: 2, name: "2")
let someStruct3 = SomeStruct(id: 2, name: "3")
let someStruct4 = SomeStruct(id: 4, name: "4")
var arrayA: [SomeStruct]!
var arrayB: [SomeStruct]!
override func setUp() {
arrayA = [someStruct1, someStruct2]
arrayB = [someStruct3, someStruct4]
}
func testMerging() {
arrayA = arrayA.merge(mergeWith: arrayB, uniquelyKeyedBy: \.id)
XCTAssert(arrayA.count == 3)
XCTAssert(arrayA.contains(someStruct1))
XCTAssert(arrayA.contains(someStruct3))
XCTAssert(arrayA.contains(someStruct4))
}
func testMergingWithOrdering() {
arrayA.mergeWithOrdering(mergeWith: arrayB, uniquelyKeyedBy: \.id)
XCTAssert(arrayA.count == 3)
XCTAssert(arrayA[0] == someStruct1)
XCTAssert(arrayA[1] == someStruct3)
XCTAssert(arrayA[2] == someStruct4)
}
}
How do I split a deck of cards? I have an array made and a random card dealer, but have no idea how to split the deck.
Thanks everyone for the help! I now have a working card app, did run into other problems but they were solved quickly.
You can make an extension so it can return an array of two arrays, working with Ints, Strings, etc:
extension Array {
func split() -> [[Element]] {
let ct = self.count
let half = ct / 2
let leftSplit = self[0 ..< half]
let rightSplit = self[half ..< ct]
return [Array(leftSplit), Array(rightSplit)]
}
}
let deck = ["J", "Q", "K", "A"]
let nums = [0, 1, 2, 3, 4]
deck.split() // [["J", "Q"], ["K", "A"]]
nums.split() // [[0, 1], [2, 3, 4]]
But returning a named tuple is even better, because it enforces the fact that you expect exactly two arrays as a result:
extension Array {
func split() -> (left: [Element], right: [Element]) {
let ct = self.count
let half = ct / 2
let leftSplit = self[0 ..< half]
let rightSplit = self[half ..< ct]
return (left: Array(leftSplit), right: Array(rightSplit))
}
}
let deck = ["J", "Q", "K", "A"]
let splitDeck = deck.split()
print(splitDeck.left) // ["J", "Q"]
print(splitDeck.right) // ["K", "A"]
Note: credits goes to Andrei and Qbyte for giving the first correct answer, I'm just adding info.
You can use subscript range
let deck: [String] = ["J", "Q", "K", "A"]
// use ArraySlice only for transient computation
let leftSplit: ArraySlice<String> = deck[0 ..< deck.count / 2] // "J", "Q"
let rightSplit: ArraySlice<String> = deck[deck.count / 2 ..< deck.count] // "K", "A"
// make arrays from ArraySlice
let leftDeck: [String] = Array(leftSplit) // "J", "Q"
let rightDeck: [String] = Array(rightSplit) // "K", "A"
EDIT: above code is for Swift 2, maybe for Swift 3 is a more convenient way.
Swift
More generic solution to split the array into chunks the answer from this link
extension Array {
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}
let numbers = Array(1...100)
let result = numbers.chunked(into: 5)
And one more realization of previously provided ideas. Firstly, up to Swift current documentation, it is better to choose names in past simple tense for functions that produce some result and present tense for mutating ones.
As second, as for me, it is better to choose half adding count % 2 to give more uniformed result.
Here is it:
extension Array {
func devided() -> ([Element], [Element]) {
let half = count / 2 + count % 2
let head = self[0..<half]
let tail = self[half..<count]
return (Array(head), Array(tail))
}
}
And results:
let set1 = [1, 2, 3, 4, 5, 6, 7,8]
let set2 = [1, 2, 3, 4, 5]
let set3 = [1]
let set4 = [Int]()
print(set1.devided())
print(set2.devided())
print(set3.devided())
print(set4.devided())
([1, 2, 3, 4], [5, 6, 7, 8])
([1, 2, 3], [4, 5])
([1], [])
([], [])
You can create an extension on SequenceType, and create a function named divide.
This function would iterate through the elements of the sequence while placing those that match the predicate into one array (slice) and those that do not match into another array (remainder).
The function returns a tuple containing the slice and the remainder.
extension SequenceType {
/**
Returns a tuple with 2 arrays.
The first array (the slice) contains the elements of self that match the predicate.
The second array (the remainder) contains the elements of self that do not match the predicate.
*/
func divide(#noescape predicate: (Self.Generator.Element) -> Bool) -> (slice: [Self.Generator.Element], remainder: [Self.Generator.Element]) {
var slice: [Self.Generator.Element] = []
var remainder: [Self.Generator.Element] = []
forEach {
switch predicate($0) {
case true : slice.append($0)
case false : remainder.append($0)
}
}
return (slice, remainder)
}
}
This is an example
let tuple = [1, 2, 3, 4, 5].divide({ $0 >= 3 })
tuple.slice // [3, 4, 5]
tuple.remainder // [1, 2]
I have two arrays like this:
var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]
As you can see, James and Steve match and I want to be able to remove them from arrayA. How would I write this?
#francesco-vadicamo's answer in Swift 2/3/4+
arrayA = arrayA.filter { !arrayB.contains($0) }
The easiest way is by using the new Set container (added in Swift 1.2 / Xcode 6.3):
var setA = Set(arrayA)
var setB = Set(arrayB)
// Return a set with all values contained in both A and B
let intersection = setA.intersect(setB)
// Return a set with all values in A which are not contained in B
let diff = setA.subtract(setB)
If you want to reassign the resulting set to arrayA, simply create a new instance using the copy constructor and assign it to arrayA:
arrayA = Array(intersection)
The downside is that you have to create 2 new data sets.
Note that intersect doesn't mutate the instance it is invoked in, it just returns a new set.
There are similar methods to add, subtract, etc., you can take a look at them
Like this:
var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]
for word in arrayB {
if let ix = find(arrayA, word) {
arrayA.removeAtIndex(ix)
}
}
// now arrayA is ["Mike", "Stacey"]
I agree with Antonio's answer, however for small array subtractions you can also use a filter closure like this:
let res = arrayA.filter { !contains(arrayB, $0) }
matt and freytag's solutions are the ONLY ones that account for duplicates and should be receiving more +1s than the other answers.
Here is an updated version of matt's answer for Swift 3.0:
var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]
for word in arrayB {
if let ix = arrayA.index(of: word) {
arrayA.remove(at: ix)
}
}
Original answer
This can also be implemented as a minus func:
func -<T:RangeReplaceableCollectionType where T.Generator.Element:Equatable>( lhs:T, rhs:T ) -> T {
var lhs = lhs
for element in rhs {
if let index = lhs.indexOf(element) { lhs.removeAtIndex(index) }
}
return lhs
}
Now you can use
arrayA - arrayB
Updated implementation for Swift 5
func -<T: RangeReplaceableCollection>(lhs: T, rhs: T) -> T where T.Iterator.Element: Equatable {
var lhs = lhs
for element in rhs {
if let index = lhs.firstIndex(of: element) { lhs.remove(at: index) }
}
return lhs
}
Using the Array → Set → Array method mentioned by Antonio, and with the convenience of an operator, as freytag pointed out, I've been very satisfied using this:
// Swift 3.x/4.x
func - <Element: Hashable>(lhs: [Element], rhs: [Element]) -> [Element]
{
return Array(Set<Element>(lhs).subtracting(Set<Element>(rhs)))
}
For smaller arrays I use:
/* poormans sub for Arrays */
extension Array where Element: Equatable {
static func -=(lhs: inout Array, rhs: Array) {
rhs.forEach {
if let indexOfhit = lhs.firstIndex(of: $0) {
lhs.remove(at: indexOfhit)
}
}
}
static func -(lhs: Array, rhs: Array) -> Array {
return lhs.filter { return !rhs.contains($0) }
}
}
Remove elements using indexes array:
Array of Strings and indexes
let animals = ["cats", "dogs", "chimps", "moose", "squarrel", "cow"]
let indexAnimals = [0, 3, 4]
let arrayRemainingAnimals = animals
.enumerated()
.filter { !indexAnimals.contains($0.offset) }
.map { $0.element }
print(arrayRemainingAnimals)
//result - ["dogs", "chimps", "cow"]
Array of Integers and indexes
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
let indexesToRemove = [3, 5, 8, 12]
numbers = numbers
.enumerated()
.filter { !indexesToRemove.contains($0.offset) }
.map { $0.element }
print(numbers)
//result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
Remove elements using element value of another array
Arrays of integers
let arrayResult = numbers.filter { element in
return !indexesToRemove.contains(element)
}
print(arrayResult)
//result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
Arrays of strings
let arrayLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
let arrayRemoveLetters = ["a", "e", "g", "h"]
let arrayRemainingLetters = arrayLetters.filter {
!arrayRemoveLetters.contains($0)
}
print(arrayRemainingLetters)
//result - ["b", "c", "d", "f", "i"]