I have :-
var myArray:Array = array<JSON>
I want :-
var myJSON:JSON = myArray as? JSON
but i get a warning:-
Cast from 'Array' to unrelated type 'JSON' always fails
Can anyone help me how to convert an Array object to a JSON object?
A little more insight what i am trying to do:-
(This might not be needed to answer my above question but still...) Note:- I am using objectMapper for mapping swiftyJSONObjects.
var monthArray = Array<JSON>
var allEventsInDayArray:Array<JSON> = [] // an empty array
for (_,dayObj) in monthArray
{
guard let dayEventsArray = dayObj["events"].array else { break }
allEventsInDayArray.appendContentsOf(dayEventsArray)
}
print(allEventsInDayArray)
var allEventsJSON:JSON? = JSON(allEventsInDayArray)
var EventModelArray:Array<EventModel>? = Mapper<EventModel>().mapArray(allEventsJSON?.object.allValues)
If I understood your question and you want to create a SwiftyJSON object from an array you should do like this:
var myJSON:JSON = JSON(myArray)
Related
Hello I have a json the returns me some parameters as variables.
It has Parameter1, Parameter2, Parameter3 etc..
I don't know how many parameters will it give me. It's not a list it's just different variables in the json.
Which is the best way to map a json like that? I use Object Mapper
For Example:
First Time the json is
{
"MyObject": {
"Parameter1": "p1",
"Parameter2": "p2",
"Parameter3": "p3",
"Parameter4": "p4"
}
}
And a second time the json is
{
"MyObject": {
"Parameter1": "p1",
"Parameter2": "p2",
"Parameter3": "p3"
}
}
You can try this.
let keyvalue = parentDict.value(forKey: "MyObject") as! NSDictionary
var lastValue = Keyvalue.allValues
var lastKey = Keyvalue.allKeys
for Keyname in Keyvalue.allKeys
{
print("Keyname %#",Keyname)
print("Value %#",Keyvalue.value(forKey:Keyname))
}
the first step to parse any JSON to make it reusable is to create your Model class or struct accordingly.
Create a class called MyObject as same as your json dictionary
Create a let/var property parameters: [String]?. It's optional as API isn't reliable and maybe wont send anything at all.
See the example below how I parse the json object below.
class MyObject {
let parameters: [String]?
// it's failable because maybe json different at runtime & couldn't parse
init?(json: [String:AnyObject]) {
var key = "Parameter"
var parms = [String]()
for i in 0..<json.count {
guard let item = json["\(key)\(i+1)"] as? String else { continue }
params.append(item)
}
self.parameters = params
}
}
Now you can access the parameters array with index.
Well this could be refactored and you can get the idea how you will handle this with that library.
I have a Dictionary and i want to save it to NSUserDefaults(or something else so I can have access to my variables after i have terminated the app) , I found an example:
var saved = NSUserDefaults.standardUserDefaults()
let dict = ["Name": "Paul", "Country": "UK"]
saved.setObject(dict, forKey: "SavedDict")
But when i used it to mine Dictionary it didn't work. (maybe because my dictionary it's a little bit different)
My Dictionary is made like this:
var userDictionary = [Int : Event]()
struct Event {
var sensorName: String
var sensorType: String
var sensorSub: String
}
And i add elements like this:
userDictionary[value] = Event(sensorName: "first", sensorType: "Temp", sensorSub: "Third")
And here is what i tried to do so I can store it.
saved.setObject(userDictionary, forKey: "valueDictionary")
And I get this error:
Cannot convert value of type '[Int : SensorsView.Event]' to expected
argument type 'AnyObject?'
To avoid this error I did this:
self.saved.setObject(self.userDictionary as? AnyObject, forKey: "valueDictionary")
But I can't retrieve what i saved
Unfortunately this question didn't help me after some comments i believe that the goal here is to convert my dictionary to Data (or something else) and after i retrieve it i convert it back to Dictionary
Try to convert the data to NSData and then retrieve like so:
/// Save
NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(object), forKey: key)
/// Read
var data = NSUserDefaults.standardUserDefaults().objectForKey(key) as NSData
var object = NSKeyedUnarchiver.unarchiveObjectWithData(data) as [String: String]
What i think is from the link below you will be able to store the Dictionary into NSUserDefaults
Swift NSUserDefaults not saving Dictionary?
or
Saving dictionary into NSUserDefaults may help
I managed to save my custom Dictionary using Realm!
Instead of a struct I use a different class like this:
import RealmSwift
class Sensors : Object {
dynamic var sensorName = ""
dynamic var sensorType = ""
dynamic var sensorSub = ""
}
and then I fill it like this:
var useOfRealm = try! Realm()
var allSensors = useOfRealm.objects(Sensors.self)
var saving = Sensors()
func fillThis() {
try! useOfRealm.write {
saving.sensorName = "something"
saving.sensorType = "something"
saving.sensorSub = "something"
useOfRealm.add(saving)
}
}
Use the function with parameters so you can fill the 'Dictionary' Dynamically.
Use allSensors so you can retrieve everything that you want.
I have two separate arrays that I want to import into a dictionary. Order is extremely important because both arrays must match in index
struct MyVariables {
static var users:NSArray!
static var img:NSArray!
}
var data = SearchVC.getData()
MyVariables.users = data.users; //array 1 (key)
MyVariables.img = data.img; //array 2
// Goal is to insert these arrays into a dictionary while maintaing the matching indexes on both arrays
// Dictonary (MyVariables.img, key: MyVariables.users)
A Dictionary does not have a particular order. However, if both arrays have the same length, it is quite easy to iterate over them together:
var dictionary = [NSString: AnyObject]()
for var index = 0; index < data.users.count; index++ {
let img = data.img as! NSString
dictionary[img] = data.users[index]
}
Or, as #robertvojta suggested, use the zip() method:
var dictionary = [NSString: AnyObject]()
for (user, image) in zip(data.users, data.img) {
let img = image as! NSString
dictionary[img] = user
}
The key in a dictionary in swift must be hashable. i.e., not AnyObject.
Assuming you can replace some of your untyped Swift arrays, or cast them like so:
struct MyVariables {
var users:Array<AnyObject>
var img:Array<String>
}
then you can iterate through 1 array using a preferred Swift method and access the second using indexing:
var dictionary = Dictionary<String, AnyObject>()
for (index, element) in enumerate(MyVariables.img) {
dictionary[element] = MyVariables.users[index]
}
Use for loop for travels the array in that as per index access keys and values respective array and add it in dictionary. Its so simple so you can achive your goal using it.
I hope it will help you!
for example.. I want to pass in some dictionaries into a class in its initializer, and i want to reference those dictionaries across my class.. the problem is when I set them as properties, they are actually being copied, not referenced.
example:
var activeDict: [Int: Projectile]
var inactiveDict: [Int: Projectile]
init(inout activeDict: [Int: Projectile], inout inactiveDict: [Int: Projectile]) {
self.activeDict = activeDict
self.inactiveDict = inactiveDict
I want to use activeDict, and inactiveDict across my class. I want them to be references of the originals that are being passed in.
You can store an UnsafeMutablePointer to the dictionary, here is an example, tested in playground:
var dict = ["hejj": 1]
class A<T> {
var myDictRef: UnsafeMutablePointer<T>
init(ref: UnsafeMutablePointer<T>) {
self.myDictRef = ref
}
}
let a = A(ref: &dict)
a.myDictRef.memory["asd"] = 3
a.myDictRef.memory
dict
Updated
In your case use it like that:
var activeDict: UnsafeMutablePointer<[Int: Projectile]>
var inactiveDict: UnsafeMutablePointer<[Int: Projectile]>
init(activeDict: UnsafeMutablePointer<[Int: Projectile]>, inactiveDict: UnsafeMutablePointer<[Int: Projectile]>) {
self.activeDict = activeDict
self.inactiveDict = inactiveDict
}
whenever you want to use activeDict or inactiveDict, you can call the dictionary behind the pointer with their memory property like:
activeDict.memory[YourKey] = YourValue
I have a dictionary set up as:
var jDict = Dictionary<String, AnyObject[]>()
Where the arrays are either a collection of custom buttons (JunkButton) or Labels (JunkLabels).
I am having an issue when trying to access the members of the arrays contained in the Dictionary as follows:
let thisArray = jDict[key]
var aButton = thisArray[0] //Gives error: 'AnyObject[]? does not have a member named 'subscript'
I can get around this by downcasting the whole array as follows:
if let aArray = thisArray as? JunkButton[]{
var aButton = aArray[0]
}
This seems very cumbersome especially if I am sure I know what type the array is made up of beforehand. Is there a way to cast thisArray when it is created that would allow me to extract its elements without unwrapping them each time?
Dictionary always give you Optional value.
Your code is like this
let thisArray : Optional<AnyObject[]> = jDict[key]
You need to unwrap it to get non-optional value
let thisArray = jDict[key]! // thisArray is AnyObject[]
You really shouldn't use a dictionary for this. Swift makes it very easy to use custom little structs or classes instead of dictionaries:
struct JunkItems {
var buttons: [JunkButton] = []
var labels: [JunkLabel] = []
}
Then you can access those items like this without downcasting:
for button in junkItems.buttons {
// ...
}
Or:
if let button = junkItems.buttons[0] {
// ...
}
Btw, the array notation [JunkButton] is new in beta 3.