Add Array Multiple Objects to [Any] in Swift 3 [duplicate] - swift

This question already has answers here:
Swift 3 unable to append array of objects, which conform to a protocol, to a collection of that protocol
(2 answers)
Closed 6 years ago.
I'm trying to understand the best way to add multiple objects of different types to an [Any] array. This doesn't work in a playground in Swift 3, unless I explicitly cast the arrays and the objects in the arrays to Any.
var anyArray: [Any] = []
let strings = ["sup", "cool"]
let numbers = [5, 3]
anyArray += strings
anyArray += numbers
anyArray
It fails with the message - Cannot convert value of type '[Any]' to expected argument type 'inout _'

var arr = [Any]()
let arr1:[Any] = [2,3,4]
let arr2:[Any] = ["32","31"]
arr += arr1
arr += arr2
print(arr)

I think this is another case of useless error messages from Swift's compiler. The real issue is that AnyObject means any object (reference type); structs -- which both Int and String are -- don't count because they are value types. If you want to refer to any type at all, use Any.

Related

How to create an array by multiplying another array in a functional way? [duplicate]

This question already has answers here:
Repeating array in Swift
(4 answers)
Closed 5 years ago.
I'd like to create an array that contains elements from another array multiplied by some Int value.
Example:
the following code
let arr = [1,2,3]
let multiplier = 3
print(function(arr, multiplier))
should return
[1,2,3,1,2,3,1,2,3]
I know how to make it using nested for loops, but I'm looking for some nifty functional way. I was thinking about map() function, but it iterates over each element of a given array, which is not my use case I suppose.
Main idea:
Create array of arrays,
flatMap to one-dimensional array.
Example:
let arr = [1, 2, 3]
let multiplayer = 3
print(Array(repeating: arr, count: multiplayer).flatMap({ $0 }))

Cannot assign sorted array to a variable in Swift [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to sort one array and assign it to the other. Both arrays are identically defined like so:
var arrayA: [String: [Int]] = [:]
var sortedArrayA:[String: [Int]] = [:]
sortedArrayA = arrayA.sort{ $0.0 < $1.0 } // error on this line.
I am gettin this error:
Cannot assign value of type [(String, [Int])] to type [String : [Int]]
What I'm trying to achieve is to make this dictionary:
["c" : [1,2,3], "a" : [2,3,3], "b" : [4,4,4]]
sorted like this:
["a" : [2,3,3], "b" : [4,4,4], "c" : [1,2,3]]
If it makes sence.
Yeah, I know closures in Swift are cool. But they are not cool enough to infer that you want to sort an array from this code:
var arrayA: [Int] = []
var sortedArrayA:[Int] = []
sortedArrayA = arrayA{ $0 < $1 }
And your code is even worse! You didn't even declare arrays! What you declared are dictionaries which are supposed to not be sorted!
Anyway, just learn the syntax of arrays: it's a pair of square brackets surrounding the type of array you want. So an array of Ints will be [Int] and an array of Strings will be [String].
Got it? Cool.
"But I only have dictionaries, though..." you said sadly. If you only have dictionaries, you can either sort its keys or values. I think you probably need to sort the values.
let values = someDictionary.values // if you want to sort keys, use .keys instead
Now you need to actually call the sort method in order to sort. Just writing a closure is not going to work.
let sortedValues = values.sort(<)
You can do this with any arrays of course!
let array = [3, 2, 1]
let sortedArray = array.sort(<)
In your question you say that you use array but actually you are using dictionaries. And your syntax for this is wrong. you can declare empty dictionary like this: var dictionary: [String:Int] = (). But to answer your real question you can achieve it like this:
let arrayA = ["c" : [1,2,3], "a" : [2,3,3], "b" : [4,4,4]]
let sortedDict = arrayA.sort { $0.0 < $1.0 }
print("\(sortedDict)")
Try and figure out the array sorting in Playground, in swift you can just use .sort() to sort the array. For example, for array of integers:
var array = [Int]() //initial empty array
array = [2, 1, 4, 3]
array = array.sort() // array is now sorted

How to create an array with incremented values in Swift? [duplicate]

This question already has answers here:
Is there a way to instantly generate an array filled with a range of values in Swift?
(4 answers)
Closed 7 years ago.
I know that I can create an array with repeated values in Swift with:
var myArray = [Int](count: 5, repeatedValue: 0)
But is there a way to create an array with incremented values such as [0, 1, 2, 3, 4] other than to do a loop such as
var myArray = [Int]()
for i in 0 ... 4 {
myArray.append(i)
}
I know that code is pretty straightforward, readable, and bulletproof, but it feels like I should be able pass some function in some way to the array as it's created to provided the incremented values. It might not be worth the cost in readability or computationally more efficient, but I'm curious nonetheless.
Use the ... notation / operator:
let arr1 = 0...4
That gets you a Range, which you can easily turn into a "regular" Array:
let arr2 = Array(0...4)

Multi-Dimensional Arrays of Different Types in Swift

I can easily write a multi-dimensional array in Swift when all the dimensions are of the same type, for example:
var totalTime : [[Int]]
How would I get the first dimension to be String and the second dimension Int?
I would recommend using an array of tuples instead. What you want could be accomplished using an array of type Any, but it is not a good idea.
Instead, your array should be [[(String, Int)]]. This would also be more compact than what you want to do.
var myArray: [[(String, Int)]] = []

Immutable Dictionary value change

Can we change any pair value in let type Dictionary in Swift Langauage.
like :
let arr2 : AnyObject[] = [1, "23", "hello"]
arr2[1] = 23
arr2 // output: [1,23,"hello"]
let arr1 :Dictionary<Int,AnyObject> = [1: "One" , 2 : 2]
arr1[2] = 4 // not posible error
arr1
In Case of Immutable Array we can change its value like above but not in case of Immutable
Dictionary. Why?
This is taken from The Swift Programming Language book:
For dictionaries, immutability also means that you cannot replace the
value for an existing key in the dictionary. An immutable dictionary’s
contents cannot be changed once they are set.
Immutability has a slightly different meaning for arrays, however. You
are still not allowed to perform any action that has the potential to
change the size of an immutable array, but you are allowed to set a
new value for an existing index in the array.
Array declared with let has only immutable length. Contents can still be changed.
Dictionary declared with let is completely immutable, you can't change contents of it. If you want, you must use var instead of let.
Swift has changed a lot since then.
Array and Dictionary are value types. When declared with let, they cannot change any more. Especially, one cannot re-assign them, or the elements in them.
But if the type of the elements is reference type, you can change the properties of the elements in Array or Dictionary.
Here is a sample.(run in Xcode6 beta-6)
class Point {
var x = 0
var y = 0
}
let valueArr: [Int] = [1, 2, 3, 4]
let refArr: [Point] = [Point(), Point()]
valueArr[0] = -1 // error
refArr[0] = Point() // error
refArr[0].x = 1
let valueDict: [Int : Int] = [1: 1, 2: 2]
let refDict: [Int: Point] = [1: Point(), 2: Point()]
valueDict[1] = -1 //error
refDict[1] = Point() //error
refDict[1]!.x = -1