Cast While Looping Over Dictionary in Swift

Cast While Looping Over Dictionary in Swift

You're asking the compiler to iterate over headers as a tuple of Strings, but headers is a dictionary, not a tuple.

The solution is to cast the entire headers dictionary at once with the right type, key as String and value as String, like this:

for (key, value) in headers as! [String:String] {
println(key)
println(value)
}

Of course, beware that it will crash if any of the keys or values are not a String.

You would have to iterate over the dictionary with its original type then cast as String inside the loop with safety checks if you're not sure all your keys and values are Strings.

Iterate Dictionary with dictionary data and add it to an array in swift

First of all, when you use

for let tempDict in dataDictionary {
self.tempArray.addObject(tempDict)
}

Swift gives you tuple like (key, value) in tempDict.

So you should iterate like this

for (key, value) in sourceDict {
tempArray.append(value)
}

Note: I used here native swift structures, and my advise - to use them as often as possible (instead of ObjC ones)

Or you can use map-function on dictionary.

let array = sourceDict.map({ $0.1 })

Edit. For

(
{
1455201094707 = {
};
}
{
1455201116404 = {
}:
}
)

use

for (key, value) in sourceDict {
tempArray.append([key : value])
}

or

let array = dict.map({ [$0.0 : $0.1] })

Note. if you use NSDictionary you should cast it to swift Dictionary

if let dict = dict as? [String: AnyObject] {
let array = dict.map({ [$0.0 : $0.1] })
print(array)
}

SwiftUI iterating through dictionary with ForEach

Simple answer: no.

As you correctly pointed out, a dictionary is unordered. The ForEach watches its collection for changes. These changes includes inserts, deletions, moves and update. If any of those changes occurs, an update will be triggered. Reference: https://developer.apple.com/videos/play/wwdc2019/204/ at 46:10:

A ForEach automatically watches for changes in his collection

I recommend you watch the talk :)

You can not use a ForEach because:

  1. It watches a collection and monitors movements. Impossible with an unorered dictionary.
  2. When reusing views (like a UITableView reuses cells when cells can be recycled, a List is backed by UITableViewCells, and I think a ForEach is doing the same thing), it needs to compute what cell to show. It does that by querying an index path from the data source. Logically speaking, an index path is useless if the data source is unordered.

For-in loop and type casting only for objects which match type

You can use a for-loop with a case-pattern:

for case let item as YourType in array {
// `item` has the type `YourType` here
// ...
}

This will execute the loop body only for those items in the
array which are of the type (or can be cast to) YourType.

Example (from
Loop through subview to check for empty UITextField - Swift):

for case let textField as UITextField in self.view.subviews {
if textField.text == "" {
// ...
}
}

Swift 3 iterate over a nested Dictionary?

You want to decode the JSON String and then cast to an array of Dictionary:

if
// cast sender["actions"] to String
let actionsString = sender["actions"] as? String,
// decode data of string and then cast to Array<Dictionary<String, String>>
let actionsStringData = actionsString.data(using: .utf8),
let result = try JSONSerialization.jsonObject(with: actionsStringData, options: []) as? [[String : String]]
{

print("YES \(result)")

for action in result {
print(action)
}
}

Casting an AnyObject to a Dictionary nested in an Array

I think you need to cast the individual elements of the array.

func updateTable(data: [AnyObject]) {
for item in data {
if let item = item as? [String: String] {
items.append(item)
}
}

Or if you want to be more concise...

func updateTable(data: [AnyObject]) {
items += data.flatMap({$0 as? [String: String]})
}

Iterate through nested dictionary of type String: Any

I got it! So basically all I had to do was to fix my Published dictionary from:

@Published var positions = [String: [Any]]() 

to:

@Published var positions = [String: [Position]]() 

where my Position was a struct where I decoded my JSON Response.

Cast value from Dictionary to String in Swift

That's because you are trying to cast from NSNumber to String. If you have different values inside this dictionary use this:

for value in dataDict.values {
if let value = value as? String {
mTextLabel.text = value
}
else if let value = value as? NSNumber {
mTextLabel.text = value.stringValue
}
....
}

In case all values are NSNumber you can cast your dataDict to [String: NSNumber] to avoid the if-lets



Related Topics



Leave a reply



Submit