Understanding Downcasting on Swift

Asked 2 years ago, Updated 2 years ago, 32 views

I have a question about downcasting.
Inherit the class as follows:

class CNMutableGroupKai:CNMutableGroup{
    varicon: String=""
}

and

var groupData=group.mutableCopy() as!CNMutableGroupKai

I want to downcast with , but I fail.

I think the fundamental thing is probably wrong.
May I speak to you?

swift

2022-09-30 18:17

1 Answers

mutableCopy() creates replication for that instance. CNMutableGroupKai does not override mutableCopy(), so the parent class implementation is called to create replication for CNMutableGroup.

It is illegal to cast a CNMutableGroup to CNMutableGroupKai, so crashing with as! is a legitimate behavior.

The workaround is to implement mutableCopy(), but

class CNMutableGroupKai:CNMutableGroup{
    varicon: String=""

    override func mutableCopy()->AnyObject{
        let copy = CNMutableGroupKai()
        // Identifier is read-only and cannot be copied
        // copy.identifier=self.identifier
        copy.name = self.name
        copy.icon=self.icon
        return copy
    }
}

Adding your own properties to CNMutableGroup does not even save them in the CNContactStore (CNMutableGroup is a class to manipulate and store group information) and seems to be an undesirable behavior.

If you want a contact book group to have an icon to show it, wouldn't it be better to create a wrapper structure than to extend the Contacts framework class?

structureGroupData{
    varicon:UIimage
    var group —CNGroup
}


2022-09-30 18:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.