How can create assoc 3D Array of Array? - swift

I tried create Array 3D but i still don't know how to create one ?
var array = [
"10001": [
"last_index": 0, //Int
"conteiner": [
"id_from": 321, // Int
"val2": "string text" // String
]
]
]

This works for me in Swift 2.0:
let array : [String : [String : Any]] = [
"10001": [
"last_index": 0, //Int
"conteiner": [
"id_from": 321 as Any, // Int
"val2": "string text" as Any // String
]
]
]
array["10001"]?["last_index"] // 0

Related

How to remove multiple items from a swift array?

For example i have an array
var array = [1, 2, 3, 4]
I want to remove item at index 1 then at index 3 "let it be in a for loop".
But removing the item at index 1 will move the item at index 3 to index 2, thus messing up the second removal.
Any suggestions ?
Given your array
var numbers = [1, 2, 3, 4]
and a Set of indexes you want to remove
let indexesToRemove: Set = [1, 3]
You want to remove the values "2" and "4".
Just write
numbers = numbers
.enumerated()
.filter { !indexesToRemove.contains($0.offset) }
.map { $0.element }
Result
print(numbers) // [1, 3]
It's simple. delete items from the end.
First delete 3 and after that delete 1
Swift 3: Use swift closure to perform the same operation.
If your array is like
var numbers = [0, 1, 2, 3, 4, 5]
and indexes you want to remove
let indexesToBeRemoved: Set = [2, 4]
numbers = numbers
.enumerated()
.filter { !indexesToRemove.contains($0.offset) }
.map { $0.element }
and result
print(numbers) // [0, 1, 3, 5]
Swift 3:
Here is same operation with JSON Object (dictionary)
var arrayString = [
[ "char" : "Z" ],
[ "char" : "Y" ],
[ "char" : "X" ],
[ "char" : "W" ],
[ "char" : "V" ],
[ "char" : "U" ],
[ "char" : "T" ],
[ "char" : "S" ]
]
let arrayIndex = [2, 3, 5]
arrayString = arrayString.enumerated()
.filter { !arrayIndex.contains($0.0 + 1) }
.map { $0.1 }
print(arrayString)
[["char": "Z"], ["char": "W"], ["char": "U"], ["name": "T"], ["name":
"S"]]

How do I use JSON arrays with Alamofire parameters?

