gpt4 book ai didi

swift - @distinctUnionOfObjects 在 Swift 中可用吗?

转载 作者:行者123 更新时间:2023-11-28 06:32:16 25 4
gpt4 key购买 nike

我正在尝试从 this 开始快速制作日历很好的例子。到目前为止,我设法显示了网格和所有自定义 UICollectionViewLayout 的补充 View 。问题是当我试图在日历中添加事件时。日行和日历都在同一个 NSMutableDictionary 中,它有一个使用此格式 2016-10-12 表示日期(字符串)的键。 objective-c 代码是

-(void)groupEventsBySection{
//toDeviceTimezoneDateString simply take a Date and make a string
_eventsBySection = [mEvents groupBy:@"StartDate.toDeviceTimezoneDateString"].mutableCopy;
// after groupBy is performed _eventsBySection contains only those keys found in mEvents with inside an array of objects {
// "2016-10-12" = (
// "<MSEvent: 0x60000004a680>",
// "<MSEvent: 0x60000004a380>");
// "2016-10-13" = (
// "<MSEvent: 0x600000049b10>");
// "2016-10-17" = (
// "<MSEvent: 0x600000049fc0>");
// }

NSDate* date = [NSDate today:@"device"]; // today's date
if(self.daysToShow == 1 && _eventsBySection.count == 1){
date = [NSDate parse:_eventsBySection.allKeys.firstObject];
}
//here it adds the remaining "daysToShow" if the key doesn't already exist in the MutableDictionary.
for(int i = 0; i< self.daysToShow; i++){
if(![_eventsBySection.allKeys containsObject:date.toDeviceTimezoneDateString]){
[_eventsBySection setObject:@[] forKey:date.toDeviceTimezoneDateString];
}
date = [date addDay]; // this just add one day to date
}
}

到此为止已经很清楚了。问题是当我尝试更改 objective-c 中的 groupBy 函数时:

- (NSDictionary*)groupBy:(NSString*)keypath{
return [self groupBy:keypath block:^NSString *(id object, NSString *key) {
return key;
}];
}

- (NSDictionary*)groupBy:(NSString*)keypath block:(NSString*(^)(id object, NSString* key))block{
NSMutableDictionary *result = [NSMutableDictionary new];
NSString* finalKeypath = [NSString stringWithFormat:@"%@.@distinctUnionOfObjects.self",keypath];
NSArray *distinct = [self valueForKeyPath:finalKeypath];

[distinct each:^(NSString* value) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K = %@", keypath,value];
NSArray *objects = [self filteredArrayUsingPredicate:predicate];
[result setObject:objects forKey:block(objects[0],value)];
}];
return result;
}

- (NSDictionary*)expand:(NSString*)keypath{
return [self expand:keypath unique:NO];
}

到目前为止,这是我在 swift 中所做的:

我有这个类,在原始代码中是 MSEvent

class Event : NSObject {

var title:String?
var location:String?
var startTime:Date?
var endTime:Date?
var duration:Int?
var subtitle:String?

init(startTime: Date, duration: Int, title: String, subtitle: String) {
super.init()
self.startTime = startTime
self.duration = duration
self.title = title
self.subtitle = subtitle

}

我创建了一些假事件:

override func viewDidLoad() {
let today = Date()
let event1 = Event(startTime: today, duration: 60, title: "prova", subtitle: "HEllo")
let event2 = Event(startTime: today, duration: 60, title: "prova", subtitle: "HEllo")
let event3 = Event(startTime: today.dateByAddingDays(days: 1), duration: 60, title: "prova", subtitle: "HEllo")

var array:[Event] = []
array.append(event1)
array.append(event2)
array.append(event3)

calendarView.setEvents(events: array)
}

func setEvents(events:[Event]){

mEvents = events as NSArray
print(mEvents)
//this right now returns the 3 event objects I added:
// (
// "<myapp.Event: 0x60800032ba40>",
// "<myapp.Event: 0x60800032bae0>",
// "<myapp.Event: 0x60800032bcc0>"
// )
self.forceReload(reloadEvent: true) //force reload eventually call the groupEventsBy days
}


func groupEventsByDays(){
// of course everything works without the next line of code
eventsBySection = mEvents.groupBy(keypath: "startTime").mutableCopy() as! NSMutableDictionary
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var date = dateFormatter.date(from: "2016-10-01")
// right now daysToShow is equal to 30
for _ in 0..<daysToShow{

eventsBySection.setObject([], forKey: self.setFormatDate(date: date!) as NSCopying)


date = self.addDay(date: date!)

}
}

问题来了。这是我的扩展。 扩展 NSArray{

    func groupBy(keypath:NSString)->NSDictionary{

return self.groupBy(keypath: keypath, block: { (object, key) -> NSString in
return key
})
}

func groupBy(keypath:NSString,block:@escaping ((_ object: Any, _ key:NSString )-> NSString))-> NSDictionary{

let result:NSMutableDictionary = NSMutableDictionary()

let finalKeypath = String.localizedStringWithFormat("%@.distinctUnionOfObjects.self", keypath)
let distinct:NSArray = self.value(forKey: finalKeypath) as! NSArray

(distinct as AnyObject).each(operation: { (value) in
let predicate = NSPredicate(format: "%K = %@", keypath,value as! CVarArg)
let objects = self.filtered(using: predicate)
result.setObject(objects, forKey: (block(objects[0], value as! NSString)))

})

return result;
}

func each(operation:@escaping ((_ object: AnyObject)-> Void)){

self.enumerateObjects({ (object, idx, stop) in
operation(object as AnyObject)
})

}
}

它崩溃并出现错误 此类不符合键 startTitle.distinctUnionOfObjects.self 的键值编码。'我试过像这样使用 map

