如何在Swift类中重写Objective-C类的抽象类级别方法?

Ramcharan Reddy

我有一个Objective-c类级别的方法,如下所示

+(SObjectData *)createSObjectData:(NSDictionary *)soupDict{
@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You Must override %@ in a sub class",NSStringFromSelector(_cmd)],userInfo:nil]
}

我想在这个在子类中重写此方法迅速

我尝试了以下

override class func createSObjectData(soupDict:NSDictionary)->SObjectData
{
//some code
}

但是它给我一个错误

方法不会覆盖超类中的任何方法

哈里萨曼

首先修复方法中的语法错误,使其看起来像

+(SObjectData *)createSObjectData:(NSDictionary *)soupDict
{
    @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You Must override %@ in a sub class",NSStringFromSelector(_cmd)]userInfo:nil];
}

在您的BaseClass.h中

+(SObjectData *)createSObjectData:(NSDictionary *)soupDict;

在您的BaseClass.m中

+(SObjectData *)createSObjectData:(NSDictionary *)soupDict
{
    @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You Must override %@ in a sub class",NSStringFromSelector(_cmd)]userInfo:nil];
}

在你的快速课堂上

override class func createSObjectData(soupDict: [NSObject : AnyObject]!) -> SObjectData
{
    return SObjectData();
}

更新:

如果您确定字典永远不会为零NSDictionary * _Nonnull,则NSDictionary可以为零NSDictionary * _Nullable,并将swift代码分别更新为soupDict: [NSObject : AnyObject]soupDict: [NSObject : AnyObject]?如果NSDictionary为零,则guard let用于可选检查

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章