Ramcharan Reddy Ramcharan Reddy - 3 months ago 14
iOS Question

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

Answer

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

Comments