Welcome to our beginner-friendly Swift Interview Questions series! In this lesson, we'll dive into the basics of Swift, a powerful and intuitive programming language for iOS, macOS, watchOS, and tvOS. Let's get started!
Swift is a modern, open-source programming language developed by Apple for iOS, macOS, watchOS, and tvOS app development. Swift combines the performance and efficiency of C and Objective-C with a modern and safe programming language.
Variables and constants are essential in every programming language. Here's how you can declare and use them in Swift:
// Declaring a variable
var myVariable: Int = 10
print("The value of myVariable is \(myVariable)")
// Declaring a constant
let pi = 3.14159
print("The value of pi is \(pi)")š” Pro Tip: Use let to declare a constant, and var to declare a variable.
Swift supports various data types, including integers, floating-point numbers, strings, booleans, and more.
// Integer
let myInteger: Int = 10
// Floating-point number
let myFloat: Float = 10.5
let myDouble: Double = 10.5
// String
let myString: String = "Hello, World!"
// Boolean
let isTrue: Bool = true
let isFalse: Bool = falseControl structures like loops and conditional statements allow you to control the flow of your code.
// If statement
if myInteger > 5 {
print("myInteger is greater than 5")
}
// If-else statement
if myInteger > 5 {
print("myInteger is greater than 5")
} else {
print("myInteger is less than or equal to 5")
}
// Switch statement
let myValue: Int = 10
switch myValue {
case 0:
print("myValue is 0")
case 1...4:
print("myValue is between 1 and 4")
case 5...10:
print("myValue is between 5 and 10")
default:
print("myValue is greater than 10")
}// For loop
for index in 1...10 {
print("Index is \(index)")
}
// While loop
var counter = 0
while counter < 10 {
print("Counter is \(counter)")
counter += 1
}Functions allow you to group a series of statements to perform a specific task.
// Function definition
func greet(name: String) {
print("Hello, \(name)!")
}
// Function call
greet(name: "John")What is the purpose of a variable in Swift?
Stay tuned for our next lesson, where we'll dive deeper into Swift, covering advanced concepts and practical examples! šÆ