将Swift字典作为AnyObject返回

时间:2016-09-27 02:51:25

标签: ios swift

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

上面的代码产生以下错误:

Contextual type 'AnyObject' cannot be used with dictionary literal

更新:我正在尝试创建toAnyObject函数并在Firebase应用程序中使用它。我得到以下内容:

, 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

        }

2 个答案:

答案 0 :(得分:1)

Dictionary是swift中的值类型AnyObject仅接受引用类型

因此,为了返回Dictionary使用Any而不是AnyObject

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

答案 1 :(得分:1)

将其投放到$("#options").trigger('liszt:updated');

NSDictionary