Memory Safety

Run Settings
LanguageSwift
Language Version
Run Command
// A write access to the memory where one is stored. var one = 1 // A read access from the memory where one is stored. print("We're number \(one)!") func oneMore(than number: Int) -> Int { return number + 1 } var myNumber = 1 myNumber = oneMore(than: myNumber) print(myNumber) // Prints "2" var stepSize = 1 func increment(_ number: inout Int) { number += stepSize } increment(&stepSize) // Error: conflicting accesses to stepSize // Buat salinan secara eksplisit. var copyOfStepSize = stepSize increment(&copyOfStepSize) // Perbarui variabel yang asli. stepSize = copyOfStepSize // stepSize sekarang bernilai 2 func balance(_ x: inout Int, _ y: inout Int) { let sum = x + y x = sum / 2 y = sum - x } var playerOneScore = 42 var playerTwoScore = 30 balance(&playerOneScore, &playerTwoScore) // OK balance(&playerOneScore, &playerOneScore) // Error: conflicting accesses to playerOneScore struct Player { var name: String var health: Int var energy: Int static let maxHealth = 10 mutating func restoreHealth() { health = Player.maxHealth } } extension Player { mutating func shareHealth(with teammate: inout Player) { balance(&teammate.health, &health) } } var gilang = Player(name: "Gilang", health: 10, energy: 10) var ramadhan = Player(name: "Ramadhan", health: 5, energy: 10) gilang.shareHealth(with: &ramadhan) // OK gilang.shareHealth(with: &gilang) // Error: conflicting accesses to gilang var playerInformation = (health: 10, energy: 20) balance(&playerInformation.health, &playerInformation.energy) // Error: conflicting access to properties of playerInformation var yourName = Player(name: "Nama kamu", health: 10, energy: 10) balance(&yourName.health, &yourName.energy) // Error func someFunction() { var gilang = Player(name: "Gilang", health: 10, energy: 10) balance(&gilang.health, &gilang.energy) // OK }
Editor Settings
Theme
Key bindings
Full width
Lines