Last active
August 12, 2017 21:13
-
-
Save mattrubin/93d25d7769c1b3e664d8 to your computer and use it in GitHub Desktop.
Swift weak var of protocol type (No @objc required)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference: The Swift Programming Language: Class-Only Protocols