Create a mutable array of arrays each containing a dictionary in swift? - swift

I am trying to declare a variable that stores an array of arrays. Each array then contains a Dictionary object. I tried a bunch of different possible declarations but the compiler is not happy with any of them.
Any suggestion?
Thanks
Clarification on what I needed:
An array that contains arrays where each of them contains dictionaries.

You Said
Each array then contains a Dictionary object
that mean that each array will have a single Dictionary so why do you need that extra Array
anyway the following code declare an Array that contain Dictionaries(The code assume that eventually your dictionary will contain strings but you can change that to any type you want)
var myObj = Array<Dictionary<String,String>>()
var dic1:Dictionary<String,String> = Dictionary<String,String>()
dic1["A"] = "Alpha :A"
dic1["B"] = "Alpha :B"
var dic2:Dictionary<String,String> = Dictionary<String,String>()
dic2["C"] = "Alpha :C"
dic2["D"] = "Alpha :D"
myObj.append(dic1)
myObj.append(dic2)
if you need an array containing arrays of dictionaries it will be almost the same
var myObj = Array<Array<Dictionary<String,String>>>()

Related

Convert Realm list of Strings to Array of Strings in Swift

I'm just starting up with RealmSwift, and I'm trying to store an array of Strings in Realm. It doesn't work, so now I'm using List<String>() as an alternative. However, how do I convert these Realm Lists back to [String] again? And if I can't do that, are there any alternatives?
Thanks
However, how do I convert these Realm Lists back to [String] again
You can simply cast List to Array, because List has Sequence Support:
let list = List<String>()
let array = Array(list)
Bear in mind that by converting to an array you'll lose the 'dynamic' quality of a Realm collection (i.e. you'll receive a static array, whereas keeping the original List will provide automatic updating should the source change). But you can create an array by using an extension, e.g.:-
extension RealmCollection
{
func toArray<T>() ->[T]
{
return self.compactMap{$0 as? T}
}
}
Then use:-
let stringList = object.strings.toArray()
Where object is the realm object, and strings is your field.
Here are the details. how to assign an array in the realm list model.
jim.dogs.append(objectsIn: someDogs)

Swift - insert new array at the beginning of another array [duplicate]

