Conform to Protocol and Keep Property Private - swift

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.

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
}

Since protocol's properties always have the same access level as your protocol has you can create a separate class where you can apply fileprivate level to them e.g.:
public class Props {
fileprivate var x: Int = 0
}
public protocol ProtocolX: class {
var privateProps: Props { get }
}
extension ProtocolX {
public func performAnyActionOnX() {
privateProps.x = 5
print(privateProps.x)
}
}
public class A: ProtocolX {
public let privateProps = Props()
public init() {
privateProps.x = 7
}
}
As you can see x has fileprivate access level so it can be accessible in ProtocolX extention and A class implementation only so it behaves as private and you can't change privateProps variable of class A and access to x outside:
let a = A()
a.performAnyActionOnX()
// Prints: 5
let x = a.privateProps.x
// error: 'x' is inaccessible due to 'fileprivate' protection level

There is no the exact solution for your question, by the reason stated in the #TheAppMentor's comment. But there some workarounds which may be helpful if you purpose is to make your code understandable for humans (not to trick the compiler).
Compiles in Swift 4.0.
Solution 1: Python-like __privacy
Fast and simple. This solution relies on the user who would agree that properties and functions starting from _ are private and shouldn't be accessed.
protocol ProtocolX: class {
// Public x
var x: Int { get }
// It's private!
var _x: Int { get set }
func performAnyActionOnX()
}
extension ProtocolX {
var x: Int { return _x }
func performAnyActionOnX(){
_x = 5
print(x)
}
}
class A: ProtocolX {
var _x: Int = 7
}
Solution 2: Additional layer of abstration
Architecturally correct. You should split your protocol on the two parts: private and public.
protocol ProtocolX: class {
var x: Int { get }
func performAnyActionOnX()
}
protocol ProtocolXImplementation: class {
var _x: Int { get set }
}
extension ProtocolXImplementation {
var x: Int { return _x }
func performAnyActionOnX(){
_x = 5
print(x)
}
}
class A: ProtocolX, ProtocolXImplementation {
var _x: Int = 7
}
// ... somewhere later ...
// Hide the implementation when use `A`:
let item: ProtocolX = A()

Related

Implement a public method that rely on a private property in Swift using protocols

I'm building an API that uses ResultBuilder with structs as components and chaining methods as modifiers.
Sometimes different components have the same modifier, e.g.:
var resultBuilderContent = {
Component1()
.modifier(x: 1)
Component2()
.modifier(x: 2)
}
I'd like to implement 'modifier' method in a protocol to avoid duplicating the code. But the method relies on internal properties and if I implement it like this:
protocol SameModifierProtocol{
var x: Int { get set }
}
extension SameModifierProtocol{
public func modifier(x: Int)->SameModifierProtocol{
var s = self
s.x = x
return s
}
}
public struct Component: SameModifierProtocol{
var x: Int = 0
public init(){}
}
// in another module
let c = Component().modifier(x: 1)
I get the error: "'modifier' is inaccessible due to 'internal' protection level".
If I try to differentiate access levels between two protocols like this:
protocol SameModifierProtocol{
var x: Int { get set }
}
public protocol ReceivingSameModifier{
}
extension ReceivingSameModifier where Self: SameModifierProtocol{
public func modifier(x: Int)->ReceivingSameModifier{
var s = self
s.x = x
return s
}
}
I get the following error: "Cannot declare a public instance method in an extension with internal requirements".
This is where I stuck. What are my options?
Following this discussion from Swift forum, there are two ways to solve the issue.
First one is straightforward:
/// The publically visible capabilities.
public protocol SameModifierProtocol {
func modifier(x: Int) -> SameModifierProtocol
}
/// The internal requirements on which the default implementation relies.
internal protocol SynthesizedSameModifierProtocolConformance:
SameModifierProtocol {
var x: Int { get set }
}
/// The default implementation.
extension SynthesizedSameModifierProtocolConformance {
public func modifier(x: Int) -> SameModifierProtocol{
var s = self
s.x = x
return s
}
}
/// Conforms to the public protocol
/// and requests the default implementation from the internal one.
/// Clients can only see the public protocol.
public struct Component: SynthesizedSameModifierProtocolConformance {
internal var x: Int = 0
public init() {}
}
The second involves an unofficial feature #_spi, that allows to make implementation details unexposed in a public protocol:
public protocol SameModifierProtocol {
#_spi(SameModifier) var x: Int { get set }
}
extension SameModifierProtocol {
public func modifier(x: Int) -> Self {
var s = self
s.x = x
return s
}
}
public struct Component: SameModifierProtocol {
#_spi(SameModifier) public var x: Int = 0
public init() {}
}

