Kotlin Array with named parameter equivalent of swift - arrays

Hi i'am new to Kotlin and i would like to do an array with named parameter. In Swift i can do :
let analytics = ["organization_login": "toto", "organization_name": "titi", "lead_email": "tata"]
The type is : [String: String]
I Looked all Array and Arraylist in kotlin but i couln't find the equivalent.
What i want it's to be able to give parameter name for my array.
Edit
I misunderstood the swift syntaxe, it's seem that it's only a dictonary, so we just have to use map.

The reason is that [String: String] is not an array, it's a Dictionary.
The equivalent of Dictionary in Kotlin is Map.
Maps can be created like so:
val map = mapOf("string_one" to "string_2", "string_3" to "string_4")
or, if you want to mutate it:
val mutableMap = mutableMapOf("string_one" to "string_2")

You need to use Map as
val map = mapOf("organization_login" to "toto", "organization_name" to "titi")
// immutable map
you can also use sortedMapOf, hashMapOf linkedMapOf etc for different algo based storage.
Note: If you want to add more elements later then make sure to use mutableMapOf

Related

Storing arrays of string persistently in SwiftUI using AppStorage

I'm trying to store an array of string in user defaults using the AppStorage property wrapper like this:
#AppStorage("History") var history: [String] = ["End of history"]
however I get the error No exact matches in call to initializer
Is this a limitation of AppStorage because UserDefaults can store arrays if I'm not wrong? What is a workaround I can use?

is it good practice to Any element type in swift?

is it good practice to Any element type in swift?
For example
let arrayObject = [Any]
or
let arrayObject = [[String: String]]
Swift's strong type system encourages you to be always as type specific as possible. Please don't use Any as a don't-care type.
I'd recommend to consider this priority list (high to low)
If the type is known and homogenous, use the static type.
For example in a JSON dictionary if all values are String use always [String:String] rather than [String:Any].
If the type is heterogenous – for example objects in an array – and contains only a few known types use a common protocol.
Try to use generics.
Use Any
When you know your Array element's type you can avoid using Any and use the direct data type.
For example: If you are holding array of String, you can directly define String type as like below.
var arrayObject = [String]()
If you are holding an unknown type of objects in array or multiple types of objects in array, you can go with Any.
For example: If you are holding String and NSNumber in same array, you can define Any as type of array element as like below.
var arrayObject = [Any]()
arrayObject.append("Hundred")
arrayObject.append(NSNumber(value: 100))
let str = arrayObject[0] as! String
let number = arrayObject[1] as! NSNumber

Store a NSMutableArray of NSManagedObject arrays in core data | swift 2

I'm somewhat new to swift, and I'm not a master when it comes to arrays
I'm trying to find a way where I can store an array of NSManagedObjects into core data.
Here's an example:
let array = [["a", "b", "c",],["1", "2", "3",],["apple", "orange", "pear"]]
This is the way I did it:
I have several arrays of NSManagedObjects that I added to a NSMutableArray
Then I stored it as transformable data. Like this.
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity_entry = NSEntityDescription.entityForName("EntityForArrays", inManagedObjectContext: managedContext)
let new_value = NSManagedObject(entity: entity_entry!, insertIntoManagedObjectContext: managedContext)
new_value.setValue(array, forKey: "attribute")
So am I going down the right path by using a NSMutableArray or should I try something new?
Also if can store this array, how can I receive it?
Whether it's the right path depends on how you need to use that array. It's convenient to put it all into one transformable attribute, but you can't use predicates to fetch objects based on their array contents.
Saving the array like that should work. To get it back, fetch objects using NSFetchRequest and then look up the array value using valueForKey().

How would you create a multidimensional array with n dimensions in Swift?

For instance, asume
var hierarchicalFileSystem: [[String]] = []
This allows one to support one layer of folders, but there appears to be no way to create an array in Swift like the one above but with an undefined number of nested String arrays.
Am I missing something here?
An array of arrays (of arrays of arrays...) of strings doesn't really make much sense to represent a file system.
What I'd instead recommend is making a class or struct to represent objects in the file system. Perhaps something like this:
struct FileSystemObject {
let name: String
let extension: String?
let isFolder: Bool
let contents: [FileSystemObject]?
}
Something like this let's us represent a file system quite nicely.
let fileSystem = [FileSystemObject]()
So, your fileSystem variable here is an array of FileSystemObjects and it represents the root. Each object within the root has its own set of details (its name, its file extension if it has one, and whether or not its a folder), and if it's a folder it has a non-nil contents property, and if it's a non-empty folder, that contents array of FileSystemObjects contains more file system objects (some of which are folders of course, which contain contents themselves).
What you can perhaps do is create an array with AnyObject and add new depths as you need it
var fileSystem: [AnyObject] = []
This would be a very bad way of representing a file system however and you should really go with some kind of tree structure like
struct Node {
children: [Node]?
parent: Node?
name: String
}
Swift is type-safe language. You have to declare type of your variable, or set it to AnyObject, but please don't. So, answering your question: yes it's possible:
var array: [AnyObject] = [[[1,2,3], [1,2,3]], [[1,2,3],[1,2,3]]]
But this is awful. Try to figure out better representation for your problem. Maybe custom structures.
you can have as much dimensional array as you want. is it a good idea? i don't think ...
var threeDArray: Array<Array<Array<String>>> = []
let oneDArray = ["1","2","3"]
let twoDArray1: Array<Array<String>> = [oneDArray, oneDArray, oneDArray, oneDArray, oneDArray]
let twoDArray2 = twoDArray1 + [["4","5","6"],["7","8","9"]]
threeDArray.append(twoDArray1)
threeDArray.append(twoDArray2)
let arr = [threeDArray,threeDArray,threeDArray]
print(arr.dynamicType) // Array<Array<Array<Array<String>>>>

Encoding toJSON from Arrays and Dictionaries in Swift

I am trying to create a JSON file from an array that i make inside my application with swift.
I need to encode to JSON an 'Array' because i am creating dictionaries and arrays before and i just combine them to that array.
In my code i have :
var order = Array<Any>()
var orderArray = Array<Dictionary<String, String>>()
var dict = Dictionary<String, Any>()
and i put first the orderArray in dict and then the dict inside order.
The output if i print it is correct and it works. The problem is when i try to encode the order(array) into JSON. Then i get the following error:
Cannot invoke 'dataWithJSONObject' with an argument list of type '(Array'
This is the code i use:
let json = NSJSONSerialization.dataWithJSONObject(order, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
If i try the same code with the orderArray for example it works.
The 'Any' i think does the mess. But how could i resolve this?
Thank you.

Resources