小编Ada*_*dam的帖子

使用索引将Swift数组转换为Dictionary

我正在使用Xcode 6.4

我有一个UIViews数组,我想转换为带键的字典"v0", "v1"....像这样:

var dict = [String:UIView]()
for (index, view) in enumerate(views) {
  dict["v\(index)"] = view
}
dict //=> ["v0": <view0>, "v1": <view1> ...]
Run Code Online (Sandbox Code Playgroud)

这有效,但我试图以更实用的方式做到这一点.我想我必须创建dict变量让我感到困扰.我很乐意使用enumerate()reduce()喜欢这样:

reduce(enumerate(views), [String:UIView]()) { dict, enumeration in
  dict["v\(enumeration.index)"] = enumeration.element // <- error here
  return dict
}
Run Code Online (Sandbox Code Playgroud)

这感觉更好,但我得到错误:Cannot assign a value of type 'UIView' to a value of type 'UIView?'我已经尝试过其他对象UIView(即:) [String] -> [String:String],我得到了相同的错误.

有关清理的建议吗?

functional-programming swift swift2 swift3

12
推荐指数
1
解决办法
1万
查看次数

按天分组Mongoid对象

在控制台中玩了很多次之后,我想出了这种方法,可以在它们发生的那一天将类似activerecord的(Mongoid)对象分组.我不确定这是实现这一目标的最佳方式,但它确实有效.有没有人有更好的建议,或者这是一个好方法吗?

#events is an array of activerecord-like objects that include a time attribute
events.map{ |event|
  # convert events array into an array of hashes with the day of the month and the event
  { :number => event.time.day, :event => event }
}.reduce({}){ |memo,day|
  # convert this into a hash with arrays of events keyed by their day or occurrance
  ( memo[day[:number]] ||= [] ) << day[:event]
  memo
}

=>  {
      29 => [e1, e2],
      28 => [e3, e4, e5],
      27 …
Run Code Online (Sandbox Code Playgroud)

ruby grouping ruby-on-rails mongoid

5
推荐指数
1
解决办法
2606
查看次数