SwiftUI-Day2 复杂数据类型

文章目录

  • 吐槽
  • 结果
  • 初始化
    • 数组-Arrays
    • 集合-Sets
    • 元组-Tuples
    • 怎么选择
    • 字典- Dictionaries
  • 创建空集合 - Collections
  • Enumerations
  • Enum associated values
  • Enum raw values

吐槽

Xcode升级,什么appdelegate都没有了,现在全是swiftUI。。。
下面的代码是playground的代码,不是swiftUI View。
参考资料:https://www.hackingwithswift.com/100/swiftui/2
时间:09 October, 2020

结果

运行快捷键:shift+command+回车
删除当前行:option+D

初始化

数组-Arrays

import UIKit

let john = "John Lennon"
let paul = "Paul McCartney"
let george = "George Harrison"
let ringo = "Ringo Starr"

let beatles = [john, paul, george, ringo]
beatles[1]

SwiftUI-Day2 复杂数据类型_第1张图片

集合-Sets

与Array的不同:

  • set元素无序
  • set元素唯一
let colors = Set(["red", "green", "blue"])
let colors2 = Set(["red", "green", "blue", "red", "blue"])

SwiftUI-Day2 复杂数据类型_第2张图片

元组-Tuples

与Array的不同:

  • tuple不能添加或修改
  • 元素类型不能修改
  • 可以通过下标或者关键字访问
var name = (first: "Taylor", last: "Swift")
name.0
name.first

SwiftUI-Day2 复杂数据类型_第3张图片

怎么选择

  • Tuple - 元素有固定的属性
  • Set - 元素唯一,访问速度很快
  • Array - 有重复元素或者有固定的顺序
//Tuple
let address = (house: 555, street: "Taylor Swift Avenue", city: "Nashville")
//Set
let set = Set(["aardvark", "astronaut", "azalea"])
//Array
let pythons = ["Eric", "Graham", "John", "Michael", "Terry", "Terry"]

字典- Dictionaries

import UIKit

let heights = [
    "Taylor Swift": 1.78,
    "Ed Sheeran": 1.73
]
heights["Taylor Swift"]

let temp:[String: Double] = [
    "temperature":35.4
]
temp["temperature"]

//Dictionaries with default value
let favoriteIceCream = [
    "Paul": "Chocolate",
    "Sophie": "Vanilla"
]
favoriteIceCream["Paul"]
//没有找到关键字会显示nil
favoriteIceCream["Charlotte"]
//有了默认值之后
favoriteIceCream["Charlotte", default: "Unknown"]

SwiftUI-Day2 复杂数据类型_第4张图片

创建空集合 - Collections

Arrays, sets, 和 dictionaries都是collections

//空数组
var results = [Int]()
//或者下面这样
var resultss = Array<Int>()
results.append(10)//添加
results.remove(at: 0)//删除
results.append(20)//添加
results[0]//访问

//空字典
var teams = [String: String]()
//或者下面这样
var scores = Dictionary<String, Int>()
teams["teams1"] = "sya"//添加
teams.removeValue(forKey: "teams1")//删除
teams["teams1"]//访问

//array和dictionary用中括号,set用尖括号
//空集
var words = Set<String>()//empty set
var numbers = Set<Int>()
words.insert("hi")//添加
words.remove("hi")//删除
numbers.insert(22)//访问
for value in numbers{
    print(value)
}

Enumerations

枚举类型的作用:防止写错

let result = "failure"
let result2 = "failed"
let result3 = "fail"
enum Result {
    case success
    case failure
}
let result4 = Result.failure

Enum associated values

enum Activity {
    case bored
    case running(destination: String)
    case talking(topic: String)
    case singing(volume: Int)
}
let talking = Activity.talking(topic: "football")

Enum raw values

默认从零开始
SwiftUI-Day2 复杂数据类型_第5张图片

你可能感兴趣的:(Swift)