Skip to content

Instantly share code, notes, and snippets.

@mattrubin
Last active August 12, 2017 21:13
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattrubin/93d25d7769c1b3e664d8 to your computer and use it in GitHub Desktop.
Save mattrubin/93d25d7769c1b3e664d8 to your computer and use it in GitHub Desktop.
Swift weak var of protocol type (No @objc required)
import UIKit
// A swift protocol can apply to a class, struct, or enum,
// but only a reference type can be stored in a `weak` var,
// so a weak var cannot be of a typical protocol type.
protocol MyProcotol {
}
class MyViewControllerWithError: UIViewController {
// ERROR: 'weak' cannot be applied to non-class type 'MyProtocol'
weak var delegate: MyProcotol?
}
// Swift protocols can be declared to only apply to class types,
// so that any value conforming to the protocol must be a class object.
// This allows the class protocol to be used as the type of a weak var.
protocol MyDelegate: class {
// ...
}
class MyViewController: UIViewController {
weak var delegate: MyDelegate? // This compiles! 😄🎉
}
// A class can be declared which conforms to the class protocol,
// but a struct cannot declare a class protocol without causing
// a compiler error:
class MyClass: MyDelegate {
}
// ERROR: Non-class type 'MyStruct' cannot conform to class protocol 'MyDelegate'
struct MyStruct: MyDelegate {
}
// The @objc keyword on a protocol implicitly makes it a class protocol,
// so an @objc protocol cannot be applied to a value type,
// but can be used as the type of a weak var.
@objc protocol MyObjCProtocol {
}
class MyClass2: MyObjCProtocol {
}
// ERROR: Non-class type 'MyStruct2' cannot conform to class protocol 'MyObjCProtocol'
struct MyStruct2: MyObjCProtocol {
}
@mattrubin
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment