15

I'm trying to convert over my Objective-C to Swift - a little confused on the error here and how to take care of it. I've been reading through the documentation but still confused - this was generated from a converter. Anyone have any ideas?

Objective-C
- (id) init
{
    self = [super init];

    if (!self)
        return nil;

     self.cmRequestsQuery = [[NSMutableArray alloc] initWithCapacity:5];
     self.cmQueryIsRuning = NO;
     self.requestCounter = 0;
     self.serverOfflineOrBadResponse = NO;
     self.userWasLoggedIn = NO;
     self.needToSendPushNotiToken = NO;
     self.noInternetConection = NO;
     self.needToUpdateToken = NO;

    [[reqOperationManager sharedManager] setDelegate:self];

    return self;
}


Swift
func init() -> AnyObject {
    self = super()
    if !self {
        return nil
    }
    self.cmRequestsQuery = NSMutableArray(capacity: 5)
    self.cmQueryIsRuning = false
    self.requestCounter = 0
    self.serverOfflineOrBadResponse = false
    self.userWasLoggedIn = false
    self.needToSendPushNotiToken = false
    self.noInternetConection = false
    self.needToUpdateToken = false
    reqOperationManager.sharedManager().setDelegate(self)
    return self
}
user2836292
  • 305
  • 2
  • 5
  • 13
  • That took care of one issue, it still complains at `func init() -> AnyObject {` with "Expected identifier in function declaration. Removing the "func" part then brings the error "Consecutive declarations on a line must be separated by ';'. I believe it is from the AnyObject aspect. – user2836292 Oct 11 '15 at 18:03
  • See [This link](http://stackoverflow.com/questions/24302288/how-to-write-init-method-in-swift) – eliasRuizHz Oct 11 '15 at 18:18

2 Answers2

27

In Swift init methods have no func keyword and no return value and the point to call super is different.

init() {

First initialize all instance variables.

self.cmRequestsQuery = NSMutableArray(capacity: 5)
self.cmQueryIsRuning = false
self.requestCounter = 0
self.serverOfflineOrBadResponse = false
self.userWasLoggedIn = false
self.needToSendPushNotiToken = false
self.noInternetConection = false
self.needToUpdateToken = false

Then call super – if required – to get the instance.

super.init()

Then call the methods which use self

reqOperationManager.sharedManager().setDelegate(self)

That's it.

}

In some cases you have to add the override keyword before init().

For more details please read the chapter about Initialization in the Swift Language Guide. It's worth it.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • The "Initialization in the Swift Language Guide" mentioned at the end of the answer: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html – AJP Jun 28 '16 at 13:59
0

I had this problem because I was trying to import the swift header (import "ProjectName-swift.h") in my swift class.

smukamuka
  • 1,442
  • 1
  • 15
  • 23