文章目录
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 完善,增加目录和更多的注释