我有一个旧项目,我正试图从Swift 3移植到Swift 4再移植到Swift5。看来我最终需要离开ObjectMapper,但是在我能够这样做之前,我需要将这个错误修复为获取重新编译的代码。不幸的是,这只是整个代码库中此问题的众多实例之一,因此我无法避免。
代码let sortedWorkoutDiary = List(from: exercise.workoutDiary.sorted(byKeyPath: "date"))
产生Argument type 'Results<Workout>' does not conform to expected type 'Decoder'
错误:
func recordWorkout(_ newWorkout: Workout) {
let lastWorkout = exercise.workoutDiary.last // grab the last workout for later comparison
let realm = try! Realm()
try! realm.write {
exercise.workoutDiary.append(newWorkout) // write the workout no matter what
}
if let secondToLastWorkout = lastWorkout { // only bother checking out of order if there is a last workout...
if newWorkout.date < secondToLastWorkout.date { // ...and now look to see if they are out of order
let sortedWorkoutDiary = List(from: exercise.workoutDiary.sorted(byKeyPath: "date")) // ERROR: Argument type 'Results<Workout>' does not conform to expected type 'Decoder'
try! realm.write {
exercise.workoutDiary.removeAll()
exercise.workoutDiary.append(objectsIn: sortedWorkoutDiary)
}
}
}
}
这是将Realm List <>支持添加到ObjectMapper的代码
class ListTransform<T:RealmSwift.Object> : TransformType where T:Mappable {
typealias Object = List<T>
typealias JSON = [[String:Any]]
let mapper = Mapper<T>()
func transformFromJSON(_ value: Any?) -> List<T>? {
let result = List<T>()
if let tempArr = value as? [Any] {
for entry in tempArr {
let mapper = Mapper<T>()
let model : T = mapper.map(JSONObject: entry)!
result.append(model)
}
}
return result
}
func transformToJSON(_ value: Object?) -> JSON? {
var results = [[String:Any]]()
if let value = value {
for obj in value {
let json = mapper.toJSON(obj)
results.append(json)
}
}
return results
}
}
对象的简化视图:
final class Exercise: Object, Mappable {
dynamic var name = ""
dynamic var notes: String?
var workoutDiary = List<Workout>()
dynamic var goal = 0
}
extension Exercise {
func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
notes <- map["notes"]
workoutDiary <- (map["workoutDiary"], ListTransform<Workout>())
bodyWeightMultiplier <- map["bodyWeightMultiplier"]
sortOrder <- map["sortOrder"]
username <- map["username"]
}
}
final class Workout: Object, Mappable {
dynamic var date = NSDate()
var sets = List<WorkSet>()
}
extension Workout {
func mapping(map: Map) {
date <- (map["date"], DateTransform())
sets <- (map["sets"], ListTransform<WorkSet>())
}
}