воскресенье, 5 июля 2020 г.

Swift, Access Control

Online Swift Playground 

- private
- fileprivate
- internal (default)
- public
- open

//weapon.swift
public protocol Weapon {
    var ammo: Int {get}
}

//gun.swift
internal class Gun: Weapon {
    private(set) var ammo: Int
    fileprivate(set) var isEmpty: Bool

    init(ammo: Int = 3){
        self.ammo = ammo
        self.isEmpty = false
    }

    func fire() {
        guard self.ammo > 0 else {
            print("Out of ammo!")
            self.isEmpty = true
            return
        }
        self.ammo -= 1
        print("Fire!")
    }

    func reload(ammo: Int = 3){
        self.ammo = ammo
        print("Reloading!")
        self.isEmpty = false
    }
}

//main.swift
var g1 = Gun()
print("ammo: \(g1.ammo)")
while !g1.isEmpty {
    g1.fire()
}
//g1.ammo = 3 //error
g1.reload()
print("ammo: \(g1.ammo)")

Комментариев нет:

Отправить комментарий