diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..e9d08dd --- /dev/null +++ b/Package.swift @@ -0,0 +1,19 @@ +// swift-tools-version: 6.2 +// The swift-tools-version declares the minimum version of Swift required to build this package. + +import PackageDescription + +let package = Package( + name: "HelloSwift", + targets: [ + // Targets are the basic building blocks of a package, defining a module or a test suite. + // Targets can depend on other targets in this package and products from dependencies. + .executableTarget( + name: "HelloSwift" + ), + .testTarget( + name: "HelloSwiftTests", + dependencies: [] + ), + ] +) diff --git a/README.md b/README.md index 789f7bd..1c63db2 100644 --- a/README.md +++ b/README.md @@ -1 +1,77 @@ -# helloswift \ No newline at end of file +# HelloSwift - Learn Swift Programming + +A comprehensive learning repository for Swift programming language basics. + +## About + +This repository contains examples covering fundamental Swift concepts including: + +- **Basic Syntax** - Introduction to Swift's syntax and print statements +- **Variables and Constants** - Understanding `var` and `let` +- **Data Types** - Common types like Int, Double, Bool, String, Character +- **Control Flow** - if-else statements, switch cases, loops (for, while) +- **Functions** - Defining functions with parameters and return values +- **Optionals** - Working with optional values and safe unwrapping +- **Collections** - Arrays, Dictionaries, and Sets +- **Closures** - Anonymous functions and functional programming +- **Structs and Classes** - Value types vs reference types + +## Requirements + +- Swift 6.2 or later +- Swift Package Manager (comes with Swift) + +## Getting Started + +### Building the project + +```bash +swift build +``` + +### Running the examples + +```bash +swift run +``` + +This will execute all the learning examples and display the output for each concept. + +## Project Structure + +``` +HelloSwift/ +├── Package.swift # Swift Package Manager configuration +├── Sources/ +│ └── HelloSwift/ +│ └── HelloSwift.swift # Main file with all examples +└── README.md # This file +``` + +## Learning Path + +The examples are organized in a logical learning sequence: + +1. Start with Basic Syntax to understand print statements +2. Learn about Variables and Constants +3. Explore different Data Types +4. Master Control Flow with conditionals and loops +5. Create reusable code with Functions +6. Handle missing values with Optionals +7. Work with Collections of data +8. Write concise code with Closures +9. Build custom types with Structs and Classes + +## Resources + +- [Official Swift Documentation](https://docs.swift.org/swift-book/) +- [Swift.org](https://swift.org/) +- [Swift Package Manager](https://swift.org/package-manager/) + +## Contributing + +Feel free to add more examples or improve existing ones! + +## License + +This is a learning repository and is free to use for educational purposes. \ No newline at end of file diff --git a/Sources/HelloSwift/HelloSwift.swift b/Sources/HelloSwift/HelloSwift.swift new file mode 100644 index 0000000..db81198 --- /dev/null +++ b/Sources/HelloSwift/HelloSwift.swift @@ -0,0 +1,254 @@ +// The Swift Programming Language +// https://docs.swift.org/swift-book +// +// This is a learning repository for Swift basics +// Run with: swift run + +@main +struct HelloSwift { + static func main() { + print("=== Welcome to Swift Learning! ===\n") + + // Run all examples + basicSyntax() + variablesAndConstants() + dataTypes() + controlFlow() + functions() + optionals() + collections() + closures() + structsAndClasses() + + print("\n=== End of Swift Learning Examples ===") + } + + // MARK: - Basic Syntax + static func basicSyntax() { + print("--- Basic Syntax ---") + print("Hello, Swift!") + print("Swift is a powerful and modern programming language.") + print() + } + + // MARK: - Variables and Constants + static func variablesAndConstants() { + print("--- Variables and Constants ---") + + // Variables (can be changed) + var greeting = "Hello" + print("Variable: \(greeting)") + greeting = "Hi" + print("Changed to: \(greeting)") + + // Constants (cannot be changed) + let name = "Swift" + print("Constant: \(name)") + + // Type annotations + let age: Int = 10 + let version: Double = 6.2 + print("Age: \(age), Version: \(version)") + print() + } + + // MARK: - Data Types + static func dataTypes() { + print("--- Data Types ---") + + let integer: Int = 42 + let floatingPoint: Double = 3.14159 + let boolean: Bool = true + let string: String = "Swift" + let character: Character = "A" + + print("Integer: \(integer)") + print("Double: \(floatingPoint)") + print("Boolean: \(boolean)") + print("String: \(string)") + print("Character: \(character)") + + // String interpolation + print("Interpolation: \(integer) is an integer") + print() + } + + // MARK: - Control Flow + static func controlFlow() { + print("--- Control Flow ---") + + // If-else + let temperature = 25 + if temperature > 30 { + print("It's hot!") + } else if temperature > 20 { + print("It's warm!") + } else { + print("It's cold!") + } + + // Switch + let fruit = "apple" + switch fruit { + case "apple": + print("It's an apple!") + case "banana": + print("It's a banana!") + default: + print("Unknown fruit") + } + + // For loop + print("Counting 1 to 3:") + for i in 1...3 { + print(" \(i)") + } + + // While loop + var count = 0 + while count < 2 { + print(" While count: \(count)") + count += 1 + } + print() + } + + // MARK: - Functions + static func functions() { + print("--- Functions ---") + + func greet(name: String) -> String { + return "Hello, \(name)!" + } + + func add(a: Int, b: Int) -> Int { + return a + b + } + + print(greet(name: "Developer")) + print("2 + 3 = \(add(a: 2, b: 3))") + + // Function with default parameter + func greetWithDefault(name: String = "World") -> String { + return "Hi, \(name)!" + } + + print(greetWithDefault()) + print(greetWithDefault(name: "Swift")) + print() + } + + // MARK: - Optionals + static func optionals() { + print("--- Optionals ---") + + // Optional declaration + var optionalName: String? = "John" + print("Optional with value: \(optionalName ?? "nil")") + + // Optional binding (if let) + if let name = optionalName { + print("Unwrapped: \(name)") + } else { + print("Optional is nil") + } + + // Nil value + optionalName = nil + print("Optional set to nil: \(optionalName ?? "nil")") + + // Guard statement + func printLength(of string: String?) { + guard let str = string else { + print("String is nil") + return + } + print("Length: \(str.count)") + } + + printLength(of: "Swift") + printLength(of: nil) + print() + } + + // MARK: - Collections + static func collections() { + print("--- Collections ---") + + // Arrays + var fruits = ["apple", "banana", "orange"] + print("Array: \(fruits)") + fruits.append("grape") + print("After append: \(fruits)") + print("First fruit: \(fruits[0])") + + // Dictionaries + var scores = ["Alice": 95, "Bob": 87, "Charlie": 92] + print("Dictionary: \(scores)") + scores["David"] = 88 + print("After adding David: \(scores)") + + // Sets + var uniqueNumbers: Set = [1, 2, 3, 3, 4] + print("Set (no duplicates): \(uniqueNumbers)") + print() + } + + // MARK: - Closures + static func closures() { + print("--- Closures ---") + + // Closure as a variable + let sayHello = { (name: String) -> String in + return "Hello, \(name)!" + } + print(sayHello("Swift")) + + // Closure as parameter + let numbers = [1, 2, 3, 4, 5] + let doubled = numbers.map { $0 * 2 } + print("Original: \(numbers)") + print("Doubled: \(doubled)") + + let evenNumbers = numbers.filter { $0 % 2 == 0 } + print("Even numbers: \(evenNumbers)") + print() + } + + // MARK: - Structs and Classes + static func structsAndClasses() { + print("--- Structs and Classes ---") + + // Struct (value type) + struct Person { + var name: String + var age: Int + + func introduce() -> String { + return "Hi, I'm \(name) and I'm \(age) years old." + } + } + + let person = Person(name: "Alice", age: 30) + print(person.introduce()) + + // Class (reference type) + class Vehicle { + var brand: String + var year: Int + + init(brand: String, year: Int) { + self.brand = brand + self.year = year + } + + func description() -> String { + return "\(year) \(brand)" + } + } + + let car = Vehicle(brand: "Tesla", year: 2024) + print("Vehicle: \(car.description())") + print() + } +} diff --git a/Tests/HelloSwiftTests/BasicTests.swift b/Tests/HelloSwiftTests/BasicTests.swift new file mode 100644 index 0000000..07a0fe5 --- /dev/null +++ b/Tests/HelloSwiftTests/BasicTests.swift @@ -0,0 +1,103 @@ +import Testing + +// This file demonstrates basic Swift testing +// Tests help verify that your code works correctly + +@Suite("Swift Basics Tests") +struct BasicTests { + + // MARK: - String Tests + @Test("String concatenation works correctly") + func testStringConcatenation() { + let greeting = "Hello" + let name = "Swift" + let message = "\(greeting), \(name)!" + + #expect(message == "Hello, Swift!") + } + + @Test("String length is calculated correctly") + func testStringLength() { + let word = "Swift" + #expect(word.count == 5) + } + + // MARK: - Math Tests + @Test("Addition works correctly") + func testAddition() { + let result = 2 + 3 + #expect(result == 5) + } + + @Test("Multiplication works correctly") + func testMultiplication() { + let result = 4 * 5 + #expect(result == 20) + } + + // MARK: - Array Tests + @Test("Arrays can be created and accessed") + func testArrays() { + let numbers = [1, 2, 3, 4, 5] + + #expect(numbers.count == 5) + #expect(numbers[0] == 1) + #expect(numbers[4] == 5) + } + + @Test("Array map transforms elements") + func testArrayMap() { + let numbers = [1, 2, 3] + let doubled = numbers.map { $0 * 2 } + + #expect(doubled == [2, 4, 6]) + } + + @Test("Array filter selects matching elements") + func testArrayFilter() { + let numbers = [1, 2, 3, 4, 5, 6] + let evenNumbers = numbers.filter { $0 % 2 == 0 } + + #expect(evenNumbers == [2, 4, 6]) + } + + // MARK: - Dictionary Tests + @Test("Dictionaries store key-value pairs") + func testDictionaries() { + let scores = ["Alice": 95, "Bob": 87] + + #expect(scores["Alice"] == 95) + #expect(scores["Bob"] == 87) + #expect(scores.count == 2) + } + + // MARK: - Optional Tests + @Test("Optionals can contain values") + func testOptionalWithValue() { + let optionalName: String? = "Swift" + + #expect(optionalName != nil) + #expect(optionalName == "Swift") + } + + @Test("Optionals can be nil") + func testOptionalNil() { + let optionalValue: Int? = nil + + #expect(optionalValue == nil) + } + + // MARK: - Struct Tests + @Test("Structs can be created and used") + func testStructs() { + struct Point { + var x: Int + var y: Int + } + + let point = Point(x: 10, y: 20) + + #expect(point.x == 10) + #expect(point.y == 20) + } +}