Online Swift Compiler – Instantly Run Swift Code in Your Browser
Write and execute Swift code in real time with our free online Swift compiler. Perfect for iOS developers and Swift learners — it's fast, easy, and works right in your browser.
✨ Popular Swift courses people love
Loading...
💡 Swift Basics Guide for Beginners
1. Declaring Variables and Constants
Use var
for variables and let
for constants in Swift.
var age = 30
let pi = 3.14159
var name = "Alice"
let isActive = true
// Constants cannot be reassigned
// pi = 3.14 // ❌ Error
2. Conditionals (if / switch)
Use if
, else if
, else
for logic, and switch
for multiple branches.
let number = 2
if number == 1 {
print("One")
} else if number == 2 {
print("Two")
} else {
print("Other")
}
switch number {
case 1:
print("One")
case 2:
print("Two")
default:
print("Other")
}
3. Loops
Swift supports for-in
, while
, and repeat-while
loops.
for i in 0..<3 {
print(i)
}
var n = 3
while n > 0 {
print(n)
n -= 1
}
4. Arrays
Arrays store ordered collections of values.
var numbers = [10, 20, 30]
print(numbers[1])
5. Array Manipulation
Use array methods like append
and removeLast
.
var nums = [1, 2, 3]
nums.append(4)
nums.removeLast()
for n in nums {
print(n)
}
6. Console Input/Output
Use print()
for output. Input requires additional work in Swift Playgrounds or Xcode.
let name = "Alice"
print("Hello, \(name)")
7. Functions
Define reusable functions with parameters and return values.
func add(a: Int, b: Int) -> Int {
return a + b
}
print(add(a: 3, b: 4))
8. Dictionaries
Dictionaries store key-value pairs.
var ages = ["Alice": 30]
print(ages["Alice"] ?? 0)
9. Error Handling
Swift uses do-catch
for error handling.
enum MyError: Error {
case runtimeError(String)
}
do {
throw MyError.runtimeError("Something went wrong")
} catch let error {
print(error)
}
10. File I/O
Swift uses FileManager
or String
methods for file I/O.
let text = "Hello File"
try text.write(toFile: "file.txt", atomically: true, encoding: .utf8)
let content = try String(contentsOfFile: "file.txt")
print(content)
11. String Manipulation
Use methods like count
, contains
, uppercased()
, etc.
let text = "Hello World"
print(text.count)
print(text.contains("World"))
print(text.uppercased())
12. Classes & Objects
Swift supports OOP using class
and init
.
class Person {
var name: String
init(name: String) {
self.name = name
}
func greet() {
print("Hi, I'm \(name)")
}
}
let p = Person(name: "Alice")
p.greet()
13. Optionals
Swift uses ?
and !
to handle optional values.
var name: String? = "Alice"
print(name ?? "Unknown")
if let unwrappedName = name {
print(unwrappedName)
}