简体   繁体   English

如何在swift类中覆盖objective-c类的抽象类级方法?

[英]How to override an abstract class level method of an objective-c class in a swift class?

I have an Objective-c class level method as follows 我有一个Objective-c类级别方法如下

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

I want to override this method in a subclass of this in swift 我想在swift的子类中重写此方法

I tried the following 我尝试了以下内容

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

But its is giving me an error that 但它给了我一个错误

method does not override any method from super class 方法不会覆盖超类中的任何方法

First fix syntax error in the method and make it look like 首先修复方法中的语法错误并使其看起来像

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

In your BaseClass.h 在你的BaseClass.h中

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

In your BaseClass.m 在你的BaseClass.m中

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

In your swift class 在你的快速课堂上

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

Update: 更新:

If your are sure the dictionary is never nil use NSDictionary * _Nonnull on the other had if NSDictionary can be nil use NSDictionary * _Nullable and update the swift code to soupDict: [NSObject : AnyObject] or soupDict: [NSObject : AnyObject]? 如果您确定字典永远不会使用NSDictionary * _Nonnull另外如果NSDictionary可以使用NSDictionary * _Nullable并将swift代码更新为soupDict: [NSObject : AnyObject]soupDict: [NSObject : AnyObject]? respectively. 分别。 In case NSDictionary is nil then use guard let for optional checking 如果NSDictionary为nil,则使用guard let进行可选检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM