Swift is a powerful and intuitive open-source programming language developed by Apple Inc. for building applications across Apple’s ecosystem, including iOS, macOS, watchOS, and tvOS. It is also increasingly used for server-side development and other platforms due to its performance and modern features.
High Level Language Review
Swift Code Examples
1. Hello World:
print("Hello, world!")
2. Variables and Constants:
var greeting = "Hello" // Declares a variable
let name = "Alice" // Declares a constant
greeting = "Hi" // Variables can be changed
// name = "Bob"
// Constants cannot be changed (this would cause an error)
3. Functions:
func greet(person: String) {
print("Hello, \(person)!")
}
greet(person: "Bob") // Calling the function
4. Control Flow (If/Else):
let temperature = 25
if temperature > 30 {
print("It's hot!")
} else if temperature < 10 {
print("It's cold!")} else {
print("The weather is pleasant.")
}
5. Arrays:
var fruits = ["Apple", "Banana", "Cherry"]
print(fruits[0]) // Accessing elements by index
//(output: Apple)
fruits.append("Date") // Adding an element
print(fruits)
// output: ["Apple", "Banana", "Cherry", "Date"]
6. Loops (For-in):
for fruit in fruits {
print("I like \(fruit).")
}
7. Structures:
struct Book {
var title: String
var author: String
var year: Int
}
let myBook = Book(title: "The Great Gatsby", author: "F. Scott Fitzgerald", year: 1925)
print(myBook.title) // output: The Great Gatsby