简体   繁体   中英

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

+(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

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

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

In your 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]? respectively. In case NSDictionary is nil then use guard let for optional checking

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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