Code · 1 file
Sample Swift File
Swift is Apple’s language for iOS, macOS and server development. The Swift sample is a small program — a customer record, a VIP check and a formatted total — that is the same in every language we offer, so you can compare them side by side.
Swift · 665 B
Sample Swift file
An idiomatic Swift example: a customer record type, a VIP check, a total and a formatted loop — the same program in every language we offer.
CC0 · free for any use · Verified by an independent tool · Report a problem
// Sample Swift program — samplefiles.com
import Foundation
struct Customer {
let id: Int
let name: String
let balance: Double
var isVIP: Bool { balance >= 10_000 }
}
func totalBalance(_ customers: [Customer]) -> Double {
customers.reduce(0) { $0 + $1.balance }
}
let customers = [Customer(id: 1, name: "Ada", balance: 12_500), Customer(id: 2, name: "Grace", balance: 830.5), Customer(id: 3, name: "Linus", balance: 10_000)]
for c in customers {
print(c.name.padding(toLength: 6, withPad: " ", startingAt: 0), String(format: "%10.2f", c.balance), c.isVIP ? "VIP" : "")
}
print("Total:", String(format: "%.2f", totalBalance(customers)))File details
Download from the command line
curl -L -o sample.swift https://files.samplefiles.com/code/swift/sample.swiftwget https://files.samplefiles.com/code/swift/sample.swifthttps://files.samplefiles.com/code/swift/sample.swiftprintf '%s %s\n' 1768fd87dd91accb08c60a3aa8ec47fb587d7f7cc31da2bd452273842a85e992 sample.swift | shasum -a 256 -cOr check the download in your browser with the checksum calculator.