Swift 4 Dictionary [String : AnyObject] sort by key in alphabetical order
I think the first step is to change
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject]
to
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : Any]
But I cannot understand why you want to sort a Dictionary.. Maybe You intended to declare variable json as Array?
Cannot assign value of type 'String' to type 'AnyObject?' , Swift 3, Xcode 8 beta 6
In b6, String no longer magically bridges to NSString. String is not a class; it's a struct. You need to do the bridging by hand:
dict["key"] = "value" as AnyObject
The fact that is
still seems to be bridging is likely a bug and should be reported.
It goes without saying that [String: AnyObject]
and [String: Any]
should be used as little as possible in your code.
(Make sure to follow the link Hamish provides in the comments below.)
Can't assign value of type Dictionary to LazyMapCollection
It may be that Dictionary.keys
returned a LazyMapCollection
in earlier Swift versions. In Swift 5 it is Dictionary<Key, Value>.Keys
as can be seen from the documentation, in your case
var answerKeys: Dictionary<IntPoint, String>.Keys
But note that you can always access answer.keys
in your code instead of assigning this to a separate property.
Cannot assign value of type String to type AnyObject? Swift 3.0
String
is the value type. AnyObject
only accepts reference types. So in order to add both value types and reference types in Dictionary
use Any
instead of AnyObject
, i.e.
var parameters = [String: Any]()
This is an addition to Swift 3.0.
Swift filter dictionary error: Cannot assign a value of type '[(_, _)]' to a value of type '[_ : _]'
This has been fixed in Swift 4
let data = ["a": 0, "b": 42]
let filtered = data.filter { $0.value > 10 }
print(filtered) // ["b": 42]
In Swift 4, a filtered dictionary returns a dictionary.
Original answer for Swift 2 and 3
The problem is that data
is a dictionary but the result of filter
is an array, so the error message says that you can't assign the result of the latter to the former.
You could just create a new variable/constant for your resulting array:
let data: [String: String] = [:]
let filtered = data.filter { $0.1 == "Test" }
Here filtered
is an array of tuples: [(String, String)]
.
Once filtered, you can recreate a new dictionary if this is what you need:
var newData = [String:String]()
for result in filtered {
newData[result.0] = result.1
}
If you decide not to use filter
you could mutate your original dictionary or a copy of it:
var data = ["a":"Test", "b":"nope"]
for (key, value) in data {
if value != "Test" {
data.removeValueForKey(key)
}
}
print(data) // ["a": "Test"]
Note: in Swift 3, removeValueForKey
has been renamed removeValue(forKey:)
, so in this example it becomes data.removeValue(forKey: key)
.
Cannot assign value of type '[String : AnyObject]
The problem is that you cannot split []
operator onto a separate line in Swift: square brackets need to be on the same line as the dictionary being dereferenced. Also don't forget to dismiss and release the picker
.
picker.dismissModalViewControllerAnimated(true)
picker.release()
imgview.image = info[UIImagePickerControllerOriginalImage] as UIImage
Since Swift does not use mandatory semicolons to break down statements, you need to pay more attention to what goes onto which line. Your code is interpreted like this:
- Assign
info
toimgview.image
- Cast an array that consists of
UIImagePickerControllerOriginalImage
toUIImage
Obviously, this is not the effect that you were trying to get. Moving square brackets to the same line as info
will fix this problem.
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:
- It watches a collection and monitors movements. Impossible with an unorered dictionary.
- When reusing views (like a
UITableView
reuses cells when cells can be recycled, aList
is backed byUITableViewCells
, and I think aForEach
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.
Can't add UInt64 to dictionary of type: [String : AnyObject?]
This used to work in an earlier version of Swift when Swift types were automatically bridged to Foundation types. Now that that feature has been removed, you have to do it explicitly:
You can just explicitly cast them to AnyObject
:
let dic : [String: AnyObject?] = [
"Name": someString_Variable as AnyObject,
"Sum": someUInt64_Variable as AnyObject
]
and Swift will convert them to Foundation types NSString
for String
and NSNumber
for UInt64
.
It might be clearer if you just cast to those types yourself:
let dic : [String: AnyObject?] = [
"Name": someString_Variable as NSString,
"Sum": someUInt64_Variable as NSNumber
]
Related Topics
Split Paragraphs into Sentences
Scrolling Delegate in Tableview
How to Add Icon to a Share Sheet in Swift
How to Refresh Multiple Timers in Widget iOS14
Swift Subclasses Used in Generics Don't Get Called When Inheriting from Nsobject
Button State Activates on Wrong Cells
Cast to Different C Struct Unsafe Pointer in Swift
Arkit - Collision with Real World Objects
How to Combine Two Nsdictionary in Swift
Error: Extraneous Argument Label 'No1:' in Call
Generics and Functional Programming in Swift
How to Incorporate Swift Package Manager to an Existing Xcode Project
Swiftui Pass Two Child Views to View
Split String by Components and Keep Components in Place
Comparing Two Enum Variables Regardless of Their Associated Values
See Characters in an Nscharacterset (Swift)
How to Create a Portal Effect in Arkit Just Using the Scenekit Editor