- (id) from Obj-C Lib in Swift?

2019-09-02 01:10发布

问题:

At first, I'm very very bad at Obj-C (don't like the syntax), but now with Swift I love iPhone developing :D

Here is my problem, I try to work with a Obj-C Library (xmppframework), but when I try to initialize the XMPPRoster the required Method isn't available...

Objective-C usage:

xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] initWithInMemoryStore];  
xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:xmppRosterStorage];

But within my Swift Class the Method "initWithRosterStorage" isn't available :(

Swift:

var jabberRosterStorage: XMPPCoreDataStorage = XMPPCoreDataStorage()
var jabberRoster:XMPPRoster = XMPPRoster(....)

XMPPRoster.m:

- (id)initWithRosterStorage:(id <XMPPRosterStorage>)storage
{
    return [self initWithRosterStorage:storage dispatchQueue:NULL];
}

Maybe Swift has problem with (id) because in Swift I think it's now AnyObject

回答1:

Try initializing it like this in Swift:

var jabberRosterStorage: XMPPCoreDataStorage, XMPPRosterStorage = XMPPCoreDataStorage()

var jabberRoster: XMPPRoster = XMPPRoster(rosterStorage: jabberRosterStorage)

Swift will convert the [[Class alloc] initWithVar:variable] to Class(var: variable).

Reference