접근제한자
5가지 접근 제한자 종류
[제약이 적음] open < public < internal < fileprivate < private [제약이 많음]
상위 요소보다 하위 요소가 더 높은 접근 수준을 가질 수 없다.
private struct Car {
public var model: String // Error
}
모듈과 소스파일
public, open
internal
fileprivate
private
예시
open class Vehicle{
open func startEngine() {
print("Engine started")
}
}
open class Car: Vehicle {
open var carType: String = "Sedan"
}
//public
public struct Point {
public var x: Int
public var y: Int
public init(x: Int, y: Int){
self.x = x
self.y = y
}
public mutating func moveByX(_ deltaX: Int,_ deltaY: Int){
self.x += deltaX
self.y += deltaY
}
}
//internal
internal class InternalClass {
internal var internalProperty: Int = 10
internal func doSomethingInternally(){
print("Internal operation performed")
}
}
//private
class MyClass {
private var privateVariable = 40
private func privateFunction() {
print("Private function called")
}
}
/*
Swift에서 mutating 키워드는 구조체(Struct)나 열거형(Enum) 내에서
메서드가 해당 구조체 또는 열거형의 속성을 수정할 수 있도록 하는 키워드
기본적으로 Swift에서는 구조체나 열거형의 인스턴스가 상수로 선언되면 해당 인스턴스의 속성을 변경할 수 없다.
하지만 메서드 내에서 해당 인스턴스의 속성을 변경하려면 mutating 키워드를 사용하여
해당 메서드가 해당 인스턴스의 속성을 수정할 수 있도록 허용해야 한다.
*/
// 구조체 예시
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double){
x += deltaX
y += deltaY
}
}
var point = Point(x: 1.0, y: 1.0)
print("Before moving: x = \(point.x), y = \(point.y)")
point.moveBy(x: 2.0, y: 3.0)
print("After moving: x = \(point.x), y = \(point.y)")
// Before moving: x = 1.0, y = 1.0
// After moving: x = 3.0, y = 4.0
// 열거형 예시
enum TrafficLight {
case red, yellow, green
mutating func next(){
switch self{
case .red:
self = .green
case .yellow:
self = .red
case .green:
self = .yellow
}
}
}