Protocol Conformance Check

How can I perform conformance check against protocol with AssociatedType. Xcode shows error:
Protocol 'MyListener' can only be used as a generic constraint because
it has Self or associated type requirements
My ultimate goal is to extract "MyListener.section" from an array of weakObjects, where the handler matches the function argument.
Note. The NSPointerArray of weakObjects is suppose to capture different types of MyListeners.
public class MyHandler<O,E> {
var source = [O]()
var dest = [E]()
}
public protocol MyListener:class {
var section: Int {get}
associatedtype O
associatedtype E
var handler: MyHandler<O,E>? { get }
}
public class MyAnnouncer {
private let mapWeakObjects: NSPointerArray = NSPointerArray.weakObjects()
public func add<L: MyListener>(listener: L) {
let pointer = Unmanaged.passUnretained(listener).toOpaque()
mapWeakObjects.addPointer(pointer)
}
public func search<O, E> (h:MyHandler<O,E>) -> [Int] {
_ = mapWeakObjects.allObjects.filter { listener in
if listener is MyListener { // Compilation failed
}
if let _ = listener as? MyListener { //Compilation error
}
if listener is MyListener.Type { //Compilation failed
}
}
return [] // ultimate goal is to extract corresponding [MyListener.section].
}
}
Unfortunately, Swift doesn't support protocols with AssociatedType to conformance.
You should try to use Type Erasure. One of the way is to implement type erasure by creating new AnyType class.
Here is another way to release type erasure (example from the internet)
protocol SpecialValue { /* some code*/ }
protocol TypeErasedSpecialController {
var typeErasedCurrentValue: SpecialValue? { get }
}
protocol SpecialController : TypeErasedSpecialController {
associatedtype SpecialValueType : SpecialValue
var currentValue: SpecialValueType? { get }
}
extension SpecialController {
var typeErasedCurrentValue: SpecialValue? { return currentValue }
}
extension String : SpecialValue {}
struct S : SpecialController {
var currentValue: String?
}
var x: Any = S(currentValue: "Hello World!")
if let sc = x as? TypeErasedSpecialController { // Now we can perform conformance
print(sc.typeErasedCurrentValue)
}

How do you implement a generic class factory in Swift?

I want to "make" a number of class instances similar to a base class but different in underlying type. (Not quite the same as the typical "Animal" class factory examples seen all over the net!)
The code below is close to working but it requires the user to "upcast" the make result, as in:
var f1 = FOO.make(version: FOO.Ver.f1) as! FOO1_32
I do not want the user to know about the specific class type other than it is a FOO. I have seen other proposals and they all indicate that the solution is to define the make with a generic type that conforms to the protocol as in:
make<T: FOOProtocol>(version: Ver = .f1) -> T
However this gives me the error "generic parameter 'T' could not be inferred" on the call to FOO.make(version: FOO.Ver.f1)
Anyone know how to do this? My Playground code follows.
protocol FOOProtocol
{
associatedtype FOOtype
var value: FOOtype {get set}
}
class FOO
{
enum Ver
{
case f1
case f2
}
class func make(version: Ver = .f1) -> FOO
{
print("FOO make")
switch version
{
case .f1:
return FOO1_32()
case .f2:
return FOO2_64()
}
}
}
class FOO1_32: FOO, FOOProtocol
{
typealias FOOtype = UInt32
private var fooVal: UInt32 = 0
var value: UInt32
{
get { return self.fooVal }
set { self.fooVal = newValue }
}
override init()
{
print("FOO1_32 init")
self.fooVal = 132
}
}
class FOO2_64: FOO, FOOProtocol
{
typealias FOOtype = UInt64
private var fooVal: UInt64 = 0
var value: UInt64
{
get { return self.fooVal }
set { self.fooVal = newValue }
}
override init()
{
print("FOO2_64 init")
self.fooVal = 264
}
}
var f1 = FOO.make(version: FOO.Ver.f1) // requires: as! FOO1_32
let f1v = f1.value
print("\(f1v)")
var f2 = FOO.make(version: FOO.Ver.f2) // requires: as! FOO2_64
let f2v = f2.value
print("\(f2v)")

Swift: Abstract base class/protocol with private members

