Reputation: 9606
I am getting this error:
"Realm Swift: instance member 'Int' cannot be used on type 'Comment'"
I have found this answer that suggest to use the keyword static. However, as the point of the function that I am writing is to access the primary key after that the object has been created, having a static variable would not work.
Any suggestion on how to improve this?
import Foundation
import RealmSwift
class Comment: Object {
dynamic var id : Int = -1
override class func primaryKey() -> String? {
return String(id)
}
}
Upvotes: 0
Views: 873
Reputation: 73206
I'll add this answer to explain the telling error message [emphasis mine]:
"Realm Swift: instance member '
Int
' cannot be used on type 'Comment
'"
A type method cannot access instance members of the type without having explicit access to an instance of the type itself (which it does not, in you example above).
From the Language Guide - Methods:
Type Methods
Instance methods, as described above, are methods that are called on an instance of a particular type. You can also define methods that are called on the type itself. These kinds of methods are called type methods. You indicate type methods by writing the
static
keyword before the method’sfunc
keyword. Classes may also use theclass
keyword to allow subclasses to override the superclass’s implementation of that method.
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"
}
}
Upvotes: 0
Reputation: 9606
Quoting "@Octaviano Putra" in the comments this worked for me:
primaryKey function should return the variable name of primary key variable, not the value, so u should return "id" instead Ref: realm.io/docs/swift/latest/#primary-keys
Upvotes: 1