How to assign a Dictionary to AnyObject in swift

前端 未结 3 495
我在风中等你
我在风中等你 2021-01-18 11:04

I have been playing around with Swift. I have had multiple errors with types, especially working with Swift and my old Objective-C classes. The problem with this method is:

相关标签:
3条回答
  • 2021-01-18 11:22

    In Swift 3

    code:
    
    var curArr:[Dictionary<String, Any>] = [
    [
            "imageName" : "photo.jpg",
            "colorDic" :[
                "red" : 1.0,
                "green" : 0.0,
                "blue" : 0.0
            ],
            "percentage" : 0.5
        ]
    ]
    

    0 讨论(0)
  • 2021-01-18 11:23

    Your code works fine in playground, without compile or runtime errors. Here is what I added to populate curArr:

    var curArr:[Dictionary<String, AnyObject>] = [
        [
            "imageName" : "photo.jpg",
            "colorDic" : ["red" : 1.0, "green" : 0.0, "blue" : 0.0],
            "percentage" : 0.5
        ]
    ]
    

    With all this forced unwrapping I think you just have to make sure that what self.getItemsForCurrentStack() returns is indeed what you expect.

    Result in playground:

    [
     "percentage": {Some 5.0e+-1}, 
     "image": nil, 
     "color": {Some r 1,0 g 0,0 b 0,0 a 1,0}
    ]
    

    My recommendation would be to refactor into objects - that would make your code so much more readable!

    0 讨论(0)
  • 2021-01-18 11:40

    Dictionary is a struct in Swift, whereas AnyObject is

    /// The protocol to which all classes implicitly conform.

    Depending what you're trying to do, you may want to use Any in your code, or cast your dictionary to NSDictionary using as NSDictionary.


    Edit after your clarification:

    If you split up the append call from the dictionary itself, you see a better error message:

    So, the issue is that your dictionary contains some Optional values, but Optional is a struct and not convertible to Obj-C. You can fix by casting to UIImage! and AnyObject! (ImplicitlyUnwrappedOptional), or by using as!.

    0 讨论(0)
提交回复
热议问题