I wanna subclass the PFUser object in swift.
I also want to declare my own variables. The Parse documentation on subclassing do not cover PFUser at this point.
Parse documentation on subclassing PFObject:
class Armor : PFObject, PFSubclassing {
class func load() {
self.registerSubclass()
}
class func parseClassName() -> String! {
return "Armor"
}
}
BridgingHeader.h:
#import <Parse/Parse.h>
#import <Parse/PFObject+Subclass.h>
User.swift:
import Foundation
class User : PFUser, PFSubclassing {
override class func load() {
self.registerSubclass()
}
//My variables
dynamic var firstname: String
dynamic var lastname: String
}
DONT´T include this snippet when subclassing PFUser:
class func parseClassName() -> String! {
return "User"
}
In Swift 2.0 You not need to implement PFSubclassing Protocol for Subclassing PFUser.
Just create normal subclass like this;
class ParseUser: PFUser {
#NSManaged var name: String?
#NSManaged var surname: String?
#NSManaged var phoneNumber: String?
override class func initialize() {
struct Static {
static var onceToken : dispatch_once_t = 0;
}
dispatch_once(&Static.onceToken) {
self.registerSubclass()
}
}
Related
I've using Kotest recently and I hadn't had any issues, but recently I was trying some annotations for dependency injection so to simplify the problem I created some basic classes with some methods that just print some messages, just for the sake of learning how to use Kotest and Mockk, but during the testing, I ran with the exception that the variable hasn't been initialized when trying to run the test.
These are my classes
class DefaultClass : AbstractClass() {
private val anotherClass: AnotherClass = AnotherClass()
fun testMethod(value: String): String {
val normalizeValue = value.trim().lowercase().replace(Regex("[^ A-Za-z\\d]*"), "")
return runBlocking {
anotherClass.someOtherMethod()
callsProtectedMethod(normalizeValue)
}
}
private suspend fun callsProtectedMethod(value: String) = coroutineScope {
println("Original method")
returnDefaultString(value)
}
}
AnotherClass
class AnotherClass {
fun someOtherMethod(): Unit {
println("SomeOtherMethod original")
}
}
Test
class DefaultClassTest : FunSpec({
context("Testing DefaultClass") {
#MockK
lateinit var anotherClass: AnotherClass
#OverrideMockKs
lateinit var defaultClass: DefaultClass
beforeContainer {
MockKAnnotations.init(this)
}
test("testing mocks") {
defaultClass.testMethod("some method")
}
}
I've changed the initialization to beforeTest, taken it out of the context, and also use beforeContainer, beforeTest, beforeSpec, but none of these work... every time I still get lateinit property defaultClass has not been initialized
So, I recreated the same test using JUnit and I don't have this issue.
class DefaultClassJUnitTest {
companion object {
#MockK
lateinit var anotherClass: AnotherClass
#OverrideMockKs
lateinit var defaultClass: DefaultClass
#BeforeAll
#JvmStatic
fun setup() {
MockKAnnotations.init(this)
}
}
#Test
fun `Testing with JUnit`() {
every { anotherClass.someOtherMethod() } answers {
println("Mocking another class")
}
val value = defaultClass.testMethod("some method")
}
}
So I'm pretty sure that I'm doing something wrong when using Kotest. I hope anyone might help me, thanks...
I think MockK is probably not looking for variables defined within function scopes. If you want to use the annotations, you likely have to move them to the companion object, like this:
class DefaultClassTest : FunSpec({
context("Testing DefaultClass") {
beforeContainer {
MockKAnnotations.init(this)
}
test("testing mocks") {
defaultClass.testMethod("some method")
}
}
}) {
companion object {
#MockK
lateinit var anotherClass: AnotherClass
#OverrideMockKs
lateinit var defaultClass: DefaultClass
}
}
I have some abstract with generic type:
interface Abstract<T> {
val dataHolder: T
}
class AbstractImplA : Abstract<String> {
override val dataHolder = "Test"
}
class AbstractImplB : Abstract<Int> {
override val dataHolder = 1
}
Now I want to create open class that persist this data:
open class Base<T>(private val abstract: Abstract<T>) {
val data : T get() = abstract.dataHolder
// ...
}
now for child class I have to explicitly specifiy generic type of Abstract:
class ClassA : Base<String>(AbstractImplA()) {
fun foo() {
assertEquals("Test", data)
}
}
class ClassB : Base<Int>(AbstractImplB()) {
fun foo() {
assertEquals(1, data)
}
}
I wander if Kotlin can infere this type.
Passing wrong generic type causes Type mismatch error ex. class ClassB : Base<Boolean>(AbstractImplB())
Can I somehow write it like this?:
class ClassB : Base(AbstractImplB()) {
fun foo() {
assertEquals(1, data)
}
}
In java, i hava code like below:
public class GenericTest {
private static final GenericTest instance = new GenericTest();
IRequirement requirement;
public static GenericTest getInstance() {
return instance;
}
public class ClassA {}
public interface InterfaceA {}
public void init(IRequirement requirement){
this.requirement = requirement;
}
public interface IRequirement {
<T extends ClassA & InterfaceA> T supply();
}
class ClassB {
void doSomeThing() {
ClassA a = requirement.supply();
InterfaceA ia = requirement.supply();
}
}
}
I can get ClassA or InterfaceA instance according to my needs.
But in kotlin, same codes like below:
open class ClassA(val name: String) {
fun function1() {}
fun function2() {}
}
interface InterfaceA {
fun iFunction1()
}
class ModuleX private constructor() {
var requirement: IRequirement? = null
companion object {
val instance = ModuleX()
}
fun init(requirement: IRequirement) {
instance.requirement = requirement
}
interface IRequirement {
fun <T> supply(): T where T : ClassA, T : InterfaceA
}
}
object ClassB {
inline fun <reified T> doSomeThing() where T : ClassA, T : InterfaceA{
val require = ModuleX.instance.requirement?.supply<T>()
require?.function1()
require?.iFunction1()
}
fun doAnotherThing() {
// IDE give an error when calling supply()
val require = ModuleX.instance.requirement?.supply()
require?.function1()
require?.iFunction1()
}
}
I must specify the actual type of the generic, or use the generic method, otherwise I will not be able to use the IRequirement in the code above, such as in ClassB.doAnotherThing() where IDE give an error "Type inference failed: Not enough information to infer parameter T in fun supply( ): T where T : InterfaceAPlease specify it explicitly."
My question is: In my module, it is required to provide a class that extends ClassA and implements InterfaceAd, but the module does not know the exact type of the class because it is outside the module. How should I use generics in this case?
fun doAnotherThing() {
val require: Any? = ModuleX.instance.requirement?.supply()
if (require != null) {
(require as ClassA).function1()
(require as InterfaceA).iFunction1()
}
}
I'm trying to use a Swift object as a key in an NSMutableDictionary. I've implemented hashValue and equality as usual and it works in a native Swift dict. But NSMutableDictionary never calls my hash function. What am I missing?
public final class Holder : Hashable, NSCopying
{
var val : Int = 0
public init( _ val : Int ) { self.val = val }
public var hashValue: Int {
return val
}
#objc public func copyWithZone(zone: NSZone) -> AnyObject {
return self
}
}
public func == (lhs: Holder, rhs: Holder) -> Bool {
return lhs.val==rhs.val
}
//var dict = Dictionary<Holder,String>()
var dict = NSMutableDictionary()
dict[ Holder(42) ]="foo"
dict[ Holder(42) ] // NSMutableDictionary will not call my hash function, returns nil here.
ANSWER:
I had to implement explicitly hash() and isEqual() like so:
#objc public func hash() -> Int {
return hashValue
}
#objc public func isEqual( obj : AnyObject ) -> Bool {
return (obj as? Holder)?.val == val
}
NSDictionary uses the hash and isEqual methods from NSObjectProtocol:
#objc var hash: Int { return hashValue }
#objc func isEqual(o: AnyObject?) -> Bool { return o as? Holder == self }
// ...
dict[ Holder(42) ] = "foo"
dict[ Holder(42) ] // returns "foo"
However, if possible I would recommend sticking with a Swift dictionary [Holder:String], as you tried previously.
I would like to access the scope of the calling class when creating an "anonymous inner class"
in Kotlin. What would be the equivalent of Java's OuterScope.this syntax? example :
open class SomeClass {
open fun doSomething() {
// ...
}
}
class MyClass {
fun someFunc() {
object : SomeClass() {
override fun doSomething() {
super<SomeClass>.doSomething()
// Access the outer class context, in Java
// this would be MyClass.this
}
}
}
}
this#MyClass
JFYI:
the same syntax for access to receiver of extension function:
fun MyClass.foo() {
// in some nested thing:
this#foo
//...
}
Kotlin Reference: This expressions
in my case i accessed it like : this#MainActivity
class MainActivity : AppCompatActivity() {
inner class Anon : Observer<PagedList<ApplicationUsers>> {
override fun onChanged(pagedList: PagedList<ApplicationUsers>?) {
Toast.makeText(this#MainActivity, "hello", Toast.LENGTH_SHORT).show()
}
}
}