文章目錄
Swift語言基礎
更新時間:2020-03-24
Swift版本:Swift 5
1.1 Swift 和 Playground簡介
/* 1.1 Swift 和 Playground簡介
* 使用XCode新建playground項目,複製一下代碼查看效果!
*/
var str = "Hello, playground"
var a = 12,b=21
print(str)
print(a+b)
1.2 常量、變量和數據類型
數據類型
let name = "John" // 常量
var age = 20 // 變量
let printStr = "name:\(name),\(age)" // 字符串插值
// 定義一個類
struct Person{
let firstName: String
let lastName: String
func sayHello() {
print("Hello there!My name is \(firstName) \(lastName).")
}
}
// 初始化類的對象實列
let person = Person(firstName: "xu", lastName: "yingchun") // 字面量
person.sayHello()
類型安全和類型推斷
let playerName = "name"
var playerScore = 1000
var numberWitchDicimals = 17.5
var gameOver = false
// playerName = playerScore
// playerScore = numberWitchDicimals
// Will be flagged for mismatched type, will not compile.
let cityName: String = "San Francisco"
let pi: Double = 3.1415927
let number: Double = 3
print(number)
1.3 運算符
// 分配值
var shoeSize = 8
shoeSize = 9 // Reassigns shoeSize to 9
// 基本算數
var opponentScore = 3 * 8 // opponentScore has a value of 24
var myScore = 100 / 4 // myScore has a value of 25
var totalScore = opponentScore * myScore
myScore += 3
myScore -= 5
myScore *= 2
myScore /= 2
var x = 2,y = 3,z = 5
x + y * z // Equals 17
let a1 = 3,b1 = 0.1415927
let pi1 = Double(a1) + b1 // 數值型類型轉換
1.4 控制流程
// if條件
let temperature = 100
if temperature >= 100 {
print("The water is boiling.")
}else if temperature < 0 {
print("The water is cold.")
}else{
print("The water is not boiling.")
}
// switch語句
let numberOfWheels = 2
switch numberOfWheels{
case 1:
print("Unicycle") // 不需要break,會直接跳出,如果要向下執行,添加fallthrough關鍵字
case 2:
print("Bicycle")
default:
print("That's a lot of wheels!")
}
// switch語句支持字符串
let character = "z"
switch character{
case "a","e","i","o","u":
print("This character is a vowel.")
default:
print("This character is a consonat.")
}
// switch語句支持區間匹配
let distance = 100
switch distance {
case 0...9:
print("Your destination is close.")
case 10...99:
print("Your destination is a medium distance from here.")
default:
print("Are you sure you want to travel this far?")
}
1.5 循環
for
// Swift5不支持for循環?,作者使用for-in代替之
for var i:=0;i<10;i++{
print(i)
}
for-in
for index in 1..<5 {
print("This is number\(index)")
}
let names2 = ["Joseph", "Cathy", "Winston"]
for item in names2 {
print("Hello \(item)")
}
let vehicles = ["unicycle": 1, "bicycle":2]
for (key,value) in vehicles {
print("A \(key) has \(value) wheels")
}
while
var numberOfLives = 3
var stillAlive = true
while stillAlive {
numberOfLives -= 1
if numberOfLives == 0{
break
}
}
1.6 集合
數組
var names: [String] = ["Anne","Gray"]
var numbers = [1, -3, 24, 114]
if numbers.contains(24){
print("There is a 24")
}
numbers[1] = 23
numbers.append(2) // 追加
numbers+=[1,3] // 一次追加多個元素
numbers.insert(31, at: 0)
numbers.remove(at: 0)
let array1 = [1,2,3]
let array2 = [4,5,6]
let arrayAll = [array1,array2] // [[1,2,3],[4,5,6]] // 二維數組
字典
var myDictionary = [String:Int]()
var myDictionary2 = Dictionary<String,Int>()
myDictionary["Oli"] = 399 //添加
if let oldValue = myDictionary.updateValue(200, forKey: "Oli") {//更新
print("Richard's old value was \(oldValue)")
}
var scores = ["Richard": 500, "Luke": 100] //訪問字典
let players = Array(scores.keys) // ["Richard", "Luke"]
let points = Array(scores.values)// [500, 100]
if let myScore = scores["Luke"] {
print(myScore)
}else{
print("Not find")
}
1.7 字符串
let greeting = "Hello \"world\""
var myString = ""
if myString.isEmpty {
print("The string is empty")
}
// 串聯和插值
myString = greeting + "yes"
let age1 = 30
let name1 = "Rick"
print("\(name1) is \(age1+5) years old")
// 字符串相等
if myString != greeting {
print("The are not the same")
}
if greeting.contains("Hello") {
print("Making an introduction")
}
print("the greeting len=\(greeting.count)")
1.8 函數
func displayPi(){
print("3.1415927")
}
displayPi() // 調用
func triple(value: Int){
let result = value * 3
print("If you multiple \(value) by 3,you'll get \(result).")
}
triple(value: 20) // 帶參數
func triple2(_ value: Int){
triple(value: value)
}
triple2(10) // 自變量標籤,可省略參數標籤
// 默認參數值和
// 返回多個值
func multiple(_ firstNumber: Int, secondNumber: Int = 10) -> (a: Int,b: Int){
return (firstNumber * secondNumber , secondNumber)
}
var multipleResult = multiple(2)
print("Return=\(multipleResult) a=\(multipleResult.a) b=\(multipleResult.b)")
1.9 枚舉
enum MsgType{
case Text
case Image
case Video
case File
}
1.10 類
構造函數和析構
var stringInit = String.init() // ""
var integerInit = Int.init() // 0
class Temperature{
var celsius: Double
// 帶一個參數的構造函數
init(celsius: Double){
self.celsius = celsius
}
// 可以重載,和java不同,可以通過參數名字區分開而不是參數數量
init(fahrenheit: Double){
self.celsius = (fahrenheit - 32) / 1.8
}
deinit{
print("對象被消耗")
}
}
var boiling = Temperature(fahrenheit: 212.0)
boiling = nil // 不再指向原來的對象,GC幫助我們自動銷燬該對象
屬性和方法
class Person{
let maxAge: 200 // 常量
var name: String // 變量
static var numberOfPerson = 0 // 類(靜態)屬性
// 對象(實例)方法
func walk(){
}
// 類(靜態)方法,使用class修飾
class func convert(){
}
}
繼承
class Scientist{
func doSomeThing() {
}
// final 修飾的屬性和方法,子類不能重寫
final func finalMethod(){
}
}
class Geologist: Scientist{
override func doSomeThing() {
super.doSomeThing() // super調用父類方法
}
}
計算屬性
class Temperature2{
var celsius: Double
var fahrenheit: Double{
get{ // 變量可讀
return celsius * 1.8 + 32
}
set{ // 變量可寫
celsius = newValue / 1.8
}
}
}
屬性觀察器
struct StepCounter{
var totalSteps: Int = 0 {
willSet{
print("About to set totalSteps to \(newValue)")
}
didSet{
if totalSteps > oldValue{
print("Added \(totalSteps - oldValue)")
}
}
}
}
var stepCounter = StepCounter()
stepCounter.totalSteps = 40
stepCounter.totalSteps = 100
1.11 結構體
定義
注意:
結構體是值類型,類是引用類型。
struct Car{
var make: String
var year: Int = 0
func startEngine() {}
func drive() {}
}
var firstCar = Car(make: "Ford", year: 2013)
firstCar.startEngine()
firstCar.drive()
拷貝
var t1 = Temperature2(celsius: 2.0)
var t2 = t1
t2.celsius = 10.0 // 拷貝結構體,所以不會影響原結構體的值,和“類”的不同之處,如果分不清,全部使用Class即可。
print(t1.celsius)
1.12 協議(接口)
protocol CanFly {
var mustBeSettable: Int { get set} // 必須實現可讀可寫的屬性
class func someTypeMethod() // 類(靜態)方法
func random() -> Double // 對象(實例)方法
}
1.13 高級
可選鏈和類型轉換
class Residence{
var numberOfRooms = 1
}
class Person{
var residence: Residence? // 可爲nil
}
let john = Person()
let rootCount = john.residence!.numberOfRooms // 報錯
// 正確的寫法
if let roomCount = john.resindece?.numberOfRooms {
print("房間數量爲:\(roomCount))")
}else{
print("房間數量爲空")
}
閉包
func compare(a: String, b: String) -> Bool{
return a > b
}
let namges = ["Bob","Alice","Barry","Ewa"]
var reversed = sorted(names,compare) // 排序
println(reversed)
// 閉包語法
//{(paremeters) -> returnType in
// statements
//}
// 這裏可省略compare方法的定義,更簡潔
reversed = sorted(names,{(a: String, b: String) -> Bool in
return a > b
})
// 可放在一行,可讀性不是很好,不是很推薦
reversed = sorted(names,{(a: String, b: String) -> Bool in return a > b })
泛型
struct Stack<T>{
var items = [T]() // 一個數組
mutating func push(item:T){
items.append(item)
}
mutating func pop() -> T{
return items.removeLast()
}
}
var stackOfStrings = Stack<String>() // 初始化一個Stack<String>類型,注意類型是:Stack<String>,不是Stack
stackOfStrings.push("a")
stackOfStrings.push("b")
print(stackOfStrings.pop())
完整的Playground項目
import UIKit
/* 1.1 Swift 和 Playground簡介
* 使用XCode新建playground項目,複製一下代碼查看效果!
*/
var str = "Hello, playground"
var a = 12,b=21
print(str)
print(a+b)
/* 1.2 常量、變量和數據類型 */
// 數據類型
let name = "John" // 常量
var age = 20 // 變量
let printStr = "name:\(name),\(age)" // 字符串插值
struct Person{
let firstName: String
let lastName: String
func sayHello() {
print("Hello there!My name is \(firstName) \(lastName).")
}
}
let person = Person(firstName: "xu", lastName: "yingchun")
person.sayHello()
// 類型安全和類型推斷
let playerName = "name"
var playerScore = 1000
var numberWitchDicimals = 17.5
var gameOver = false
// playerName = playerScore
// playerScore = numberWitchDicimals
// Will be flagged for mismatched type, will not compile.
let cityName: String = "San Francisco"
let pi: Double = 3.1415927
let number: Double = 3
print(number)
/* 1.3運算符 */
// 分配值
var shoeSize = 8
shoeSize = 9 // Reassigns shoeSize to 9
// 基本算數
var opponentScore = 3 * 8 // opponentScore has a value of 24
var myScore = 100 / 4 // myScore has a value of 25
var totalScore = opponentScore * myScore
myScore += 3
myScore -= 5
myScore *= 2
myScore /= 2
var x = 2,y = 3,z = 5
x + y * z // Equals 17
let a1 = 3,b1 = 0.1415927
let pi1 = Double(a1) + b1 // 數值型類型轉換
/* 1.4 控制流程 */
let temperature = 100
if temperature >= 100 {
print("The water is boiling.")
}else if temperature < 0 {
print("The water is cold.")
}else{
print("The water is not boiling.")
}
let numberOfWheels = 2
switch numberOfWheels{
case 1:
print("Unicycle")
case 2:
print("Bicycle")
default:
print("That's a lot of wheels!")
}
let character = "z"
switch character{
case "a","e","i","o","u":
print("This character is a vowel.")
default:
print("This character is a consonat.")
}
let distance = 100
switch distance {
case 0...9:
print("Your destination is close.")
case 10...99:
print("Your destination is a medium distance from here.")
default:
print("Are you sure you want to travel this far?")
}
/* 2.1字符串 */
let greeting = "Hello \"world\""
var myString = ""
if myString.isEmpty {
print("The string is empty")
}
// 串聯和插值
myString = greeting + "yes"
let age1 = 30
let name1 = "Rick"
print("\(name1) is \(age1+5) years old")
// 字符串相等
if myString != greeting {
print("The are not the same")
}
if greeting.contains("Hello") {
print("Making an introduction")
}
print("the greeting len=\(greeting.count)")
/* 2.2函數 */
func displayPi(){
print("3.1415927")
}
displayPi()
func triple(value: Int){
let result = value * 3
print("If you multiple \(value) by 3,you'll get \(result).")
}
// 自變量標籤,可省略參數標籤
triple(value: 20)
func triple2(_ value: Int){
triple(value: value)
}
triple2(10)
// 默認參數值和返回多個值
func multiple(_ firstNumber: Int, secondNumber: Int = 10) -> (a: Int,b: Int){
return (firstNumber * secondNumber , secondNumber)
}
var multipleResult = multiple(2)
print("Return=\(multipleResult) a=\(multipleResult.a) b=\(multipleResult.b)")
/* 2.3結構 */
struct Car{
var make: String
var year: Int = 0
func startEngine() {}
func drive() {}
}
var firstCar = Car(make: "Ford", year: 2013)
firstCar.startEngine()
firstCar.drive()
//構造器
var stringInit = String.init() // ""
var integerInit = Int.init() // 0
struct Temperature{
var celsius: Double
init(celsius: Double){
self.celsius = celsius
}
init(fahrenheit: Double){
self.celsius = (fahrenheit - 32) / 1.8
}
}
var boiling = Temperature(fahrenheit: 212.0)
//計算屬性
struct Temperature2{
var celsius: Double
var fahrenheit: Double{
return celsius * 1.8 + 32
}
}
//屬性觀察器
struct StepCounter{
var totalSteps: Int = 0 {
willSet{
print("About to set totalSteps to \(newValue)")
}
didSet{
if totalSteps > oldValue{
print("Added \(totalSteps - oldValue)")
}
}
}
}
var stepCounter = StepCounter()
stepCounter.totalSteps = 40
stepCounter.totalSteps = 100
//拷貝
var t1 = Temperature2(celsius: 2.0)
var t2 = t1
t2.celsius = 10.0 // 拷貝結構體,所以不會影響原結構體的值
print(t1.celsius)
/* 2.4類與繼承 */
class Scientist{
func doSomeThing() {
}
}
class Geologist: Scientist{
override func doSomeThing() {
}
}
/* 2.5集合 */
// 數組
var names: [String] = ["Anne","Gray"]
var numbers = [1, -3, 24, 114]
if numbers.contains(24){
print("There is a 24")
}
numbers[1] = 23
numbers.append(2) // 追加
numbers+=[1,3] // 一次追加多個元素
numbers.insert(31, at: 0)
numbers.remove(at: 0)
let array1 = [1,2,3]
let array2 = [4,5,6]
let arrayAll = [array1,array2] // [[1,2,3],[4,5,6]] // 二維數組
//字典
var myDictionary = [String:Int]()
var myDictionary2 = Dictionary<String,Int>()
myDictionary["Oli"] = 399 //添加
if let oldValue = myDictionary.updateValue(200, forKey: "Oli") {//更新
print("Richard's old value was \(oldValue)")
}
var scores = ["Richard": 500, "Luke": 100] //訪問字典
let players = Array(scores.keys) // ["Richard", "Luke"]
let points = Array(scores.values)// [500, 100]
if let myScore = scores["Luke"] {
print(myScore)
}else{
print("Not find")
}
/* 2.6循環 */
// for/for-in
for index in 1..<5 {
print("This is number\(index)")
}
let names2 = ["Joseph", "Cathy", "Winston"]
for item in names2 {
print("Hello \(item)")
}
let vehicles = ["unicycle": 1, "bicycle":2]
for (key,value) in vehicles {
print("A \(key) has \(value) wheels")
}
// while
var numberOfLives = 3
var stillAlive = true
while stillAlive {
numberOfLives -= 1
if numberOfLives == 0{
break
}
}
更新記錄
- 2019.08.23 初稿
- 2020.03.07 完善,增加目錄和更多的註釋