Swift access control on protocol conformance - ios

I have a private protocol defined in a file as below
private protocol testProtocol {
func testFunc1()
func testFunc2()
}
A public class conforms to the above protocol as follows
public class testClass : testProtocol {
func testFunc1() {}
func testFunc2() {}
}
As per apples documentation , the members of a public class get internal access control by default unless it is explicitly set to a different access control modifier.
The documentation also says that a type's conformance to a protocol with a lower access control will make the type's implementation of the protocol access control the same as that of the protocol. In this scenario since the type's access control is public and the protocols access control is private , the methods testfunc1 and testfunc2 should get an access control of private.
When the class is instantiated in a different source file and the methods are accessed as below , the compiler does not show an error which is not expected as the methods should be private as per the guidelines
var test: testClass = testClass()
test.testFunc1()
Is this expected behavior ? Am i missing something?

Apple Documentation says:
When you write or extend a type to conform to a protocol, you must ensure that the type’s implementation of each protocol requirement has at least the same access level as the type’s conformance to that protocol.
According to this I assume that implementing methods testFunc1 and testFunc2 with another access control modifier inside testClass just overrides that from protocol. If you use default protocol implementation of this methods like the following compiler will return error:
extension testProtocol {
func testFunc1() {}
func testFunc2() {}
}
As far as Swift is Protocol Oriented Language with replacing inheritance with protocols it's probably reasonable if you want to change protocol defined access level of function inside your custom class.

According to Apple's documentation:
When you write or extend a type to conform to a protocol, you must ensure that > the type’s implementation of each protocol requirement has at least the same > access level as the type’s conformance to that protocol.
Please be aware of the "at least" in the doc, it means that the as long as the access level of the type's implementation of the protocol requirements is higher or equal to the access level of the protocol, it will be ok. In your case, testFunc1 and testFunc2 from testClass have the default access level of internal, it is higher than access level of private. So actually the two methods in testClass get the access level of internal, and compiler won't treat it as en error.
We can change your code a little bit as follows:
fileprivate protocol TestProtocol {
func testFunc1()
func testFunc2()
}
public class TestClass : TestProtocol {
public func testFunc1() {}
public func testFunc2() {}
}
This piece of code will also compile without an error.

Related

Swift Concurrency: Conforming a 3rd party library to actor isolation

I am in the process of converting some code bases over to using Swift concurrency and am running into a few snags along the way.
The current project I'm working through has a few 3rd party libraries that it relies on, and in one of those libraries, there is a delegate protocol that requires some data values to be returned from its methods.
Here is an example of the type of delegate methods in the library:
public protocol FooDelegate: AnyObject {
func foo() -> CGFloat
}
I'm attempting to return some values from the implementation of the protocol like this:
extension ViewController: FooDelegate {
func foo() -> CGFloat { // <- Cannot satisfy requirement from protocol
view.bounds.height
}
}
Without any modification, the above is implicitly isolated to the MainActor and can not satisfy the requirement from the FooDelegate protocol.
One solution I've tried was to mark the function implementation with nonisolated:
extension ViewController: FooDelegate {
nonisolated func foo() -> CGFloat {
view.bounds.height // <- Cannot be referenced from a non-isolated context
}
}
This did not work though because it references the view controller's view. That results in the view being referenced from a non-isolated synchronous context. (There are also a few other issues with this since any values that are passed through into any of the delegate functions need to conform to Sendable to be able to be passed across actors).
My question is, is there a way to take a 3rd party library and extend it somehow so that it conforms to proper actor isolation without having to modify its source code?

Add Swift protocol conformance to Objective-C header and make it public

