0Pricing
Swift Academy · Aula

Pacotes de biblioteca versus executáveis

Entenda os pacotes de biblioteca e executáveis do SwiftPM: como declarar produtos/alvos, consumir bibliotecas e executar arquivos executáveis.

Pacotes de biblioteca versus executáveis é uma aula grátis de Swift Academy no CoddyKit. Esta é a aula 1 de 3. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Swift Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Swift Academy inclui 3 aulas no total.

Dois tipos de produto

Os pacotes SwiftPM podem ser distribuídos como uma library (código a ser importado) ou um executable (uma ferramenta executável).

  • Declare os produtos em Package.swift
  • Organize os destinos e os códigos-fonte
  • Use bibliotecas; execute ferramentas

Noções básicas de uma library

Uma library expõe módulos que outras partes do código podem import. Nenhum ponto de entrada é necessário.

// Package.swift (illustrative library)
// import PackageDescription
// let package = Package(
//   name: "GreeterLib",
//   products: [
//     .library(name: "GreeterLib", targets: ["GreeterLib"]),
//   ],
//   targets: [
//     .target(name: "GreeterLib"),
//     .testTarget(name: "GreeterLibTests", dependencies: ["GreeterLib"]),
//   ]
// )
//
// Sources/GreeterLib/Greeter.swift
public struct Greeter {
    public init() {}
    public func hello(_ name: String) -> String { "Hello, \\(name)!" }
}
print(Greeter().hello("Ana")) // demo run

Noções básicas de um executable

Um executable tem um ponto de entrada (main.swift) e cria um binário executável (swift run).

// Package.swift (illustrative executable)
// import PackageDescription
// let package = Package(
//   name: "greeter",
//   products: [ .executable(name: "greeter", targets: ["App"]) ],
//   targets: [ .executableTarget(name: "App") ]
// )
//
// Sources/App/main.swift
let args = CommandLine.arguments.dropFirst()
let who = args.first ?? "world"
print("Hello, \\(who)")

Usar bibliotecas como dependências

Use .package e .product no consumidor para importar uma biblioteca. Fixe a dependência com versões semânticas (por exemplo, from: "1.0.0").

// In the consumer's Package.swift (illustrative):
// dependencies: [
//   .package(url: "https://example.com/GreeterLib.git", from: "1.0.0")
// ],
// targets: [
//   .executableTarget(
//     name: "App",
//     dependencies: [ .product(name: "GreeterLib", package: "GreeterLib") ]
//   )
// ]
//
// Sources/App/main.swift
// import GreeterLib
struct Dummy {}
print("Add import GreeterLib in your app to use its APIs.")

Dividir responsabilidades

Compartilhe o código: coloque a lógica central em uma library e mantenha o executable como um invólucro simples.

// Package.swift can expose both a library and an executable:
// products: [
//   .library(name: "GreeterLib", targets: ["GreeterLib"]),
//   .executable(name: "greeter", targets: ["GreeterCLI"]),
// ],
// targets: [
//   .target(name: "GreeterLib"),
//   .executableTarget(name: "GreeterCLI", dependencies: ["GreeterLib"]),
// ]
//
// Reuse logic in the library; keep CLI thin.
print("Tip: put reusable logic in the library; the CLI depends on it.")

Comandos para criar e executar

Crie bibliotecas com swift build e execute os testes com swift test. Execute ferramentas com swift run <name>.

// Library: build & test
//   swift build
//   swift test
//
// Executable: run & release
//   swift run greeter Ana
//   swift build -c release
//
// Artifact:
//   .build/release/greeter
print("Use swift run for executables; import libraries into apps.")

Definição de library e executable

Verificação rápida: o que diferencia uma library de um executable no SwiftPM?

Recapitulação

Recapitulação: use uma library para compartilhar código entre aplicativos e um executable para distribuir uma ferramenta de CLI. Declare produtos e destinos em Package.swift e dependa de bibliotecas usando .package + .product.

Perguntas Frequentes

A aula “Pacotes de biblioteca versus executáveis” é grátis?

Sim — o texto completo de “Pacotes de biblioteca versus executáveis” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Swift Academy, atualize para CoddyKit PRO. O curso de Swift Academy inclui 3 aulas no total.

O que vou aprender em “Pacotes de biblioteca versus executáveis”?

Entenda os pacotes de biblioteca e executáveis do SwiftPM: como declarar produtos/alvos, consumir bibliotecas e executar arquivos executáveis. Você pratica Swift Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Swift Academy?

Nenhuma experiência prévia é necessária. Swift Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 3.

Quanto tempo leva a aula “Pacotes de biblioteca versus executáveis”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Swift Academy?

Sim. Cada aula de Swift Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Pacotes de biblioteca versus executáveis
  2. Versionamento semântico e marcação de lançamentos
  3. Noções básicas de CI com swift test e artefatos
← Voltar para Swift Academy