Swift is a fantastic way to write software, whether it’s for phones, desktops, servers, or anything else that runs code. It’s a safe, fast, and interactive programming language that combines the best in modern language thinking with wisdom from the wider Apple engineering culture and the diverse contributions from its open-source community. The compiler is optimized for performance and the language is optimized for development, without compromising on either.
Apple Inc. “The Swift Programming Language (Swift 5.2)。” Apple Books.
The Basics
- Constants and Variables
let maxValue: Int = 10
var x = 0.0, y = 0.0, z = 0.0
var message = "hello"
message += " ketty."
print("\(message)")
- Comments
// This is a comment.
/* This is also a comment
but is written over multiple lines. */
Type Safety and Type Inference
Swift is a type-safe language.Type Aliases
typealias Age = UInt8
var age: Age = 30
- Types
Integers: Int,
Floating: Double, Float
Booleans: true, false
Tuples: let httpForbidden:(Int, String) = (403, "forbidden")
Optionals: var nickname: String?
var optional: String?
optional = "hello andy."
let unwrapping = optional!//force unwarpping,dangerous, not recommend. optional must have value.
if let optional = optional {// preferred unwarpping
print(optional)
}
print(unwrapping)
nil: You set an optional variable to a valueless state by assigning it the special value nil. You can’t use nil with non-optional constants and variables.
In Swift, nil isn’t a pointer—it’s the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.
- Error Handling
func throwError() throws {
// this function may or may not throw an error
}
do {
try throwError()
// no error was thrown
} catch {
// an error was thrown
print(error)// "error" is default object with Error.
}
- Assertions and Preconditions
- Debugging with Assertions
var age = -3
assert(age>=0)
if age < 0 {
assertionFailure("age must +")
}
- Enforcing Preconditions
var age = -3
precondition(age >= 0, "age must +")