Swift Examples
Modern, safe, and expressive - Apple's language for iOS, macOS, and beyond.
Example 1: Adding two Numbers
Code
// Taking input from user
print("Enter first number: ", terminator: "")
if let input1 = readLine(), let a = Int(input1) {
print("Enter second number: ", terminator: "")
if let input2 = readLine(), let b = Int(input2) {
// Calculating sum
let sum = a + b
// Displaying output
print("Sum is: \(sum)")
}
}
Input
Enter first number: 10 Enter second number: 8
Output
Sum is: 18
Code Explanation
readLine() takes input as string, Int() converts to number. Optional binding (if let) ensures safe conversion. print() with \(sum) displays the result using string interpolation.