       let startDate = array.map ({ $0.startTime })

我设法获取了所有日期(虽然没有明显区别),但我不知道如何使用 swift 实现上述代码中显示的相同结果。

最佳答案

我终于设法完成了上述 objective-c 代码使用 @distinctUnionOfObjects.sel 所做的事情。不过,我不太确定这是一种优雅的方式。欢迎所有评论或更好的答案。

extension Collection {
func find( predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Self.Iterator.Element? {
return try index(where: predicate).map({self[$0]})
}
}

override func viewDidLoad() {
super.viewDidLoad()

let event1 = Event(startTime: today!, duration: 60, title: "prova", subtitle: "HEllo")
let event2 = Event(startTime: (today?.dateByAddingDays(days: 5))!, duration: 60, title: "prova", subtitle: "HEllo")
let event3 = Event(startTime: (today?.dateByAddingDays(days: 1))!, duration: 60, title: "prova", subtitle: "HEllo")
let event4 = Event(startTime: todayLater!, duration: 60, title: "prova", subtitle: "HEllo")

var array:[Event] = []
array.append(event1)
array.append(event2)
array.append(event3)
array.append(event4)

// I create an array with all the date/startTime
let startTime = array.map ({ $0.startTime })

let dict:NSMutableDictionary = [:]

for date in startTime {
//find the objects for that date
let object = array.find(predicate: {$0.startTime?.toDeviceDateString() == date?.toDeviceDateString()})
//check if that key/date exist in the dictionary
if var val:[Event] = dict[(date?.setFormatDate())!] as! [Event]? {
//if it does I simply add the object to the array
val.append(object!)
dict.setObject(val, forKey: date?.setFormatDate() as! NSCopying)

} else {
print("key is not present in dict")
//otherwise I add a new array with that object inside for the date/key
dict.setObject([object], forKey: date?.setFormatDate() as! NSCopying)
}


}

calendarView.setEvents(events: dict)
}

func setEvents(events:NSMutableDictionary){
//slots events hold the events objects
slotEvents = events
self.forceReload(reloadEvent: true)

}


func groupEventsByDays(){


let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var date = dateFormatter.date(from: "2016-10-01")

for _ in 0..<daysToShow{

if let val:[Event] = slotEvents[(date?.setFormatDate())!] as! [Event]? {

eventsBySection.setObject(val, forKey: date?.setFormatDate() as! NSCopying)

}else{

eventsBySection.setObject([], forKey: date?.setFormatDate() as! NSCopying)

}

date = self.addDay(date: date!)

}
print("after\(eventsBySection)")
//Which print
//{
//"2016-10-01" = (
// );
//"2016-10-02" = (
// );
// "2016-10-03" = (
// "Optional(<myapp.Event: 0x6000001242e0>)",
// "<myapp.Event: 0x6000001242e0>"
// );
// "2016-10-04" = (
// "Optional(<myapp.Event: 0x600000124600>)"
// );
// "2016-10-05" = (
// );
// "2016-10-06" = (
// );
// "2016-10-07" = (
// );
// "2016-10-08" = (
// "Optional(<myapp.Event: 0x600000124240>)"
// );
// "2016-10-09" = (
// );
//.... and so on up to 30 days

}

关于swift - @distinctUnionOfObjects 在 Swift 中可用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39994134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com