领域 - 总结所有字段错误

时间:2018-03-18 22:21:34

标签: ios swift realm

我试图从我的对象获取所有持续时间字段并将它们添加到一起但是我似乎无法找到解决方案来执行此操作。

我的目标如下:

Results<Relax> <0x7fe6f1c61bf0> (
    [0] Relax {
        relax = New Activity;
        duration = 16.000000;
        time = 7:05 PM;
        date = 3/18/18;
    },
    [1] Relax {
        relax = New Activity;
        duration = 1.000000;
        time = 7:12 PM;
        date = 3/18/18;
    },
    [2] Relax {
        relax = New Activity;
        duration = 1.000000;
        time = 7:18 PM;
        date = 3/18/18;
    },
    [3] Relax {
        relax = New Activity;
        duration = 3.000000;
        time = 7:31 PM;
        date = 3/18/18;
    },
    [4] Relax {
        relax = New Activity;
        duration = 3.000000;
        time = 7:32 PM;
        date = 3/18/18;
    },
    [5] Relax {
        relax = New Activity;
        duration = 5.000000;
        time = 8:55 PM;
        date = 3/18/18;
    }
)

因此,例如,如果将所有这些持续时间加在一起,则应该得到29

我尝试了以下内容:

    func getAllTime(){
     let allTime = realm.objects(Relax.self).sum(ofProperty: "duration")
        print(allTime)
    }

但是此错误出现在代码中:

  

通用参数&#39; T&#39;无法推断

我的Realm对象配置如下:

@objcMembers class Relax: Object {


    dynamic var relax: String = ""
    dynamic var duration: Double = 0.0
    dynamic var time: String = ""
    dynamic var date: String = ""

    convenience init(relax: String, duration: Double, time: String, date: String) {
        self.init()
        self.relax = relax
        self.duration = duration
        self.time = time
        self.date = date
    }

}

我有什么方法可以解决这个或其他方式解决这个错误吗?

我对Swift和Realm相当新,并且无法确定为什么这不起作用。

1 个答案:

答案 0 :(得分:1)

编译器错误所指的泛型函数是sum(ofProperty:)。通过查看函数的类型签名可以看出这一点,即func sum<T>(ofProperty property: String) -> T where T : AddableType

如果向allTime变量添加显式类型注释,则会解决错误。

let allTime: Double = realm.objects(Relax.self).sum(ofProperty: "duration")