Swift 基础语法

常量和变量的声明

 import UIKit

// 声明常量和变量
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0

多个变量同时声明

// 一次声明多个常量或者变量,用,分割
var x = 0.0, y = 0.0, z = 0.0

显示指定变量类型

// 类型指定
var welcomeMessage: String
welcomeMessage = "Hello"

// 一次指定多个变量类型(变量间用,分割,只需要在最后一个变量指定类型)
var red, green, blue: Double

字符串插值打印法

// 字符串插值打印法
var friendlyWelcome = "Hello"
friendlyWelcome = "Boujour!"

print("The current value of friendlyWelcom is \(friendlyWelcome)")

类型转换的使用

// 类型转换
let twoThousand: UInt16 = 2_000
let one: UInt8 = 1

// 直接相加会出错,需要做类型转换
// twoThousand + one

let twoThousandAndOne = twoThousand + UInt16(one)
print(twoThousandAndOne)

别名的使用

// 别名
typealias AudioSample = UInt16

var maxAmplitudeFound = AudioSample.max
print(maxAmplitudeFound)

Bool类型的使用

// Bool 类型
let turnipsAreDelicious = false
if turnipsAreDelicious {
    print("Mmm, tasty turnips!")
} else {
    print("Eww, turnips ar horrible.")
}

let i = 1
// if i {} 这种判断会出错, i不是Bool 类型
if i == 1{
    print("i 的值是1哦")
}

元组的使用

// 元组
let http404Error = (404, "Not Found")

// 通过下标访问
print("The status code is \(http404Error.0)")
print("The status message is \(http404Error.1)")

// 通过分解元组访问
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
print("The status message is \(statusMessage)")

// 通过分解元组访问时,不关心的元素可以用_代替
let (justStatusCode, _) = http404Error
print("The status code is \(justStatusCode)")

// 通过定义元组时命名访问
let http200Status = (statusCode: 200, description: "OK")
print("The status code is \(http200Status.statusCode)")
print("The status message is \(http200Status.description)")

可选类型的使用

// 可选类型
var serverResponseCode: Int? = 404
serverResponseCode = nil

let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)

if convertedNumber != nil {
    //print("convertedNumber has an interger value of \(convertedNumber)")
    // 如果不做强制拆包输出为convertedNumber has an interger value of Optional(123),不是想要的结果, 加一个!做强制拆包
    print("convertedNumber has an interger value of \(convertedNumber!)")
}

// 可选绑定
if let otherConvertedNumber = convertedNumber {
    print("convertedNumber has an interger value of \(otherConvertedNumber)")
}

if let firstNumber = Int("4"), let secondNumber = Int("42") where firstNumber < secondNumber && secondNumber < 100 {
    print("\(firstNumber) < \(secondNumber) < 100")
}

if let firstNumber = Int("4")
{
    if let secondNumber = Int("42")
    {
        if firstNumber < secondNumber && secondNumber < 100
        {
            print("\(firstNumber) < \(secondNumber) < 100")
        }
    }
}

断言的使用

// assert 断言的使用
let age = 10
assert(age > 0, "A person's age cannot be less than zero")

你可能感兴趣的:(Swift 基础语法)