(一)Swift [The Basics]

2020-04-14  本文已影响0人  Lee_Jo

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

let maxValue: Int = 10
var x = 0.0, y = 0.0, z = 0.0
var message = "hello"
message += " ketty."
print("\(message)")
// This is a comment.
/* This is also a comment
but is written over multiple lines. */
typealias Age = UInt8
var age: Age = 30
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.
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.
}
  1. Debugging with Assertions
var age = -3
assert(age>=0)

if age < 0 {
            assertionFailure("age must +")
 }
  1. Enforcing Preconditions
var age = -3
precondition(age >= 0, "age must +")
上一篇 下一篇

猜你喜欢

热点阅读