快看Sample代码,速学Swift语言(2)-基础介绍

Swift语言是一个新的编程语言,用于iOS, macOS, watchOS, 和 tvOS的开发,不过Swift不少部份内容,咱们能够从C或者Objective-C的开发经验得到一种熟悉感。Swift提供不少基础类型,如Int,String,Double,Bool等类型,它和Objective-C的相关类型对应,不过他是值类型,而Objective-C的基础类型是引用类型,另外Swift还提供了几个集合类型,如ArraySet, 和 Dictionary;Swift引入一些Objective-C里面没有的元祖类型,这个在C#里却是有相似的,也是这个名词。 Swift语言是一种类型安全的强类型语言,不是相似JavaScript的弱类型,可以在提供开发效率的同时,减小常规出错的可能,使咱们在开发阶段尽可能发现一些类型转换的错误并及时处理。编程

常量和变量

let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0

 常量用let定义,变量用var定义,它们都可以经过自动推导类型,如上面的就是指定为整形的类型。swift

也能够经过逗号分开多个定义,以下所示安全

var x = 0.0, y = 0.0, z = 0.0

 若是咱们的变量没有初始化值来肯定它的类型,咱们能够经过指定类型来定义变量,以下所示app

var welcomeMessage: String

var red, green, blue: Double

 变量的打印,能够在输出字符串中用括号包含变量输出,括号前加斜杠 \ 符号。less

print(friendlyWelcome)
// Prints "Bonjour!"

print("The current value of friendlyWelcome is \(friendlyWelcome)")
// Prints "The current value of friendlyWelcome is Bonjour!"

 

注释符

// This is a comment.

/* This is also a comment
 but is written over multiple lines. */

/* This is the start of the first multiline comment.
 /* This is the second, nested multiline comment. */
 This is the end of the first multiline comment. */

 上面分别是常规的的注释,以及Swift支持嵌套的注释符号编程语言

 

分号

Swift语句的划分能够不用分号,不过你加分号也能够,若是加分号,则能够多条语句放在一行。ide

let cat = "🐱"; print(cat)

 

整型

let minValue = UInt8.min  // minValue is equal to 0, and is of type UInt8
let maxValue = UInt8.max  // maxValue is equal to 255, and is of type UInt8

通常状况下,咱们不须要指定具体的Int类型,如Int32,Int64,咱们通常采用int类型便可,这样能够在不一样的系统平台有不一样的意义。函数

在32位平台,Int表明是Int32ui

在64位平台,Int表明Int64this

 

浮点数字

Swift的浮点数字类型包括有Float(单精度)和Double(双精度)两个类型,Float表明32位浮点数字,Double表明64位浮点数字。

默认经过小数值推导的变量或者常量的类型是Double,而非Float。

 

数字文字

let decimalInteger = 17
let binaryInteger = 0b10001       // 17 二进制
let octalInteger = 0o21           // 17 八进制
let hexadecimalInteger = 0x11     // 17 十六进制

 

let decimalDouble = 12.1875
let exponentDouble = 1.21875e1  //科学计数法 1.21875*10
let hexadecimalDouble = 0xC.3p0 // p0表明 2的0次方

 上面是科学计数方式的几种方式

 

let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1

 上面是使用0代替补齐签名数字,以及下划线来标识数字分割,方便阅读

 

let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine

 常量 three 初始化位整形类型, pointOneFourOneFiveNine 推导为Double类型,而pi则经过Double转换推导为Double类型,这样右边两个都是Double类型,能够进行相加的运算处理了。

 

布尔类型

let orangesAreOrange = true
let turnipsAreDelicious = false

 这个没有什么好讲的,就是语言默认有布尔类型提供,相对于Objective-C的非0则为True而言,布尔类型只有两个字,True或者False。

布尔类型能够用于条件判断等处理,以下

if turnipsAreDelicious {
    print("Mmm, tasty turnips!")
} else {
    print("Eww, turnips are horrible.")
}

 

元祖类型

元祖类型就是组合多个值的一个对象类型,在组合中的类型能够是任何Swift的类型,并且没必要全部的值为相同类型。

let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")

 另外能够解构对应的元祖类型的值到对应的常量或者变量里面,以下代码

let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
// Prints "The status code is 404"
print("The status message is \(statusMessage)")
// Prints "The status message is Not Found"

 也能够经过下划线来忽略相关的值,以下

let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")

 元祖对象里面的值能够经过数字索引来引用,如0,1的属性,以下

print("The status code is \(http404Error.0)")
// Prints "The status code is 404"
print("The status message is \(http404Error.1)")
// Prints "The status message is Not Found"

 

可空类型

这个和C#里面的可空类型是对应的,也就是对象可能有值,也可能没有值

let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber 推导类型为 "Int?", 或者 "optional Int"

Int类型的构造函数为可空构造函数,有可能转换失败,所以返回的为可空Int类型

可空类型能够经过设置nil,来设置它为无值状态

var serverResponseCode: Int? = 404
// serverResponseCode contains an actual Int value of 404
serverResponseCode = nil
// serverResponseCode now contains no value

 对于可空类型,若是确认它的值非空,那么能够强行解构它的值对象,访问它的值在变量后面增长一个!符号,以下所示

if convertedNumber != nil {
    print("convertedNumber has an integer value of \(convertedNumber!).")
}

 通常状况下,咱们能够经过可空绑定的方式来处理这种对象的值,语句语法以下所示

if let constantName = someOptional {
    statements
}

 具体的语句以下所示

if let actualNumber = Int(possibleNumber) {
    print("\"\(possibleNumber)\" has an integer value of \(actualNumber)")
} else {
    print("\"\(possibleNumber)\" could not be converted to an integer")
}
// Prints ""123" has an integer value of 123"

 也能够多个let的可空绑定语句一块儿使用

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

 

解包可空类型能够经过!符号进行处理,通常状况以下所示进行判断

let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // requires an exclamation mark
 
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // no need for an exclamation mark

 也可使用可空绑定的let 语句进行隐式的解包,以下所示

if let definiteString = assumedString {
    print(definiteString)
}
// Prints "An implicitly unwrapped optional string."

 

错误处理

函数抛出异常,经过在函数里面使用throws进行声明,以下

func canThrowAnError() throws {
    // this function may or may not throw an error
}

 捕捉函数抛出的异常代码以下

do {
    try canThrowAnError()
    // no error was thrown
} catch {
    // an error was thrown
}

 详细的案例代码以下所示

func makeASandwich() throws {
    // ...
}
 
do {
    try makeASandwich()
    eatASandwich()
} catch SandwichError.outOfCleanDishes {
    washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
    buyGroceries(ingredients)
}

 

断言调试

Swift提供一些标准库函数来进行断言调试,分为断言和预设条件的处理两部分。

断言调试仅仅在Debug调试模式运行,而预设条件则是调试模式和产品发布后都会运行的。

let age = -3
assert(age >= 0, "A person's age can't be less than zero.")
// This assertion fails because -3 is not >= 0.

 

if age > 10 {
    print("You can ride the roller-coaster or the ferris wheel.")
} else if age > 0 {
    print("You can ride the ferris wheel.")
} else {
    assertionFailure("A person's age can't be less than zero.")
}

 预设条件代码以下,用来对一些条件进行校验

// In the implementation of a subscript...
precondition(index > 0, "Index must be greater than zero.")
相关文章
相关标签/搜索