简体   繁体   中英

Returning Swift Dictionary as AnyObject

 func toAnyObject() -> AnyObject {
        return [
            "name": title,
            "addedByUser": subtitle,
            "completed": imageURL
        ]
    }

The above code produces the following error:

Contextual type 'AnyObject' cannot be used with dictionary literal

UPDATE: I am trying to create the toAnyObject function and utilize it in a Firebase application. I get the following:

, reason: '(setValue:) Cannot store object of type _SwiftValue at name. Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray.'

 let rootRef = FIRDatabase.database().reference()
        let categoriesRef = rootRef.child("categories")

        let annuals = FlowerCategory(id: 1, title: "Annuals",subtitle :"Plants that just last one season. These plants will die in the winter. ", imageURL: "annuals.jpg")
        let perennials = FlowerCategory(id: 2, title: "Perennials",subtitle :"Plants come back year after year. These are also very less expensive", imageURL: "Perennial.jpg")

        let flowerCategories = [annuals,perennials]

        for flowerCategory in flowerCategories {

            let categoryRef = categoriesRef.child("category")
            categoryRef.setValue(flowerCategory.toAnyObject())  <- THIS LINE ERROR

        }

Dictionary is a value type in swift. And AnyObject only accepts reference types .

So in order to return a Dictionary use Any instead of AnyObject .

func toAnyObject() -> Any {
        return [
            "name": title,
            "addedByUser": subtitle,
            "completed": imageURL
        ]
    }

Cast it to NSDictionary :

func toAnyObject() -> AnyObject {
    return [
        "name": title,
        "addedByUser": subtitle,
        "completed": imageURL
    ] as NSDictionary
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM