Eldar
Eldar

Reputation: 554

inout parameter in Swift

When trying to study ionut parameters, I came across an example of code.

This code throws an error:

"Execution was interrupted, reason: signal SIGABRT. The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation."

However, when trying to debag on a real project, po char 1.

var num1: Int = 1
var char1 = "a"

func changeNumber(num: Int) {
    var num = num
    num = 2
    print(num) // 2
    print(num1) // 1
}
changeNumber(num: num1)

func changeChar(char: inout String) {
    char = "b"
    print(char) // b
    print(char1) // b
}
changeChar(char: &char1)

Please explain why this error is issued and how to fix it?

Upvotes: 1

Views: 427

Answers (1)

Rob Napier
Rob Napier

Reputation: 299355

The error should be at the top of the stack trace:

Simultaneous accesses to 0x109fac098, but modification requires exclusive access.

When you pass char1 as a inout parameter to changeChar it is a memory violation to access char1 in any other way until that function returns.

For full details, see SE-176 Enforce Exclusive Access to Memory which added this restriction in Swift 4.

Upvotes: 3

Related Questions