Use of unresolved identifier 'finalArray'? - arrays

var firstArray = ["1.","2.","3.","4."]
var secondArray = ["a","b","c"]
func combineTheArrays(array1: [Any], array2: [Any]) -> [Any] {
var finalArray = [Any]()
let maxIndex = array1.count >= array2.count ? array1.count : array2.count;
for i in 0...maxIndex{
if (array1.count > i){
finalArray.append(array1[i])
}
if (array2.count > i){
finalArray.append(array2[i])
}
} }
combineTheArrays(array1: firstArray, array2: secondArray)
print(finalArray)
I am trying to take two arrays with different/similar types and have it work through the function and combine into one single array. The ideal result of this func is to print:
finalArray = ["1.", "a", "2.", "b", "3.", "c", "4."]

You're very close! You just need to return finalArray at the end of your function definition, and then assign the result of the function call, so that you can then use it (such as in a print call):
let finalArray = combineTheArrays(array1: firstArray, array2: secondArray)
print(finalArray)
You should also use generics to ensure that you can handle any kind of elements, so long as their types are the same. Unlike returning Any, your result will be an array of the same type, which will be safer and easier to work with. Here is how I would improve this code:
func combineTheArrays<T>(array1: [T], array2: [T]) -> [T] {
let maxIndex = max(array1.count, array2.count);
var finalArray = [T]()
finalArray.reserveCapacity(array1.count + array2.count)
for i in 0..<maxIndex {
if i < array1.count { finalArray.append(array1[i]) }
if i < array2.count { finalArray.append(array2[i]) }
}
return finalArray
}
var firstArray = ["1.","2.","3.","4."]
var secondArray = ["a","b","c"]
let finalArray = combineTheArrays(array1: firstArray, array2: secondArray)
print(finalArray)

Related

I want to remove out Strings from an Array

this is my code
func filterString(array:[Any])-> [Int]{
return array.remove(String)
}
func filterString(array:[Any])-> [Any]{
var finalArr : [Any] = []
for i in array{
if i is String.Type == false{
finalArr.append(i)
}
}
return finalArr
}
A simple filter should be enough
var arr: [Any] = ["", "", 1, 2.5]
print(arr.filter({ $0 is Int }))
// print [1]
This will return an array of Int as you seem to search for in your code. But you can also filter on only removing strings, leaving rest intact:
var arr: [Any] = ["", "", 1, 2.5]
print(arr.filter({ !($0 is String) }))
// print [1, 2.5]
And with your function:
func filterString(array: [Any]) -> [Int]{
array.filter { $0 is Int } as? [Int] ?? []
}
Almost
var array : [Any] = [1, "one", 2, "two", 3, "three"]
array.removeAll(where: {$0 is String})
or with your function, consistently you have to remove everything which is not Int
func filterString(array: [Any]) -> [Int]{
var temp = array
temp.removeAll(where: {$0 is Int == false})
return temp as! [Int]
}
Another way is compactMap
func filterString(array: [Any]) -> [Int]{
return array.compactMap{$0 as? Int}
}

Filtering Dictionary with an array of random Ints to make a new dict

