【发布时间】:2015-05-06 17:02:32
【问题描述】:
我想编写一个函数,它从字符串返回特定的 NSCalendarUnits。 因此,我的函数需要尽可能多的 NSCalendarUnits 作为用户想要的参数。
public extension String{
func calendarComponents(units: NSCalendarUnit, separateString: String) -> NSDateComponents{
// now i want to know which units the user specified
// so i can scan the string for integerValues and add them to
// the corresponding component
}
}
因此,我希望用户定义一个像 var myStringDate = "4/5" 这样的字符串,然后使用该函数
myStringDate.calendarComponents(units: .CalendarUnitMonth |
.CalendarUnitWeekday, "/")
然后得到一个 .month = 4 和 .weekday = 5 的 NSDateComponent 对象。
我确实知道如何扫描字符串以获取所有需要的值,但我不知道如何将这些值添加到正确的组件属性中。
【问题讨论】:
-
你不能这样做,因为单位被用作标志。所以你不能按“顺序”检索它们。但是您可以查找变量参数列表,例如问题:stackoverflow.com/questions/24035832/… 并使用
componentsSeparatedByString:剥离NSString。 -
我不太确定你认为我应该怎么做,但我想出了一个解决方案(虽然你的回答对我帮助很大,请参阅大答案)
-
我只是指出了潜在的提示。我指出了 .CalendarUnitMont|.CalendarUnitWeekDay 返回 .CalendarUnitMont+.CalendarUnitWeekDay 的事实,因此很难在之后检索“订单”(1+2 或 2+1 结果与更简单的示例相同)。剩下的就看你了。但我建议您发布您的答案。
标签: ios nsdatecomponents