Access Control

1.Open Access

Used primarily in frameworks to allow subclassing and overriding outside the module

open class OpenClass {
    open func greet() {
        print("Hello from Swift!")
    }
}

2.Public Access

Allows usage outside the module but does not allow subclassing or overriding outside the module.

public class PublicClass {
    public func greet() {
        print("Hello from PublicClass!")
    }
}

3.Internal Access

Accessible anywhere within the same module.

internal class InternalClass {
    internal func greet() {
        print("Hello from InternalClass!")
    }
}

4.Fileprivate Access

Limits access to the enclosing declaration or extensions within the same file

class PrivateClass {
    private func greet() {
        print("Hello from PrivateClass!")
    }
}

Open vs Public

Open allows external subclassing and overriding:

Public restricts subclassing and overriding outside the module

open class Animal {
    open func sound() {
        print("Sound")
    }
}

public class Dog: Animal {
    override open func sound() {
        print("Bark!")
    }
}
public class Animal {
    public func sound() {
        print("Sound")
    }
}

public class Dog: Animal {
    override open func sound() {
        print("Bark!")  // Error public can't be overridden outside module
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *