Maria
Maria

Reputation: 765

Swift delegate.

In Objective-C I can make something like this:

@property (nonatomic, weak) id<SomeCustomProtocol> someObject;

How to make this in swift? I tried this:

let someObject: AnyObject, SomeCustomProtocol = ....;

And it does not work.

Upvotes: 1

Views: 225

Answers (4)

James Rochabrun
James Rochabrun

Reputation: 4377

Some things to take in consideration when creating a delegate property is:

  • Use the weak keyword to avoid retain cycles
  • Set the property as an optional type of your protocol

for example:

//Protocol
protocol SomeProtocolDelegate: class {
func doSomething()
}

weak var delegate: SomeProtocolDelegate?

Here is a more complete and very useful implementation.

https://medium.com/compileswift/implementing-delegates-in-swift-step-by-step-d3211cbac3ef#.vvdx9admt

Upvotes: 0

user546719
user546719

Reputation:

The correct way to declare a delegate in Swift is:

weak var delegate: SomeCustomDelegate?

Swift uses ARC for memory management hence it's still susceptible to retain cycles.

Read a good reference to learn more.

Upvotes: 4

Nirav Gadhiya
Nirav Gadhiya

Reputation: 6342

It should be like :

 var delegate: SomeCustomProtocol?

Find more guidance from here

Upvotes: 3

Cy-4AH
Cy-4AH

Reputation: 4585

let someObject:SomeCustomProtocol = ....;

Upvotes: 2

Related Questions