Swift is a powerful and popular programming language for developing iOS, macOS, watchOS, and tvOS applications. It is widely used by developers due to its easy-to-learn syntax and features. Here’s a Swift code cheat sheet to help you get started with Swift development.
Basic Syntax
Swift is a statically typed language, which means that you need to declare the data type of a variable when you declare it. For example:
var myVariable: Int = 10
You can use let
to declare a constant:
let myConstant: String = "Hello, World!"
You can use if-else
statements for conditional logic:
if a > b {
print("a is greater than b")
} else {
print("b is greater than a")
}
You can use for-in
loops for iterating over collections:
let numbers = [1, 2, 3, 4, 5]
for number in numbers {
print(number)
}
Optionals
Optionals are used to represent the absence of a value. You can declare an optional variable by appending a ?
to the type:
var myOptional: Int?
You can use optional binding to safely unwrap an optional and check if it contains a value:
if let unwrappedOptional = myOptional {
print(unwrappedOptional)
} else {
print("myOptional is nil")
}
Functions
You can declare a function using the func
keyword:
func sayHello(name: String) -> String {
return "Hello, \(name)!"
}
You can call a function using its name:
let greeting = sayHello(name: "John")
print(greeting)
Classes and Structures
Classes and structures are used to define custom data types. Classes are reference types, while structures are value types.
You can define a class using the class
keyword:
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func sayHello() {
print("Hello, my name is \(name)")
}
}
You can define a structure using the struct
keyword:
struct Point {
var x: Int
var y: Int
mutating func moveBy(x: Int, y: Int) {
self.x += x
self.y += y
}
}
You can create an instance of a class or structure using the init
method:
let person = Person(name: "John", age: 30)
let point = Point(x: 0, y: 0)
You can access properties and call methods using the dot notation:
print(person.name)
person.sayHello()
point.moveBy(x: 10, y: 10)
print("(\(point.x), \(point.y))")
Optionals, Enums, and OptionSets
Optionals are a way to represent a value that may or may not exist. You can use the ?
symbol to declare an optional type:
var optionalString: String?
Enums are used to define a set of related values:
enum CompassPoint {
case north
case south
case east
case west
}
let direction: CompassPoint = .north
Extensions and Protocols
Extensions are used to add new functionality to an existing type. You can define an extension using the extension
keyword:
extension String {
func reverse() -> String {
return String(self.reversed())
}
}
let str = "hello"
print(str.reverse())
Protocols are used to define a set of methods and properties that a type must implement. You can define a protocol using the protocol
keyword:
protocol Vehicle {
var numberOfWheels: Int { get }
var color: String { get set }
func start()
func stop()
}
class Car: Vehicle {
var numberOfWheels: Int = 4
var color: String = "Red"
func start() {
print("Starting the car")
}
func stop() {
print("Stopping the car")
}
}
You can use the extension
keyword to add conformance to a protocol:
extension Bike: Vehicle {
var numberOfWheels: Int = 2
var color: String = "Blue"
func start() {
print("Starting the bike")
}
func stop() {
print("Stopping the bike")
}
}
Error Handling
Swift provides robust error handling mechanisms using try-catch
blocks and throwing functions:
enum NetworkError: Error {
case invalidURL
case serverError
}
func fetchData(from url: URL) throws -> Data {
guard url.absoluteString.hasPrefix("https://") else {
throw NetworkError.invalidURL
}
// perform network request and return data
}
do {
let data = try fetchData(from: url)
// process data
} catch NetworkError.invalidURL {
print("Invalid URL")
} catch {
print("Unknown error: \(error)")
}
Conclusion
In conclusion, Swift is a powerful and modern programming language that is widely used for developing applications across various Apple platforms. It has a clean syntax, strong type safety, and rich support for functional programming paradigms. In this cheat sheet, we covered some of the most commonly used features of the Swift language, including data types, control flow statements, functions, classes and structs, extensions and protocols, and error handling. With this knowledge, you can start building your own iOS apps, macOS utilities, or even server-side applications using Swift. Keep practicing, and happy coding!