I've created an abstract base class-like structure in Swift, using protocol extensions, as per this answer. This is a simplified example:
protocol AbstractBase {
var _constant: Int { get }
func _operation(_ val: Int) -> Int
}
public class ConcreteSub: AbstractBase {
let _constant: Int = 42
func _operation(_ val: Int) -> Int {
return val + 2
}
}
extension AbstractBase {
func mainOperation(_ val: Int) -> Int {
return _operation(val + _constant)
}
}
So basically, ConcreteSub provides the implementation details needed by AbstractBase, namely _constant and _operation.
I would like to hide those details from clients, and only expose mainOperation. However, Swift does not allow me to make the members fileprivate on the protocol -- if I do the following
protocol AbstractBase {
fileprivate var _constant: Int { get }
// etc
I get "error: 'fileprivate' modifier cannot be used in protocols".
Nor can I apply the modifier on the subclass -- when I try
public class ConcreteSub: AbstractBase {
fileprivate let _constant: Int = 42
// etc
I get "error: property '_constant' must be declared internal because it matches a requirement in internal protocol 'AbstractBase'".
Lastly, when I make the whole protocol fileprivate, I get no compile errors, but I consistently run into Linking errors, which I guess is because the protocol is private, but the subclass is public.
Is there another way I'm missing?
When I need an abstract base with some properties/functions hidden I use class with some additional fatalErrors and asserts to crash whenever someone is trying to use Base instead of implementation.
public class AbstractBase {
init() {
assert(type(of: self) != AbstractBase.self, "Abstract class")
}
fileprivate var _constant: Int {
fatalError("Abstract class")
}
fileprivate func _operation(_ val: Int) -> Int {
fatalError("Abstract class")
}
func mainOperation(_ val: Int) -> Int {
return _operation(val + _constant)
}
}
public class ConcreteSub: AbstractBase {
fileprivate override var _constant: Int {
return 42
}
fileprivate override func _operation(_ val: Int) -> Int {
return val + 2
}
}
I actually just ran into this issue. As of Swift 5.1, you can do this instead:
protocol MyProtocol {
var someVisibleVar: String { get }
func someVisibleFunc()
}
fileprivate extension MyProtocol {
var someFilePrivateVar: String {
"whatever"
}
func someFilePrivateFunc() {
print("someFilePrivateFunc() was called with \(someVisibleVar)")
}
}
class SomeClass: MyProtocol {
var someVisibleVar: String { "whatever" }
func someVisibleFunc() {
if someFilePrivateVar == someVisibleVar {
someFilePrivateFunc()
}
}
}
class SomeOtherClass: MyProtocol {
var someVisibleVar: String { "something else" }
func someVisibleFunc() {
if someFilePrivateVar == someVisibleVar {
someFilePrivateFunc()
}
}
}

How to store constants at the class level that can be overriden?

I want to write the following in Swift:
class A
{
class let x = 0
func print_class_property()
{
print(type(of: self).x)
}
}
class B:A
{
overriding class let x = 1
}
class C:A
{
overriding class let x = 5
}
A().print_class_property() // 0
B().print_class_property() // 1
C().print_class_property() // 5
But of course, this doesn’t compile.
Instead, I can demote the class property to a variable instance property that’s overwritten in the subclass initializers, but this allocates storage for x in every instance of A, B, or C. In addition you lose the guarantee that x never changes across the lifetime of the object.
How do I store constants at the class level, that can be shared by all instances of a subclass?
Unfortunately Swift (as for now) cannot have class stored properties that can be overriden. But can have class computed properties, which are overridable.
You can write something like this:
class A
{
class var x: Int {
return 0
}
func print_class_property()
{
print(type(of: self).x)
}
}
class B:A
{
override class var x: Int {
return 1
}
}
class C:A
{
override class var x: Int {
return 5
}
}
A().print_class_property() //->0
B().print_class_property() //->1
C().print_class_property() //->5
ADDITION
If you do not desire such re-evaluation as noted in comments, you may need to have some another static property.
For example:
class A
{
class var x: SomeLargeObject {
struct My {
static let obj = SomeLargeObject("abc", 0)
}
return My.obj
}
func print_class_property()
{
print(type(of: self).x)
}
}
class B:A
{
override class var x: SomeLargeObject {
struct My {
static let obj = SomeLargeObject("def", 1)
}
return My.obj
}
}
class C:A
{
override class var x: SomeLargeObject {
struct My {
static let obj = SomeLargeObject("ghi", 5)
}
return My.obj
}
}