使用和返回Realm对象而不是静态数组对象

时间:2018-05-03 10:27:12

标签: swift realm

更新了其他人的回答如果您遇到此问题......

问题我想在函数内部使用Realm Objects而不是静态数组来返回对象输出。

解决方案您需要设置一个Object而不是一个struct ....

e.g。

这个:

class WorkoutGeneratorObject: Object {
    @objc dynamic var name = ""
    @objc dynamic var maxReps = 0

    convenience init(name: String, maxReps: Int) {
        self.init()
        self.name = name
        self.maxReps = maxReps
    }

不是这个:

struct WorkoutExercise : Hashable, Equatable{

let name : String
let reps : Int
var hashValue: Int {
    return name.hashValue
}

static func == (lhs: WorkoutExercise, rhs: WorkoutExercise) -> Bool {
    return lhs.name == rhs.name
}

然后格式化函数的返回,在类对象中

class WorkoutGeneratorObject: Object {
    @objc dynamic var name = ""
    @objc dynamic var maxReps = 0

    convenience init(name: String, maxReps: Int) {
        self.init()
        self.name = name
        self.maxReps = maxReps
    }

    func generateExercise() -> WorkoutExercise {
        return WorkoutExercise(
            name: name,
            reps: Int(arc4random_uniform(UInt32(maxReps)))
        )
    }
}

然后你可以在你的代码中的其他函数中使用它,如下所示:

struct WorkoutGenerator {

// This is the "pool" of exercises from
// which it generates a workout (similar to your
// `exerciseBankArray`)
let realmExercisePool = realm.objects(WorkoutGeneratorObject.self)
let exercisePool: [WorkoutExerciseGenerator]

// Min and max amount of workouts
let minCount: Int
let maxCount: Int

// Generates a workout from the generator
func generate() -> Workout {

    let amount = Int(arc4random_uniform(UInt32(maxCount - minCount))) + minCount
    let myExercises : [WorkoutExercise] = (0..<amount).map { _ in
        // Selects an exercise generator at random
        let index = Int(arc4random_uniform(UInt32(exercisePool.count)))
        // Generates a random workout exercise from this generator

        return realmExercisePool[index].generateExercise()
    }

    return Workout(workoutExercises: myExercises)

}

0 个答案:

没有答案