So I have this method to get an array of random ints between 1-9, a random number of times between 1 and 7.
let n = arc4random_uniform(7) + 1
var arr: [UInt32] = []
for _ in 0 ... n {
var temp = arc4random_uniform(9) + 1
while arr.contains(temp) {
temp = arc4random_uniform(9) + 1
}
print(temp)
arr.append(temp)
}
print(arr)
So that gets me an array like [1,4,2] or [5,7,3,4,6]. And I have a method to turn another array of strings into a enumerated dictionary.
var someArray: [String] = ["War", "Peanuts", "Cats", "Dogs", "Nova", "Bears", "Pigs", "Packers", "Mango", "Turkey"]
extension Collection {
var indexedDictionary: [Int: Element] {
return enumerated().reduce(into: [:]) { $0[$1.offset] = $1.element }
}
}
let dict1 = someArray.indexedDictionary
print(dict1)
giving me the indexed dictionary
[1:"War", 2:"Peanuts",..etc]
MY question is using the Ints of the random array how do I create a new dictionary that only includes those keys and their values?
So for example if arr = [3,1,5]
how do I get a new dictionary of
[3:"dogs", 1:"Peanuts",5:"Bears"].
This should do it:
let finalDict = dict1.filter { arr.contains($0.key) }
Update:
You can even go a step further and skip the whole strings to array mapping. So remove
extension Collection {
var indexedDictionary: [Int: Element] {
return enumerated().reduce(into: [:]) { $0[$1.offset] = $1.element }
}
}
let dict1 = someArray.indexedDictionary
print(dict1)
and just use this:
Swift 4:
let finalArray = someArray.enumerated().flatMap { arr.contains($0.offset) ? $0.element : nil }
Swift 4.1:
let finalArray = someArray.enumerated().compactMap { arr.contains($0.offset) ? $0.element : nil }
Update 2:
If you need a dictionary and not an array in the end use this:
Swift 4:
let finalDict = someArray.enumerated().flatMap { randomInts.contains($0.offset) ? ($0.offset, $0.element) : nil }.reduce(into: [:]) { $0[$1.0] = $1.1 }
Swift 4.1:
let finalDict = someArray.enumerated().compactMap { randomInts.contains($0.offset) ? ($0.offset, $0.element) : nil }.reduce(into: [:]) { $0[$1.0] = $1.1 }

Swift 2.1 Array Extension objectsAtIndexes

I'm trying to extend an array to return only objects at certain indexes. The map function seemed to be the best choice for me here.
extension Array {
func objectsAtIndexes(indexes: [Int]) -> [Element?]? {
let elements: [Element?] = indexes.map{ (idx) in
if idx < self.count {
return self[idx]
}
return nil
}.filter { $0 != nil }
return elements
}
}
let arr = ["1", "2", "3", "4", "5"]
let idx = [1,3,5]
let x = arr.objectsAtIndexes(idx) //returns: [{Some "2"}, {Some "4"}]
I'm getting a EXC_BAD_INSTRUCTION error when I try to cast the result to a string array:
let x = arr.objectsAtIndexes(idx) as? [String]
Is there any way I can return an array of non-optionals? I've tried to return [Element]? from the extension function.
This throws the same error.
The following code solves the problem for Swift2.1 using the flatmap function.
extension Array {
func objectsAtIndexes(indexes: [Int]) -> [Element] {
let elements: [Element] = indexes.map{ (idx) in
if idx < self.count {
return self[idx]
}
return nil
}.flatMap{ $0 }
return elements
}
}

How to reverse array in Swift without using ".reverse()"?

