在Swift中用数组创建一个字典

时间:2016-03-10 09:28:35

标签: swift dictionary

我想从数组中创建一个字典,并为每个字符分配一个新的自定义对象。我稍后会对这些对象做些什么。我怎么能这样做?

var cals = [1,2,3] 
// I want to create out of this the following dictionary
// [1:ReminderList() object, 2:ReminderList() object, 3:ReminderList() object]

let calendarsHashedToReminders = cals.map { ($0, ReminderList()) } // Creating a tuple works!

let calendarsHashedToReminders = cals.map { $0: ReminderList() } // ERROR: "Consecutive statements on a line must be separated by ';'"

1 个答案:

答案 0 :(得分:6)

map()会返回Array,因此您必须使用reduce()或创建如下字典:

var calendars: [Int: ReminderList] = [:]
cals.forEach { calendars[$0] = ReminderList() }

您也可以使用reduce()获取oneliner,但我不喜欢使用reduce()来创建数组或字典。