Welcome to our comprehensive guide on Custom Types Access in Swift! By the end of this tutorial, you'll be able to create, modify, and understand access control for your custom types. Let's get started!
Custom types, also known as Structures (struct) and Classes, allow you to create your own data types in Swift. Understanding access control for these custom types is essential for writing clean, maintainable code. In this tutorial, we'll focus on Swift's access control mechanisms: public, private, and fileprivate.
A structure is a value type similar to an integer or string, which means each instance has its own separate memory allocation. Let's create a Point structure and learn about access control.
struct Point {
var x: Double
var y: Double
}
let origin = Point(x: 0, y: 0)In the above example, we've defined a Point structure with two properties: x and y. By default, all properties in Swift are private.
To make a property accessible outside the structure, we use access control keywords:
public: Accessible from everywhereprivate: Accessible only within the structurefileprivate: Accessible only within the file the structure is defined inLet's make the x and y properties of the Point structure publicly accessible:
struct Point {
public var x: Double
public var y: Double
}
let origin = Point(x: 0, y: 0)
print("x: \(origin.x), y: \(origin.y)") 📝 _Prints: x: 0, y: 0_Access control also applies to methods within a structure:
struct Point {
public var x: Double
public var y: Double
func distance(from another: Point) -> Double {
let distance = sqrt(pow(self.x - another.x, 2) + pow(self.y - another.y, 2))
return distance
}
}
let point1 = Point(x: 1, y: 1)
let point2 = Point(x: 4, y: 4)
let distance = point1.distance(from: point2)
print("Distance between point1 and point2 is \(distance)") 📝 _Prints: Distance between point1 and point2 is 5.0_In the above example, the distance(from:) method is accessible from outside the structure due to the public access level.
fileprivate access level restricts access to the property or method within the file where it's defined:
struct Point {
fileprivate var x: Double
fileprivate var y: Double
public func distance(from another: Point) -> Double {
let distance = sqrt(pow(self.x - another.x, 2) + pow(self.y - another.y, 2))
return distance
}
}In the above example, the properties x and y are not accessible outside the file, but the distance(from:) method is still public and can be called from other files.
Which access level restricts a property or method to be accessible only within the file where it's defined?
That's it for our Swift tutorial on Custom Types Access! With this knowledge, you can now create, modify, and understand access control for your custom types. In the next tutorial, we'll explore classes and their access control mechanisms.
Happy coding! 💡