I have array and need to reverse it without Array.reverse method, only with a for loop.
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
Swift 3:
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames : [String] = Array(names.reversed())
print(reversedNames) // ["Asus", "Lenovo", "Sony", "Microsoft", "Apple"]
Here is #Abhinav 's answer translated to Swift 2.2 :
var names: [String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()
for arrayIndex in (names.count - 1).stride(through: 0, by: -1) {
reversedNames.append(names[arrayIndex])
}
Using this code shouldn't give you any errors or warnings about the use deprecated of C-style for-loops or the use of --.
Swift 3 - Current:
let names: [String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()
for arrayIndex in stride(from: names.count - 1, through: 0, by: -1) {
reversedNames.append(names[arrayIndex])
}
Alternatively, you could loop through normally and subtract each time:
let names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
let totalIndices = names.count - 1 // We get this value one time instead of once per iteration.
var reversedNames = [String]()
for arrayIndex in 0...totalIndices {
reversedNames.append(names[totalIndices - arrayIndex])
}
Do you really need a for loop? If not, you can use reduce.
I guess that this is the shortest way to achieve it without reversed() method (Swift 3.0.1):
["Apple", "Microsoft", "Sony", "Lenovo", "Asus"].reduce([],{ [$1] + $0 })
Only need to make (names.count/2) passes through the array. No need to declare temporary variable, when doing the swap...it's implicit.
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
let count = names.count
for i in 0..<count/2 {
(names[i],names[count - i - 1]) = (names[count - i - 1],names[i])
}
// Yields: ["Asus", "Lenovo", "Sony", "Microsoft", "Apple"]
There's also stride to generate a reversed index:
let names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversed = [String]()
for index in (names.count - 1).stride(to: -1, by: -1) {
reversed.append(names[index])
}
It also works well with map:
let reversed = (names.count - 1).stride(to: -1, by: -1).map { names[$0] }
Note: stride starts its index at 1, not at 0, contrary to other Swift sequences.
However, to anyone reading this in the future: use .reverse() instead to actually reverse an array, it's the intended way.
var names:[String] = [ "A", "B", "C", "D", "E","F","G"]
var c = names.count - 1
var i = 0
while i < c {
swap(&names[i++],&names[c--])
}
Cristik
while i < c {
swap(&names[i],&names[c]
i += 1
c -= 1
}
Here you go:
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()
for var arrayIndex = names.count - 1 ; arrayIndex >= 0 ; arrayIndex-- {
reversedNames.append(names[arrayIndex])
}
Ignoring checks for emptiness..
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()
for name in names {
reversedNames.insert((name), at:0)
}
print(reversedNames)
Here is the most simpler way.
let names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()
for name in names {
reversedNames.insert(name, at: 0)
}
Edited as generic
// Swap the first index with the last index.
// [1, 2, 3, 4, 5] -> pointer on one = array[0] and two = array.count - 1
// After first swap+loop increase the pointer one and decrease pointer two until
// conditional is not true.
func reverse<T>(with array: [T]) -> [T] {
var array = array
var first = 0
var last = array.count - 1
while first < last {
array.swapAt(first, last)
first += 1
last -= 1
}
return array
}
input-> [1, 2, 3, 4, 5] output ->[5, 4, 3, 2, 1]
input-> ["a", "b", "c", "d"] output->["d", "c", "b", "a"]
// Or a shorter version divide and conquer
func reversed<T>(with arr: [T]) -> [T] {
var arr = arr
(0..<arr.count / 2).forEach { i in
arr.swapAt(i, arr.count - i - 1)
}
return arr
}
The most efficient way is to swap the items at start- and endIndex and move the indices bidirectional to the middle. This is a generic version
extension Array {
mutating func upsideDown() {
if isEmpty { return }
var 👉 = startIndex
var 👈 = index(before: endIndex)
while 👉 < 👈 {
swapAt(👉, 👈)
formIndex(after: &👉)
formIndex(before: &👈)
}
}
}
Like this, maybe:
names = names.enumerate().map() { ($0.index, $0.element) }.sort() { $0.0 > $1.0 }.map() { $0.1 }
Oh, wait.. I have to use for loop, right? Then like this probably:
for (index, name) in names.enumerate().map({($0.index, $0.element)}).sort({$0.0 > $1.0}).map({$0.1}).enumerate() {
names[index] = name
}
Swift 5:
let names: [String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversenames: [String] = []
let count = names.count
for index in 0..<count {
reversenames.insert(names[count-index-1], at: index)
}
print(reversenames)
This will work with any sized array.
import Cocoa
var names:[String] = [ "A", "B", "C", "D", "E","F"]
var c = names.count - 1
for i in 0...(c/2-1) { swap(&names[i],&names[c-i]) }
print(names)
Here is how I did it and there is no warning for Swift 3
let names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [String]()
for name in names.enumerate() {
let newIndex = names.count - 1 - name.index
reversedNames.append(names[newIndex])
}
or just simply
reversedNames = names.reverse()
Here the code for swift 3
let array = ["IOS A", "IOS B", "IOS C"]
for item in array.reversed() {
print("Found \(item)")
}
func reverse(array: inout [String]) {
if array.isEmpty { return }
var f = array.startIndex
var l = array.index(before: array.endIndex)
while f < l {
swap(array: &array, f, l)
array.formIndex(after: &f)
array.formIndex(before: &l)
}
}
private func swap( array: inout [String], _ i: Int, _ j: Int) {
guard i != j else { return }
let tmp = array[i]
array[i] = array[j]
array[j] = tmp
}
Or you can write extension of course
var rArray : [Int] = [2,5,6,8,3,8,9,10]
var ReArray = [Int]()
var a : Int = 1
func reversed (_ array: [Int]) -> [Int] {
for i in array {
ReArray.append(array[array.count-a])
a += 1
}
rArray = ReArray
return rArray
}
reversed(rArray)
print(rArray)
var arr = [1, 2, 3, 4, 5] // Array we want to reverse
var reverse: [Int]! // Array where we store reversed values
reverse = arr
for i in 0...(arr.count - 1) {
reverse[i] = arr.last! // Adding last value of original array at reverse[0]
arr.removeLast() // removing last value & repeating above step.
}
print("Reverse : \(reverse!)")
A more simple way :)
Recently I had an interview and I was asked this question, how to reverse an array without using reversed(). Here is my solution below:
func reverseArray( givenArray:inout [Int]) -> [Int] {
var reversedArray = [Int]()
while givenArray.count > 0 {
reversedArray.append(givenArray.removeLast())
}
return reversedArray
}
var array = [1,2,3,4,5,6,7]
var reversed = reverseArray(givenArray: &array)
First, need to find the middle of array. This method is faster than the linear time O(n) and slower than the constant time O(1) complexity.
func reverse<T>(items: [T]) -> [T] {
var reversed = items
let count = items.count
let middle = count / 2
for i in stride(from: 0, to: middle, by: 1) {
let first = items[i]
let last = items[count - 1 - i]
reversed[i] = last
reversed[count - 1 - i] = first
}
return reversed
}
Do it like this for reversed sorting.
let unsortedArray: [String] = ["X", "B", "M", "P", "Z"]
// reverse sorting
let reversedArray = unsortedArray.sorted() {$0 > $1}
print(reversedArray) // ["Z", "X", "P", "M", "B"]
I like simple codes.
var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
var reversedNames = [""]
for name in names {
reversedNames.insert(name, at: 0)
}
print(reversedNames)
var names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
// 'while' loop
var index = 0
let totalIndices = names.count - 1
while index < names.count / 2 {
names.swapAt(index, totalIndices-index)
index += 1
}
// 'for' loop
for index in 0..<names.count/2 {
names.swapAt(index, names.count-index-1)
}
// output: "["Asus", "Lenovo", "Sony", "Microsoft", "Apple"]"
You can use the swift3 document:
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let reversedNames = names.sorted(by: >)
// reversedNames is equal to:
// ["Ewa", "Daniella", "Chris", "Barry", "Alex"]

Swift 3 - Function for Wrapping an Array

As I try to learn Swift 3, I am attempting to "Wrap an Array of Elements". In Swift 3 Playgrounds, I was able to implement code that wraps an array. My problem occurs when I try to create a function that implements my code.
If you take the following code and copy-paste it to a Swift 3 Playground then you will likely see what I am trying to do. Change the selectedElement and on the right you will see the correct newArray. You can interchange the different elements for the selectedElement and the newArray will change accordingly.
I noted one of my failed attempts at turning this into a function.
import UIKit
let myArray = ["a", "b", "c", "d", "e"]
let selectedElement = "a"
//func arrayWrapper(inputArray: Array<String>) -> Array<String> {
var oldArray = [String]()
var priorElements = [String]()
var newArray = [String]()
for element in myArray {
if element == selectedElement || oldArray.count > 0 {
oldArray.append(element)
} else {
priorElements.append(element)
}
newArray = oldArray + priorElements
}
//return newArray
//}
priorElements
oldArray
oldArray + priorElements
newArray
Your method works fine.
The only problem I see is that you are trying to access the variables created inside the function outside of the function scope.
//priorElements
//oldArray
//
//oldArray + priorElements
arrayWrapper(inputArray: myArray)
Well, your non-function solution to this problem takes two inputs - the array you want to wrap, and the element you want it to wrap at. Therefore, your function should have two parameters as well:
// note the second parameter
func arrayWrapper(inputArray: Array<String>, selectedElemented: String) -> Array<String> {
var oldArray = [String]()
var priorElements = [String]()
var newArray = [String]()
for element in myArray {
if element == selectedElement || oldArray.count > 0 {
oldArray.append(element)
} else {
priorElements.append(element)
}
newArray = oldArray + priorElements
}
return newArray
}
Here is a more general version of this function, as an extension of Array:
extension Array where Element : Equatable {
func wrap(around selectedElement: Element) -> Array<Element> {
var oldArray = [Element]()
var priorElements = [Element]()
var newArray = [Element]()
for element in self {
if element == selectedElement || oldArray.count > 0 {
oldArray.append(element)
} else {
priorElements.append(element)
}
newArray = oldArray + priorElements
}
return newArray
}
}
// usage
myArray.wrap(around: selectedElement)

Resources