Swift study note (1)

Doc

  • Getting started: https://www.swift.org/getting-started/
  • The Swift Programing Launguage: https://docs.swift.org/swift-book/documentation/the-swift-programming-language
    • Chinese: https://gitbook.swiftgg.team/swift

Create a basic application with command line tool

mkdir hello
cd hello
swift package init --name hello --type executable

out dir:

├── Package.swift
└── Sources
    └── main.swift

Package.swift is the manifest file for Swift. It’s where you keep metadata for your project, as well as dependencies.

run:

❯ swift run
Building for debugging...
[1/1] Write swift-version--58304C5D6DBC2206.txt
Build complete! (0.18s)
Hello, world!

Add dependency

Package.swift

// swift-tools-version: 5.10
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "hello",
    dependencies: [
        .package(url: "https://github.com/apple/example-package-figlet", branch: "main")
        ],
    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: "hello",
            dependencies: [
                .product(name: "Figlet", package: "example-package-figlet")
            ],
            path: "Sources"),
    ]
)

Sources/main.swift

// The Swift Programming Language
// https://docs.swift.org/swift-book
import Figlet

@main
struct FigletTool {
    static func main() {
        Figlet.say("Hello, Swift!")
    }
}

run:

Argument parsing

via a dependency called swift-argument-parser

Package.swift

// swift-tools-version: 5.10
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "hello",
    dependencies: [
        .package(url: "https://github.com/apple/example-package-figlet", branch: "main"),
        .package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0" ),
        ],
    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: "hello",
            dependencies: [
                .product(name: "Figlet", package: "example-package-figlet"),
                .product(name: "ArgumentParser", package: "swift-argument-parser")
            ],
            path: "Sources"),
    ]
)

Sources/main.swift

// The Swift Programming Language
// https://docs.swift.org/swift-book
import Figlet
import ArgumentParser

@main
struct FigletTool: ParsableCommand {
    @Option(help: "Specify the input")
    public var input: String

    public func run() throws {
    Figlet.say(self.input)
    }
}

run:

- End -
'