Introduction to Swift: Basic Syntax, Variables, Control Flow, Functions, and More
Apple’s Swift language, introduced at WWDC 2014, offers a modern, LLVM‑compiled syntax with playgrounds, optional typing, clear variable and constant declarations, robust control‑flow constructs, first‑class functions and closures, class inheritance, protocols, extensions, generics, and safe optional handling, making development for macOS and iOS both expressive and less error‑prone.
Apple announced the new programming language Swift for macOS and iOS at WWDC 2014.
Before Swift was officially released, this guide provides a quick overview of its basic usage based on Apple’s beta documentation.
101: Basic Syntax
Compiled (LLVM) language with a Playground for real‑time input and execution.
Features include automatic global execution without a main function, no semicolons at line ends, and the simple hello‑world statement: println("Hello world") Comments use // for single‑line and /* */ for block comments, which can be nested (e.g., /* A /* B */ C */).
The assignment operator = is used only for assignment; var = value is not a valid expression, while == remains the equality test.
Variables and Data Types
Swift is a weakly typed language.
Variable declaration: var length = 10 Constant declaration: let MAX_LENGTH = 100 Explicit type annotation: var length: Double = 10 Implicit type conversion is prohibited. For example, the following is an error: println("Length = " + length + " cm") Correct usage: println("Length = " + String(length) + " cm") String interpolation provides a concise alternative:
println("Length = \(length) cm")Nil (Optional) Values
Nil is represented by nil. Variables that may hold nil must be declared as optionals using ?: var optionalString: String? = nil In logical expressions, nil is treated as false. Optional chaining allows safe access to properties or methods of a possibly‑nil value using ? after the variable.
Arrays and Dictionaries
Both are created with square brackets.
Array example: [value1, value2, value3] Dictionary example: ["key1": value1, "key2": value2] Empty array: []; empty dictionary: [:].
Control Flow
All conditional statements require a true Boolean expression; implicit conversion of numbers to Boolean is not allowed.
Conditional Branches
if statement
Parentheses are optional, but braces are required.
if condition1 { /* code */ } else if condition2 { /* code */ } else { /* code */ }switch statement
No break needed. Multiple values can be matched in a single case, and cases can include where clauses.
switch variable { case value1: /* code */ case value2, value3: /* code */ default: /* code */ }Loops
for‑in loop
Iterate over arrays, dictionaries, or ranges: for element in array { /* code */ } Dictionary iteration: for (key, value) in dictionary { /* code */ } Range iteration:
for index in 1..5 { /* code */ }C‑style for loop
for var index = 0; index < 3; ++index { /* code */ }while loop
while condition { /* code */ } do { /* code */ } while conditionFunctions
Definition and Invocation
func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." }
greet("Bob", "Tuesday")Variadic parameters: func f1(p1: Int...) -> Int { /* code */ } f1(1, 2, 3) Multiple return values via tuples: return (3.59, 3.69, 3.79) Functions can be nested, sharing the outer scope:
func returnFifteen() -> Int { var y = 10; func add() { y += 5 } add(); return y }
returnFifteen()Closures
Functions are first‑class values and can be returned or passed as arguments.
Returning a closure:
func makeIncrementer() -> (Int -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne }
var increment = makeIncrementer()
increment(7)Passing a function as a parameter:
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false }
func lessThanTen(number: Int) -> Bool { return number < 10 }
let numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, lessThanTen)Anonymous closures can be written with the in keyword:
numbers.map({ (number: Int) -> Int in let result = 3 * number; return result })When the type is inferred, the syntax can be shortened: numbers.map({ number in 3 * number }) Shorthand argument names are also supported:
sort([1, 5, 3, 12, 2]) { $0 > $1 }Objects and Classes
Definition and Instantiation
Class example:
class Shape {
var numberOfSides = 0
var name: String
init(name: String) { self.name = name }
func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." }
}Instantiation:
var shape = Shape("Triangle")
shape.numberOfSides = 3
println(shape.simpleDescription())Constructor: init(name: String) { ... } Destructor:
deinit() { ... }Inheritance and Polymorphism
Inheritance is indicated by a colon after the class name, and the super keyword accesses the superclass. Overriding requires the override keyword.
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) { self.sideLength = sideLength; super.init(name: name); numberOfSides = 4 }
func area() -> Double { return sideLength * sideLength }
override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." }
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()Properties
Properties can define custom getters and setters, using get, set, willSet, and didSet.
Example:
class Circle {
init(radius: Double) { self.radius = radius }
var radius: Double {
didSet { perimeter = radius * 6.28 }
}
var perimeter: Double {
get { return 6.28 * radius }
set { radius = newValue / 6.28 }
}
}
let circle = Circle(10)
circle.perimeter // 62.8
circle.perimeter = 31.4
circle.radius // 5Enumerations and Structures
Enums can have raw values and associated values, and can contain methods.
enum Rank: Int {
case Ace = 1, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace: return "ace"
case .Jack: return "jack"
case .Queen: return "queen"
case .King: return "king"
default: return String(self.rawValue)
}
}
}
let ace = Rank.Ace
let aceRawValue = ace.rawValue // 1Enums with associated values:
enum ServerResponse {
case Result(String, String)
case Error(String)
}
let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.")
switch success {
case let .Result(sunrise, sunset):
let msg = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
case let .Error(error):
let msg = "Failure... \(error)"
}Structures
Defined with struct, they are value types (copied on assignment) unlike classes which are reference types.
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" }
}
let threeOfSpades = Card(rank: .Three, suit: .Spades)
let description = threeOfSpades.simpleDescription()Protocols and Extensions
Protocols define a set of required properties and methods.
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}Both classes, structs, and enums can adopt protocols:
class SimpleClass: ExampleProtocol {
var simpleDescription = "A very simple class."
var anotherProperty = 69105
func adjust() { simpleDescription += " Now 100% adjusted." }
}
struct SimpleStructure: ExampleProtocol {
var simpleDescription = "A simple structure"
mutating func adjust() { simpleDescription += " (adjusted)" }
}Extensions add functionality to existing types:
extension Int: ExampleProtocol {
var simpleDescription: String { return "The number \(self)" }
mutating func adjust() { self += 42 }
}
7.simpleDescriptionGenerics
Generic functions, types, and constraints are declared using angle brackets.
Example generic function:
func repeat<ItemType>(item: ItemType, times: Int) -> [ItemType] {
var result = [ItemType]()
for _ in 0..<times { result.append(item) }
return result
}
repeat("knock", 4)Generic enum with associated values:
enum OptionalValue<T> {
case None
case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)Constraints using where:
func anyCommonElements<T: Sequence, U: Sequence where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element>(lhs: T, rhs: U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem { return true }
}
}
return false
}
anyCommonElements([1, 2, 3], [3])SF Brief Review of Swift
Swift is a major highlight of WWDC 2014, offering a modern language that combines strengths from many existing languages.
Key advantages include nested comments, prohibition of implicit type conversion, and prohibition of implicit logical evaluation, which help reduce bugs for both beginners and experienced developers.
Open questions remain about benchmark claims, the degree of open‑source availability, and the long‑term applicability of Swift beyond Apple platforms.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Baidu Tech Salon
Baidu Tech Salon, organized by Baidu's Technology Management Department, is a monthly offline event that shares cutting‑edge tech trends from Baidu and the industry, providing a free platform for mid‑to‑senior engineers to exchange ideas.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