I'm having a bit of trouble structuring my parameters so that our server API would be able to read it as valid JSON.
Alamofire uses parameters like this in swift language
let parameters : [String: AnyObject] =
[
"string": str
"params": HOW I INSERT A VALID JSON ARRAY HERE
]
The problem is that AnyObject does not seem to accept JSON so how would I send / create a structure like this with swift?
{
"string": str, "params" : [
{
"param1" : "something",
"param2" : 1,
"param3" : 2,
"param" : false
},
{
"param1" : "something",
"param2" : 1,
"param3" : 2,
"param" : false
}]
}
Taken from Alamofire's GitHub page:
let parameters = [
"foo": [1,2,3],
"bar": [
"baz": "qux"
]
]
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON)
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
EDIT: And from your example:
let parameters = [
"string": "str",
"params": [[
"param1" : "something",
"param2" : 1,
"param3" : 2,
"param" : false
],[
"param1" : "something",
"param2" : 1,
"param3" : 2,
"param" : false
]
]
]
Solved this myself. I can just do
parameters =
[
"params": array
]
Where array is Dictionary (String, AnyObject). The problem I initially had with this solution was that you can't insert booleans into this kind of dictionary, they will just be converted into integers. But apparently alamofire JSON encoding (I think) sends them as true/false values nevertheless.
In case, there is a need to pass array directly as a parameter for a alamofire request, the following method worked for me.
source: https://github.com/Alamofire/Alamofire/issues/1508
let headers = NetworkManager.sharedInstance.headers
var urlRequest = URLRequest(url: URL(string: (ServerURL + Api))!)
urlRequest.httpMethod = "post"
urlRequest.allHTTPHeaderFields = headers
let jsonArrayencoding = JSONDocumentArrayEncoding(array: documents)
let jsonAryEncodedRequest = try? jsonArrayencoding.encode(urlRequest, with: nil)
var request: Alamofire.DataRequest? = customAlamofireManager.request(jsonAryEncodedRequest!)
request?.validate{request, response, data in
return .success
}
.responseJSON {
You need to create a NSArray object for array parameters.
var yourParameters = [
"String": "a string",
"Int": 1,
"Array": NSArray(
array: [
"a", "b", "c"
])
]
Swift 2.2 and using SwiftyJSON.swift
You can use like this.
var arrayList : [String: AnyObject]//one item of array
var list: [JSON] = []//data array
for i in 0..<10//loop if you need
{
arrayList = [
"param1":"",
"param1":"",
"param2":["","",""]
]
list.append(JSON(arrayList))//append to your list
}
//params
let params: [String : AnyObject]=[
"Id":"3456291",
"List":"\(list)"//set
]
if you are using SwiftyJSON, you can write like this
let array = ["2010-12-13T5:03:20","2010-12-13T5:03:20"]
let paramsJSON = JSON(array)
var arrString = paramsJSON.rawString(NSUTF8StringEncoding)
Using Swift 5
You can use like this.
var authParams:[String:Any] = [:]
var authParamsObject:[String:Any] = [:]
authParamsObject["is_urgent"] = data_any
authParamsObject["body"] = data_any
authParams = ["note_set" : authParamsObject]
Json Result :
{
"note_set":
{
"is_urgent": true,
"body": "string"
}
}

Searching in Array of Dictionaries

I'm trying to search values in array of dictionaries which I get from JSON. I have a tableViewController with UISearchResultsUpdating. I found an example with array of Strings:
func updateSearchResultsForSearchController(searchController: UISearchController)
{
filteredTableData.removeAll(keepCapacity: false)
let searchPredicate = NSPredicate(format: "SELF contains[c] %#", searchController.searchBar.text)
let array = tableData.filteredArrayUsingPredicate(searchPredicate)
filteredTableData = array as! [String]
self.tableView.reloadData()
}
And I really don't know how to made search in array like this:
(
{
id = 3;
name = TestNewYork;
},
{
id = 2;
name = TestLA;
},
{
id = 1;
name = TestWashington;
}
)
my tableData = [] and filteredTableData must be an array too
Please, help!
You can use a simple filter function to do this...
tableData : [[String : String]] = ... // your JSON array of String, String dictionaries...
filteredTableData = tableData.filter{
dictionary in
return dictionary["name"] == filterString
}
Something like that anyway, not written Swift for a while.
You can wrap it in a function too...
func filter(array : [[String : String]], byString filterString : String) -> [[String : String]] {
return array.filter{
dictionary in
return dictionary["name"] == filterString
}
}
Or something. Not checked the code yet. Will be back if it doesn't work.
Checked in Playground and this works...
UPDATE
Changed to this...
let data = [
[
"id" : 3,
"name" : "a"
],
[
"id" : 4,
"name" : "b"
],
[
"id" : 5,
"name" : "c"
]
]
let filteredData = data.filter{
return $0["name"] == "b"
}
And it works. Just can't work out how to wrap in a function.
If you want to match the beginning of words...
let data = [
[
"id" : 3,
"name" : "Hello"
],
[
"id" : 4,
"name" : "Goodbye"
],
[
"id" : 5,
"name" : "Everybody"
]
]
let filteredData = data.filter{
let string = $0["name"] as! String
return string.hasPrefix("Goo")
}
If you want a contains you just need to do a find in the string.
Again, I'm not lying here. I'm running it in a Playground to check...
For a contains search you can do this...
let filteredData = data.filter{
let string = $0["name"] as! String
return string.rangeOfString("db") != nil
}

how to add json object to dictionary

when i create output with Alamofire using SwiftyJSON
Alamofire.request(.POST, "http://localhost:8080/ws/automobile/global/auction/latest/venues").responseJSON() {
(request, response, jsonData, error) in
var venues = JSON(jsonData!)
println(venues)
}
it appear like this in console
{
"C2058" : [
"LAA Okayama"
],
"C2062" : [
"NAA Osaka"
],
"C2035" : [
"JU Ibaraki"
],
"C2526" : [
"SMAP Fukuoka Nyusatsu"
],
"C2530" : [
"SMAP Tokyo Nyusatsu"
],
"C2074" : [
"TAA Tohoku"
],
"C2008" : [
"BCN"
],
"C2012" : [
"CAA Tokyo"
],
"C2503" : [
"L-Up PTokyoNyusatsu"
],
"C2047" : [
"JU Shizuoka"
],
"C2051" : [
"JU Yamaguchi"
],
"C2086" : [
"USS Saitama"
]
}
I want to add this to my new dictionary to use in UIPickerView,any suggestion how to do it.I am newbie to swift,code answer is really appreciated.Thank you.
What i Really want it dictionary like this
["C2047":"L-Up PTokyoNyusatsu","C2086":"USS Saitama".......]
Please help!!!
Don't know whether this is what you want:
var result = [String:String]()
let d = json.dictionaryValue
for (k, v) in d {
result[k] = v.arrayValue[0].stringValue
}
println(result)
From the example you've given:
"C2058" : [
"LAA Okayama"
],
"C2062" : [
"NAA Osaka"
],
"C2035" : [
"JU Ibaraki"
]
Those "C2058","C2062" are the key of Dictionary. And ["LAA Okayama"] is a String inside NSArray.
So, if you want to get the String inside NSArray. First, use the key to get value in Dictionary. Then, use NSArray to get the String.
it would like this:
var dict:NSDictionary=jsonData as Dictionary
var arr=dict["C2058"] as NSArray
and
println(arr[0]) //you'll see LAA Okayama

NSPredicate Filtered childs in array

Good day, I'm using new language Apple Swift and using the NSArray:
[
{
"Section" : "Title1",
"Items" :
[
{"Nr" : "101"},
{"Nr" : "201"},
{"Nr" : "301"},
{"Nr" : "401"}
]
},
{
"Section" : "Title2",
"Items" :
[
{"Nr" : "102"},
{"Nr" : "202"},
{"Nr" : "302"}
]
},
{
"Section" : "Title3",
"Items" :
[
{"Nr" : "1102"},
{"Nr" : "2102"},
{"Nr" : "3102"}
]
}
]
I want to use search, and display only content what is found
As I understand I have to use the "filteredArrayUsingPredicate" and NSPredicate in swift, so my sample is:
var arr:NSArray = [...] // My array sample goes here
var pre:NSPredicate = NSPredicate(format: "ANY Items.Nr BEGINSWITH[c] %#", argumentArray: ["20"]) // We a going to search "20" in /Items/Nr
var result:NSArray = arr.filteredArrayUsingPredicate(pre)
This is working correct but result is not what I need:
result =
[
{
"Section" : "Title1",
"Items" :
[
{"Nr" : "101"},
{"Nr" : "201"},
{"Nr" : "301"},
{"Nr" : "401"}
]
},
{
"Section" : "Title2",
"Items" :
[
{"Nr" : "102"},
{"Nr" : "202"},
{"Nr" : "302"}
]
}
]
It is display me all section what is contains Imtes with Nr started with "20"
And my question is how to do filter also in Items? The result what I need is have to be:
result =
[
{
"Section" : "Title1",
"Items" :
[
{"Nr" : "201"}
]
},
{
"Section" : "Title2",
"Items" :
[
{"Nr" : "202"}
]
}
]
I tried to use the SUBQUERY:
"SUBQUERY(Items, $x, $x.Nr BEGINSWITH[c] %#).#count > 0"
But this return me the same, if it can calculate the Items, then I thought that it can display me Items/Nr what I found, but I dont know how to write this correct. :)
Oh, hang on. I just re-read your question, editing now
To answer your requirement of filtering the sub arrays. Your data model is getting far too complex to still be using generic objects. You should think about setting up an actual data structure with custom objects. You can then offload a lot of the work to these objects instead of putting all the work in one place.
Just trying to find the best way to do this (without a custom data model).
P.S. make a custom data model :)
OK, here we go
I made this a lot easier by wrapping your generic data up into a struct...
struct Item {
let section: String
let items: [[String: String]]
}
It still feels wrong having an array of dictionaries where each dictionary has only one key and it's always the same. Really it should just be an array of strings.
Anyway...
Create the array like so...
let items: [Item] = [
Item(section: "Title1", items: [["Nr" : "101"], ["Nr" : "201"], ["Nr" : "301"], ["Nr" : "401"]]),
Item(section: "Title2", items: [["Nr" : "102"], ["Nr" : "202"], ["Nr" : "302"]]),
Item(section: "Title3", items: [["Nr" : "1102"], ["Nr" : "2102"], ["Nr" : "3102"]])
]
Or from your data however you have it stored.
Then filter and map it into a new array...
let filteredMappedArray = items.filter {
// this filters the array so that only its containing "20..." are in it.
for dictionary in $0.items {
if let numberString = dictionary["Nr"] {
if (numberString.hasPrefix("20")) {
return true
}
}
}
return false
}.map {
// This maps the array and removes anything that isn't "20..." from the items.
Item(section: $0.section, items: $0.items.filter {
numberDictionary in
if let numberString = numberDictionary["Nr"] {
return numberString.hasPrefix("20")
}
return false
})
}
Then I logged the result...
for item in filteredMappedArray {
println("Section: \(item.section) - Items: \(item.items)")
}
And got this result...
Section: Title1 - Items: [[Nr: 201]]
Section: Title2 - Items: [[Nr: 202]]
There may be better/simpler way to combine everything into one function but this is the easiest way I could find.
If you can change your dictionary array thing...
If item can be defined as...
struct Item {
let section: String
let items: [String]
}
Then the filter-map function would become...
let filteredMappedArray = items.filter {
// this filters the array so that only its containing "20..." are in it.
for numberString in $0.items {
if (numberString.hasPrefix("20")) {
return true
}
}
return false
}.map {
// This maps the array and removes anything that isn't "20..." from the items.
Item(section: $0.section, items: $0.items.filter {$0.hasPrefix("20")})
}
By changing that dictionary array to just an array of strings you're removing a layer of complexity that isn't necessary.