Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conform to Protocol and Keep Property Private

I need to use a protocol property in the conforming class as a private. But the compiler refuses that. How can I implement that?

protocol ProtocolX: class {
    var x: Int { get set }

    func performAnyActionOnX()
}

extension ProtocolX {
    func performAnyActionOnX() {
        x = 5
        print(x)
    }
}

class A: ProtocolX {
    private var x:Int = 7
}

Thanks.

like image 714
SamehDos Avatar asked May 17 '17 08:05

SamehDos


People also ask

CAN protocol have stored property?

A protocol can require any conforming type to provide an instance property or type property with a particular name and type. The protocol doesn't specify whether the property should be a stored property or a computed property—it only specifies the required property name and type.

Can Objective C protocols have properties?

Protocols are used in Objective-C to declare a set of methods and properties for a class to implement.

What is gettable and settable in Swift?

Gettable properties are values that you can read. Settable properties are values that you can edit, but not read. If you have a property that's both gettable and settable, you can read and edit the value.

Can a protocol conform to another protocol?

One protocol can inherit from another in a process known as protocol inheritance. Unlike with classes, you can inherit from multiple protocols at the same time before you add your own customizations on top. Now we can make new types conform to that single protocol rather than each of the three individual ones.


1 Answers

As @TheAppMentor mentioned, there seems to be no exact solution to this problem as of Swift 4.

There are, however, two approximate solutions:

1.)

Since a protocol in Swift has the access level of internal by default, make the variable also internal. In order for internal to be enforced by the compiler, move the protocol, the class and all of their consumers (users) to a separate module (framework).

/* internal */ protocol ProtocolX: class {
    var x: Any { get set }

    func performAnyActionOnX()
}

extension ProtocolX {
    func performAnyActionOnX() {}
}

/* internal */ class A: ProtocolX {
    internal var x: Any = 0
}

2.)

Give the protocol the access level of private and the variable the access level of fileprivate. In order for the private protocol to be accessible, move the protocol, the class and all of their consumers to the same source file.

private protocol ProtocolX: class {
    var x: Any { get set }

    func performAnyActionOnX()
}

extension ProtocolX {
    func performAnyActionOnX() {}
}

class A: ProtocolX {
    fileprivate var x: Any = 0
}
like image 100
Gary Avatar answered Sep 19 '22 06:09

Gary