Suppose I have an array, for example:
var myArray = ["Steve", "Bill", "Linus", "Bret"]
And later I want to push/append an element to the end of said array, to get:
["Steve", "Bill", "Linus", "Bret", "Tim"]
What method should I use?
And what about the case where I want to add an element to the front of the array? Is there a constant time unshift?
As of Swift 3 / 4 / 5, this is done as follows.
To add a new element to the end of an Array.
anArray.append("This String")
To append a different Array to the end of your Array.
anArray += ["Moar", "Strings"]
anArray.append(contentsOf: ["Moar", "Strings"])
To insert a new element into your Array.
anArray.insert("This String", at: 0)
To insert the contents of a different Array into your Array.
anArray.insert(contentsOf: ["Moar", "Strings"], at: 0)
More information can be found in the "Collection Types" chapter of "The Swift Programming Language", starting on page 110.
You can also pass in a variable and/or object if you wanted to.
var str1:String = "John"
var str2:String = "Bob"
var myArray = ["Steve", "Bill", "Linus", "Bret"]
//add to the end of the array with append
myArray.append(str1)
myArray.append(str2)
To add them to the front:
//use 'insert' instead of append
myArray.insert(str1, atIndex:0)
myArray.insert(str2, atIndex:0)
//Swift 3
myArray.insert(str1, at: 0)
myArray.insert(str2, at: 0)
As others have already stated, you can no longer use '+=' as of xCode 6.1
To add to the end, use the += operator:
myArray += ["Craig"]
myArray += ["Jony", "Eddy"]
That operator is generally equivalent to the append(contentsOf:) method. (And in really old Swift versions, could append single elements, not just other collections of the same element type.)
There's also insert(_:at:) for inserting at any index.
If, say, you'd like a convenience function for inserting at the beginning, you could add it to the Array class with an extension.
Use += and + operators :
extension Array {
}
func += <V> (inout left: [V], right: V) {
left.append(right)
}
func + <V>(left: Array<V>, right: V) -> Array<V>
{
var map = Array<V>()
for (v) in left {
map.append(v)
}
map.append(right)
return map
}
then use :
var list = [AnyObject]()
list += "hello"
list += ["hello", "world!"]
var list2 = list + "anything"
Here is a small extension if you wish to insert at the beginning of the array without loosing the item at the first position
extension Array{
mutating func appendAtBeginning(newItem : Element){
let copy = self
self = []
self.append(newItem)
self.appendContentsOf(copy)
}
}
In Swift 4.1 and Xcode 9.4.1
We can add objects to Array basically in Two ways
let stringOne = "One"
let strigTwo = "Two"
let stringThree = "Three"
var array:[String] = []//If your array is string type
Type 1)
//To append elements at the end
array.append(stringOne)
array.append(stringThree)
Type 2)
//To add elements at specific index
array.insert(strigTwo, at: 1)
If you want to add two arrays
var array1 = [1,2,3,4,5]
let array2 = [6,7,8,9]
let array3 = array1+array2
print(array3)
array1.append(contentsOf: array2)
print(array1)
Use Deque instead of Array
The main benefit of Deque over Array is that it supports efficient insertions and removals at both ends.
https://swift.org/blog/swift-collections/
var names:Deque = ["Steve", "Bill", "Linus", "Bret"]
Add 'Tim' at the end of names
names.append("Tim")
Add 'Tim' at the begining of names
names.prepend("John")
Remove the first element of names
names.popFirst() // "John"
Remove the last element of names
names.popLast() // "Tim"
From page 143 of The Swift Programming Language:
You can add a new item to the end of an array by calling the array’s append method
Alternatively, add a new item to the end of an array with the addition assignment operator (+=)
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l
To add to the solutions suggesting append, it's useful to know that this is an amortised constant time operation in many cases:
Complexity: Amortized O(1) unless self's storage is shared with another live array; O(count) if self does not wrap a bridged NSArray; otherwise the efficiency is unspecified.
I'm looking for a cons like operator for Swift. It should return a new immutable array with the element tacked on the end, in constant time, without changing the original array. I've not yet found a standard function that does this. I'll try to remember to report back if I find one!
You could use
Myarray.insert("Data #\(index)", atIndex: index)
If you want to append unique object, you can expand Array struct
extension Array where Element: Equatable {
mutating func appendUniqueObject(object: Generator.Element) {
if contains(object) == false {
append(object)
}
}
}
If the array is NSArray you can use the adding function to add any object at the end of the array, like this:
Swift 4.2
var myArray: NSArray = []
let firstElement: String = "First element"
let secondElement: String = "Second element"
// Process to add the elements to the array
myArray.adding(firstElement)
myArray.adding(secondElement)
Result:
print(myArray)
// ["First element", "Second element"]
That is a very simple way, regards!
In Swift 4.2:
You can use
myArray.append("Tim") //To add "Tim" into array
or
myArray.insert("Tim", at: 0) //Change 0 with specific location
Example: students = ["Ben" , "Ivy" , "Jordell"]
1) To add single elements to the end of an array, use the append(_:)
students.append(\ "Maxime" )
2) Add multiple elements at the same time by passing another array or a sequence of any kind to the append(contentsOf:) method
students.append(contentsOf: ["Shakia" , "William"])
3) To add new elements in the middle of an array by using the insert(_:at:) method for single elements
students.insert("Liam" , at:2 )
4) Using insert(contentsOf:at:) to insert multiple elements from another collection or array literal
students.insert(['Tim','TIM' at: 2 )
Swift 5.3, I believe.
The normal array wasvar myArray = ["Steve", "Bill", "Linus", "Bret"]
and you want to add "Tim" to the array, then you can use myArray.insert("Tim", at=*index*)so if you want to add it at the back of the array, then you can use myArray.append("Tim", at: 3)

how to add multiple key value pairs to dictionary Swift

okay, i'm trying to have the user add a key and value pair to a dictionary i created and have it show up in a table view. i do that just fine but i cant seem to figure out how to add another pair. when i go to add another it replaces the last one. id really like to have multiple pairs. can someone help please?
heres my code:
//declaring the dictionary
var cart = [String:String]()
//attempting to add to dictionary
cart[pizzaNameLabel.text!] = formatter.stringFromNumber(total)
This is how dictionary works:
In computer science, an associative array, map, symbol table, or
dictionary is an abstract data type composed of a collection of (key,
value) pairs, such that each possible key appears at most once in the
collection.
So
var cart = [String:String]()
cart["key"] = "one"
cart["key"] = "two"
print(cart)
will print only "key" - "two" part. It seems that you may need an array of tuples instead:
var cart = [(String, String)]()
cart.append(("key", "one"))
cart.append(("key", "two"))
print(cart)
will print both pairs.
From Swift 5.0, you can use KeyValuePairs like ordered dictionary type with multiple keys.
See this Apple Document of KeyValuePairs. ;)
let recordTimes: KeyValuePairs = ["Florence Griffith-Joyner": 10.49,
"Evelyn Ashford": 10.76,
"Evelyn Ashford": 10.79,
"Marlies Gohr": 10.81]
print(recordTimes.first!)

Create a dictionary in a loop in Swift

I have a variable set of objects that I need to place in a dictionary. I'm trying to add them to the dictionary in a for loop but from what I'm understanding dictionaries are immutable so they need to be declared immediately. How do I create a dictionary list of items that are not predetermined?
var newItems = [:]
for item in self.items{
newItems["\(item.key)"]["name"] = "A new item"
}
does not use the second value
var newItems : [String:String] = [:]
for i in 1..10{
newItems[i.description] = "A new item"
}
for more information https://www.weheartswift.com/dictionaries/
The problem with your original code is that dictionaries only have one key, so this construct newItems["\(item.key)"]["name"] is syntactically incorrect. If you had a fixed number of properties you could use a struct and put that in a dictionary. As you posed the question, though, you need to create a dictionary where the stored elements themselves are dictionaries. So, although I didn't actually put this into Xcode, it's a template for what you need to do:
var newItems = [:[:]]()
for item in self.items {
var itemDict = [:]()
for prop in whereeveryourpropertiescomefrom {
itemDict[prop] = valueforthisproperty
}
newItems["\(item.key)"] = itemDict
}
Of course, if your properties were initially stored in a dictionary unique to this item (equivalent of the inner loop), just store it directly into newItems.
Then, you could reference things as
let value = newItems["\(item.key)"]?.["property key"]
Notice the dictionary retrieval returns an optional you have to deal with.
The solution was when initializing the dictionary to create another dictionary
var newItems: [String:[String:AnyObject]]()

Set<NSObject>' does not have a member named 'allObjects'

With the original swift I could turn an NSSet (e.g. of Strings) into a typed array with the following syntax:
var stringArray = exampleSet.allObjects as [String]
With the new update I am getting the above error. What is the best way now to convert the Set into an array?
It looks as if your exampleSet is not an NSSet but a native
Swift Set which was introduced with Swift 1.2 (compare https://stackoverflow.com/a/28426765/1187415).
In that case you can convert it to an array simply with
let array = Array(exampleSet)
Looks like 'set' is a keyword. Try using a different variable name