Coming from .Net, I am trying to learn Swift3/iOS and got puzzled by the following apparent inconsistent behaviour of optional protocol members. I suspect its something got to do with the juggling between objc/swift words, but what am I missing here actually?
// In playground, given below:
#objc protocol SomePtotocol {
#objc optional func someMethod()
}
class SomeDelegate: NSObject, SomePtotocol {
}
class SomeController: NSObject {
var delegate: SomePtotocol = SomeDelegate()
}
// This works and compiles without error
let controller = SomeController()
controller.delegate.someMethod?() // No error, typed as '(() -> ())?'
// But this fails to even compile ??
let delegate = SomeDelegate()
delegate.someMethod?() // Error: 'SomeDelegate' has no member 'someMethod'
I would expect either both to fail or both pass, so if someone could please enlighten me on this anomaly.
The difference between the two blocks of code is the type of the variable involved.
In the first block, delegate is explicitly typed as SomePtotocol, and this protocol defines the someMethod method, so your statement is valid.
In the second block, delegate is implicitly typed as SomeDelegate and although this class conforms to SomePtotocol, it doesn't implement the optional method someMethod, so you get an error.
If you change your second block to
let delegate: SomePtotocol = SomeDelegate()
delegate.someMethod?()
which is equivalent to the first block, then there is no error.
Related
Consider code like this:
protocol SomeProtocol {
var something: Bool { get set }
}
class SomeProtocolImplementation: SomeProtocol {
var something: Bool = false {
didSet {
print("something changed!")
}
}
}
protocol MyProtocol {
var myProperty: SomeProtocol { get }
}
class MyClass: MyProtocol {
var myProperty: SomeProtocol = SomeProtocolImplementation() {
didSet {
print("myProperty has changed")
}
}
}
var o: MyProtocol = MyClass()
o.myProperty.something = true
This code doesn't compile with error:
error: cannot assign to property: 'myProperty' is a get-only property
o.myProperty.something = true
~~~~~~~~~~~~ ^
Why? My property is of type of SomeProtocolImplementation, which is class type so it should be possible to modify it's inner property using reference to myProperty.
Going further, after modifying myProperty definition so that it looks like that:
var myProperty: SomeProtocol { get set }
something weird happens. Now the code compile (not a surprise), but the output is:
something changed!
myProperty has changed
So at this point SomeProtocolImplementation starts behaving like a value type - modyifing it's internal state causes that the "didSet" callback for myProperty is triggered. Just as SomeProtocolImplementation would be struct...
I actually find the solution, but I want also understand what's going on. The solution is to modify SomeProtocol definition to:
protocol SomeProtocol: class {
var something: Bool { get set }
}
It works fine, but I'm trying to understand why it behaves like this. Anybody able to explain?
First read what Class Only Protocol is. Concentrate on the note section that says:
Use a class-only protocol when the behavior defined by that protocol’s requirements assumes or requires that a conforming type has reference semantics rather than value semantics.
Above quote should get you the idea.
You are trying to get the behavior of reference type for your SomeProtocol's conforming class (i.e. SomeProtocolImplementation). You want to be able to change the value of something in future. So basically you are directing to the above quoted sentence.
If you need more clarification please consider the following more meaningful design where I changed the naming for convenience:
protocol Base: class {
var referenceTypeProperty: Bool { get set }
// By now you are assuming: this property should be modifiable from any reference.
// So, instantly make the protocol `Class-only`
}
class BaseImplementation: Base {
var referenceTypeProperty: Bool = false {
didSet {
print("referenceTypeProperty did set")
}
}
}
protocol Child {
var valueTypeProperty: Base { get }
// This property shouldn't be modifiable from anywhere.
// So, you don't need to declare the protocol as Class-only
}
class ChildImplementation: Child {
var valueTypeProperty: Base = BaseImplementation() {
didSet {
print("valueTypeProperty did set")
}
}
}
let object: Child = ChildImplementation()
object.valueTypeProperty.referenceTypeProperty = true
Any class that can provide behavior useful to other classes may declare a programmatic interface for vending that behavior anonymously. Any other class may choose to adopt the protocol and implement one or more of its methods, thereby making use of the behavior. The class that declares a protocol is expected to call the methods in the protocol if they are implemented by the protocol adopter.
Protocol Apple Documentation
When you try to 'set' value to a variable that is read-only - you are trying to change the protocol's implementation. Conforming classes can only consume information from protocol. In Swift we can write protocol extensions where we can have alternative methods for the protocol.
In short think of computed variables as functions. You are technically trying to change a function in this case.
I actually find the solution, but I want also understand what's going on.
I was just about to tell you to make SomeProtocol a class protocol, but you already figured that out. — So I'm a little confused as to what you don't understand.
You understand about reference types and value types, and you understand about class protocols and nonclass protocols.
Well, as long as SomeProtocol might be adopted by a struct (it's a nonclass protocol), then if you are typing something as a SomeProtocol, it is a value type. The runtime isn't going to switch on reference type behavior just because the adopter turns out to be a class instance; all the decisions must be made at compile time. And at compile time, all the compiler knows is that this thing is a SomeProtocol, whose adopter might be a struct.
I have a class that conforms to an Objective-C protocol and has a function with the same name as one of it's parameter types.
class MessageDataController: NSObject, MCOHTMLRendererDelegate {
#objc func MCOAbstractMessage(msg: MCOAbstractMessage!, canPreviewPart part: MCOAbstractPart!) -> Bool {
return false
}
}
This causes Xcode to give the error
"Use of undeclared type 'MCOAbstractMessage'"
for using MCOAbstractMessage as both the function name and a parameter type. It doesn't give an error if I change the function name to abstractMessage or similar. I think the issue is related to this question and/or this issue but am unsure how to resolve. My project's header file is correctly configured to use MailCore2.
Tried changing the declaration to:
#objc(MCOAbstractMessage:canPreviewPart:) func abstractMessage(msg: MCOAbstractMessage!, canPreviewPart part: MCOAbstractPart!) -> Bool
which gives the error
"~/src/project/MessageDataController.swift:11:52: Objective-C method 'MCOAbstractMessage:canPreviewPart:' provided by method 'abstractMessage(:canPreviewPart:)' conflicts with optional requirement method 'MCOAbstractMessage(:canPreviewPart:)' in protocol 'MCOHTMLRendererDelegate'"
This may be solved by using the fully-qualified type name in the parameter list. I'm not familiar with the library you are using, but the suggestion below assumes that the type MCOAbstractMessage is declared in a module called MCO. Prepend MCO. to the type name.
class MessageDataController: NSObject, MCOHTMLRendererDelegate {
#objc func MCOAbstractMessage(msg: MCO.MCOAbstractMessage!, canPreviewPart part: MCOAbstractPart!) -> Bool {
return false
}
}
I tested this by adding a method called Array to one of my classes. Sure enough it threw compiler errors everywhere else that I had used Array as a type. I prefixed all of those as Swift.Array and all was well.
If you want a shorter version, use a typealias,
Is it possible to overload a protocol function and have the correct definition be called when dealing directly with the protocol type?
Here's some code to illustrate the issue
protocol SomeProtocol {
func doSomething<T>(obj: T)
}
class SomeClass : SomeProtocol {
func doSomething<T>(obj: T) {
print("Generic Method")
}
func doSomething(obj: String) {
print(obj)
}
}
let testClass = SomeClass()
testClass.doSomething("I will use the string specific method")
(testClass as SomeProtocol).doSomething("But I will use the generic method")
Edit: To clarify, the code works. I want to know why both calls do not use the string specific method.
Double Edit: Removed the intermediary dispatch class for a simpler example
Is this a bug, current limitation, or intended functionality? If this is intended, can someone please explain why?
Swift 2.0, Xcode 7.0
Answer
You can't overload a protocol function and expect the correct definition to be called. This is because the definition to call is picked at compile time. Since the compiler doesn't know the concrete type, it chooses the only definition known at compile time, doSomething<T>.
I tested your code here http://swiftstub.com/ and it worked fine.
First it prints "I will use the specific method" and then "Generic Method":
I will use the specific methodGeneric Method
I have a swift protocol:
#objc protocol SomeDelegate {
optional func myFunction()
}
I one of my classes I did:
weak var delegate: SomeDelegate?
Now I want to check if the delegate has myFunction implemented.
In objective-c I can do:
if ([delegate respondsToSelector:#selector(myFunction)]) {
...
}
But this is not available in Swift.
Edit: This is different from: What is the swift equivalent of respondsToSelector? I focus on class protocols not on classes.
How do I check if my delegate has an optional method implemented?
Per The Swift Programming Language:
You check for an implementation of an optional requirement by writing
a question mark after the name of the requirement when it is called,
such as someOptionalMethod?(someArgument). Optional property
requirements, and optional method requirements that return a value,
will always return an optional value of the appropriate type when they
are accessed or called, to reflect the fact that the optional
requirement may not have been implemented.
So the intention is not that you check whether the method is implemented, it's that you attempt to call it regardless and get an optional back.
You can do
if delegate?.myFunction != nil {
}
I've found it successful to add an extension to the protocol that defines basic default implementation and then any class implementing the protocol need only override the functions of interest.
public protocol PresenterDelegate : class {
func presenterDidRefreshCompleteLayout(presenter: Presenter)
func presenterShouldDoSomething(presenter: Presenter) -> Bool
}
then extend
extension PresenterDelegate {
public func presenterDidRefreshCompleteLayout(presenter: Presenter) {}
public func presenterShouldDoSomething(presenter: Presenter) -> Bool {
return true
}
}
Now any class needing to conform to the PresenterDelegate protocol has all functions already implemented, so it's now optional to override it's functionality.
I normally implement it like this:
self.delegate?.myFunction?()
if the delegate methods returns a value:
var result = defaultValue
if let delegateResult = self.delegate?.myFunction?() else {
result = delegateResult
}
//do something with result
Declaration
#objc public protocol nameOfDelegate: class {
#objc optional func delegateMethod(_ varA: int, didSelect item: Item)
}
Implimetation
if let delegate = nameOfDelegate {
delegate.delegateMethod?(1, didDeselect: node)
}
I know this question is 5 years old, but I would like to share what I found. My solution works as of 2021, XCode 11+, Swift 5.
Say I wanted to figure out whether the function sign follows the GIDSignInDelegate protocol and also know what all the optional functions for GIDSignInDelegate are.
I have to look at the source code of the GIDSignIn module, and this is how.
Click on jump to definition on the main module that is imported. It will lead to a file like this:
Copy the entire line, import GoogleSignIn.GIDSignIn and paste it in the ViewController or whatever .swift file (doesn't really matter).
Within the swift file, right click on the GIDSignIn part of the import line GoogleSignIn.GIDSignIn and jump to definition. This will lead you to the actual module with all the available functions (the functions not marked optional may be stubs, which are required functions in the delegate protocol):
From this file, I can see that there is a sign function that is a stub of GIDSignInDelegate and an optional sign function that is implemented as a method overload.
I used this for GIDSignInDelegate, but you can use the same method to figure out whether any function follows any delegate protocol.
Exploring Swift headers I'm seeing this pattern used by Apple, in particular the init declaration of the following struct HAS NO IMPLEMENTATION.
Obviously the init() implementation is hidden somehow, since it's Apple stuff, but I was trying to understand how.
This is only an example, but it seems a common behavior in the headers
struct AutoreleasingUnsafePointer<T> : Equatable, LogicValue {
let value: Builtin.RawPointer
init(_ value: Builtin.RawPointer) // <---- how is it possible? where is the implementation?
func getLogicValue() -> Bool
/// Access the underlying raw memory, getting and
/// setting values.
var memory: T
}
I know that it is possible to declare a protocol plus a class extension, doing this it's possible to "hide" the implementation from the class declaration and moving it elsewhere
class TestClass :TestClassProtocol
{
// nothing here
}
protocol TestClassProtocol
{
func someMethod() // here is the method declaration
}
extension TestClass
{
func someMethod() // here is the method implementation
{
println("extended method")
}
}
But it's different from what I have seen in the Apple Headers, since the method "declaration" is inside the "class", not inside the "protocol". if I try to put the method declaration inside the class TestClass, however, I have two errors (function without body on the class, and invalid redeclaration on the extension)
In Objective C this was "implicit", since the method declaration was in the .h and the implementation in the .m
How to do the same in Swift?
I think the explanation is very simple. What you see in Xcode is not actually a valid Swift
code.
It's a result from an automatic conversion of an Obj-C header into Swift-like code but it's not compilable Swift.