[英]Realm Swift: instance member cannot be used on type
我收到此错误:
“ Realm Swift:实例成员'Int'不能用于类型'Comment'”
我已经找到了建议使用关键字static的 答案 。 但是,由于我要编写的函数的重点是在创建对象之后访问主键,因此具有静态变量将不起作用。
关于如何改善这一点的任何建议?
import Foundation
import RealmSwift
class Comment: Object {
dynamic var id : Int = -1
override class func primaryKey() -> String? {
return String(id)
}
}
在对我有用的评论中引用“ @Octaviano Putra”:
primaryKey函数应该返回主键变量的变量名,而不是值,因此您应该返回“ id”,而不是Ref: realm.io/docs/swift/latest/#primary-keys
我将添加此答案以说明错误信息[ 强调我的]:
“ Realm Swift: 实例成员 '
Int
'不能用于类型 'Comment
'”
在没有显式访问类型本身的实例的情况下, 类型方法不能访问该类型的实例成员 (在上面的示例中,它不是)。
从语言指南-方法中 :
类型方法
如上所述,实例方法是在特定类型的实例上调用的方法。 您还可以定义在类型本身上调用的方法。 这些方法称为类型方法。 您可以通过在方法的
func
关键字之前写入static
关键字来指示类型方法。 类也可以使用class
关键字允许子类重写该方法的超类实现。
class Foo {
// this is an _instance_ property, accessible to
// _instances_ of the _type_ 'Foo'
let instanceProperty: Int
// this is a _type method_, owned by the _type_ 'Foo'
class func typeMethod() -> String {
// this method knows nothing about the _content_ of
// particular instances of of the type itself (unless
// we explictly provide this information to the method)
return "foo"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.