I've read along here and here about conforming to Swift protocols in Objective-C headers, and I'm not quite getting the behaviour I want - I'm also looking for a better understanding of how this all works. Here's my scenario.
I have a protocol in Swift:
PersonalDetailsProtocol.swift
#objc
protocol PersonalDetailsProtocol {
func doSomeWork()
}
I then have an Objective-C class with a header and implementation file
RegistrationPersonalDetails.h
#protocol PersonalDetailsProtocol; // Forward declare my Swift protocol
#interface RegistrationPersonalDetails : NSObject <PersonalDetailsProtocol>
#end
RegistrationPersonalDetails.m
#import "RegistrationPersonalDetails.h"
#implementation RegistrationPersonalDetails
- (void)doSomeWork {
NSLog(#"Working...");
}
#end
At this point everything compiles, although there is a warning in the RegistrationPersonalDetails.h file stating Cannot find protocol definition for 'PersonalDetailsProtocol'. Other than that warning, the issue I'm facing is I can't publicly call the doSomeWork method on an instance of RegistrationPersonalDetails.
The call site in Swift would look something like:
let personalDetails = RegistrationPersonalDetails()
personalDetails.doSomeWork()
but I get an error stating:
Value of type 'RegistrationPersonalDetails' has no member 'doSomeWork'
I get that the method isn't public, because it's not declared in the header file. But I didn't think it should have to be as long as the protocol conformance is public i.e. declared in the header file.
Can anyone point me on the right path here and offer an explanation? Or is this even possible? I can obviously rewrite the protocol in ObjC, but I just always try to add new code as Swift.
In pure objective-c, you cannot make a class conform to a protocol without importing it in the header. To make the use of a protocol private, the conformance shouldn't be declared in the header. It remains possible to call such a method using a cast however, but it should be done with caution because it's a little bit unsafe :
if ([anInstance respondToSelector:#selector(myProtocolMethod)])
[(id<MyProtocol>)anInstance myProtocolMethod];
I'm not familiar with Swift, but I think you can do the same this way (or something close to it) :
if let conformingInstance = anInstance as? MyProtocol
conformingInstance.myProtocolMethod
EDIT : To complete my first assertion, forward declarations can still be used in the header when you need to declare a method receiving or returning an instance conforming to that protocol :
#SomeProtocol;
// This is not possible
#interface MyClass : NSObject <SomeProtocol>
// But this is possible
#property (nonatomic) id<SomeProtocol> someProperty;
-(void) someMethod:(id<SomeProtocol>)object;
#end
In this document Apple clearly said that :
Forward declarations of Swift classes and protocols can be used only
as types for method and property declarations.
So it seems that the rule is the same whatever the protocol is an Objective-c protocol or a Swift protocol.

Swift Segmentation Fault with Non-Adoption of Extension

If I have a protocol, MyProtocol defined as:
protocol MyProtocol {
func myFunction() -> String
}
and I have a default implementation declared in an extension so that conformers can "optionally" implement the function:
extension MyProtocol {
func myFunction() -> String { return "" }
}
everything should work just dandy.
However, when a class conforms to that protocol and doesn't implement the functions, the compiler fails with Segmentation fault 11. Once the class implements the function, the error goes away and all is good with the world but it seems to defeat the purpose of defining default implementations in extensions.
Does anyone have any idea why this happens? Is it because the conforming class declares that it implements the methods so the compiler ignores what's written in the extension, can't find the methods and then crashes?
I also had a similar problem with protocol extensions and Segmentation fault 11.
In my case the problem was, that in the extension I put the mutating keyword before the function, but in the protocol there was no mutating. And instead on an error this lead to that Segmentation fault 11.
Maybe that helps a bit.

Cannot declare a public protocol extension with internal requirements

I am programming a media player app and created my own framework for managing all the player functionality. In this framework I have a public protocol called PlayerControllerType and an internal protocol _PlayerControllerType. In PlayerControllerType I have declared all the methods and properties, which should be accessible from outside the framework. In _PlayerControllerType I have defined a couple of properties, which are used by the concrete types implementing PlayerControllerType inside the framework. One of these types is PlayerController. Its declaration is as follows:
public class PlayerController<Item: Equatable>: NSObject, PlayerControllerType,
_PlayerControllerType, QueueDelegate
Now I want to provide a couple of default implementations for the classes in my framework, which conform to PlayerControllerType and the internal _PlayerControllerType, for example:
import Foundation
import MediaPlayer
public extension PlayerControllerType where Self: _PlayerControllerType, Item == MPMediaItem, Self.QueueT == Queue<Item>, Self: QueueDelegate {
public func setQueue(query query: MPMediaQuery) {
queue.items = query.items ?? []
}
}
This works as expected in Xcode 7 Beta 4. Yesterday I updated to Beta 6 and got this error:
"Extensions cannot be declared public because its generic requirement uses an internal type" (also see screenshot).
I find this error irritating. Of course no type outside of my framework benefits of this extension because it cannot access the internal protocol _PlayerControllerType, but it is very useful for the types inside my framework which implement both PlayerControllerType and _PlayerControllerType.
Is this just a bug in the Swift compiler or is this the intended behavior?
It's is pretty unfortunate that this doesn't work anymore because now I have to put these methods into a newly created base class for all my PlayerControllers.
Any help or feedback would greatly appreciated.
Kai
EDIT:
Here is a shortened example of the protocols and their extensions:
public protocol PlayerControllerType {
typealias Item
var nowPlayingItem: Item {get}
func play()
}
protocol _PlayerControllerType {
var nowPlayingItem: Item {get set}
}
public extension PlayerControllerType where Self: _PlayerControllerType {
/*
I want to provide a default implementation of play() for
all my PlayerControllers in my framework (there is more than one).
This method needs to be declared public, because it implements a
requirement of the public protocol PlayerControllerType.
But it cannot be implemented here, because this extension
has the requirement _PlayerControllerType. It needs this requirement,
because otherwise it cannot set the nowPlayingItem. I don't want to
expose the setter of nowPlayingItem.
I could make a base class for all PlayerControllers, but then I'm
restricted to this base class because Swift does not support
multiple inheritance.
*/
public func play() {
if nowPlayingItem == nil {
nowPlayingItem = queue.first
}
// Other stuff
}
}
You need to declare an access level of the _PlayerControllerType protocol as 'public'.
public protocol _PlayerControllerType {
// some code
}
According to (The Swift Programming Language - Access Control),
A public members cannot be defined as having an internal or private type, because the type might not be available everywhere that the
public variable is used. Classes are declared as internal by default,
so you have to add the public keyword to make them public.
A member (class/protocol/function/variable) cannot have a higher
access level than its parameter types and return type, because the
function could be used in situations where its constituent types are
not available to the surrounding code.

Typhoon - How to inject parameter which conforms to PROTOCOL instead of CLASS

I have class which represents logged user
public class User: NSObject {
init(authenticator: Authenticator) {
self.authenticator = authenticator
}
...
}
Its only initial arguments is object which conforms to Authenticator protocol
protocol Authenticator
{
func authenticate(login:String , password:String , handler: (result:AuthenticationResult)->() )
}
In my case the Auth object is instance of class BackendService
My typhoon assembly definition is:
public dynamic func user() -> AnyObject {
return TyphoonDefinition.withClass(User.self) {
(definition) in
definition.useInitializer("initWithAuthenticator") {
(initializer) in
initializer.injectParameterWith( self.backendService() )
}
}
}
Application cause runtime-error
'Method 'initWithAuthenticator' has 0 parameters, but 1 was injected. Do you mean 'initWithAuthenticator:'?'
If i change init method to 'initWithAuthenticator:' it crashes with
'Method 'initWithAuthenticator:' not found on 'PersonalMessages.User'. Did you include the required ':' characters to signify arguments?'
At the present time, it is necessary to add the '#objc' directive to Swift protocols to have them be available for dependency injection with Typhoon. Without it the objective-c runtime's introspection and dynamic dispatch features arent available and these are required.
Similarly, in the case of a class it must extend from NSObject or have the '#objc' directive, otherwise it will also use C++ style vtable dispatch and have (essentially) no reflection. In the case of private vars or methods, they must also have the 'dynamic' modifier.
While vtable dispatch is faster, it prevents runtime method interception which many of Cocoa's most powerful features, such as KVO rely on. So both paradigms are important and its impressive that Swift can switch between them. In the case of protocols though, using the '#objc' directive is a little unfortunate as it implies a 'legacy' behavior. Perhaps 'dynamic' would've been better?
dynamic protocol Authenticator //Not supported but would've been a nicer than '#objc'?
Or perhaps another way to imply that dynamic behavior is required would be to have the protocol extend the NSObject protocol, however this does not work. So using '#objc' is the only choice.
Meanwhile, for classes the requirement to extend NSObject isn't really noticible as far as working with Cocoa/Touch apps goes.

Resources