← Back to archive

Development · Swift

Functions, loops, and string interpolation in Swift

Separate work into functions, repeat it with for-in, and control formatted output with print.

Read the Korean original on Velog ↗English translation

Development archive cover

A function gives a task a name so it can be reused. Combining functions with loops and string interpolation makes it easier to process and display several values consistently.

Functions with input and output

func addingTwo(to number: Int) -> Int {
    number + 2
}

func printGreeting() {
    print("Hello")
}

A function is easier to reuse when its name describes its purpose and it has one clear responsibility.

for-in and string interpolation

for count in 1...3 {
    print("\(count)번째 실행")
}

1...3 includes both endpoints. Use 1..<3 to exclude the upper endpoint. String interpolation, written as \(expression), inserts a value into a string in a readable form.

Formatting print output

print(1, 2, 3, separator: "@")
// 1@2@3

print(1, 2, 3, separator: ", ", terminator: " and ")
print(4)
// 1, 2, 3 and 4

separator controls the text between arguments; terminator controls what is appended at the end. Functions and loops reduce duplication while making the flow of data explicit.

← Back to archive