BudiBadu Logo
Samplebadu
Swift

Learn Swift by Examples

Swift 5.x

Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and Swift includes modern features developers love.

These examples cover the core building blocks of Swift, from basic variables and constants to complex types like closures, classes, and protocols.

Variables

Learn Swift variable declaration and mutability with this sample code demonstrating type inference, explicit type annotations, string interpolation, and optional types for handling nil values safely in your applications.

Constants

Understanding Swift constants with this code example showing immutable value declarations using let keyword, type inference, explicit typing, and how constants behave with collection types like arrays and dictionaries.

Functions

Master Swift function syntax with this sample code demonstrating parameter declarations, return types, argument labels for readable function calls, omitting labels with underscore, and returning multiple values using tuples.

Closures

Explore Swift closures with this code example covering full closure syntax, type inference, implicit returns, shorthand argument names using dollar signs, trailing closure syntax, and capturing values from surrounding context.

Arrays

Working with Swift arrays through this sample code demonstrating array creation with type annotations, accessing elements by index, appending and modifying values, iterating with for-in loops, and functional methods like map and filter.

Dictionaries

Understanding Swift dictionaries with this code example showing key-value pair storage, optional value access, safe unwrapping with if-let, adding and updating entries, removing keys by setting nil, and iterating over dictionary contents.

Classes

Dive into Swift classes with this sample code demonstrating reference type behavior, property declarations, computed properties, method definitions, class inheritance using colon syntax, method overriding with override keyword, and shared instance references.

Structures

Explore Swift structures with this code example illustrating value type semantics, automatic memberwise initializers, copy-on-assignment behavior, property declarations, and mutating methods that modify struct properties requiring the mutating keyword.

Enums

Master Swift enumerations with this sample code showing enum case declarations, type inference with dot syntax, powerful associated values for storing different data types per case, and exhaustive pattern matching with switch statements.

Protocols

Understanding Swift protocols with this code example demonstrating protocol definitions as blueprints, property requirements with get/set specifications, protocol adoption by structs and classes, conformance through implementation, and computed properties satisfying protocol requirements.