Xcode升级,什么appdelegate都没有了,现在全是swiftUI。。。
下面的代码是playground的代码,不是swiftUI View。
参考资料:
https://www.hackingwithswift.com/100/swiftui/8
https://www.hackingwithswift.com/100/swiftui/9
时间:10 October, 2020
运行快捷键:shift+command+回车
删除当前行:option+D
struct Sport {
var name: String
}
var tennis = Sport(name: "Tennis")
print(tennis.name)
tennis.name = "Lawn tennis"
struct Sport {
var name: String
var isOlympicSport: Bool
//下面这个属性是计算之后的属性
var olympicStatus: String {
if isOlympicSport {
return "\(name) is an Olympic sport"
} else {
return "\(name) is not an Olympic sport"
}
}
}
let chessBoxing = Sport(name: "Chessboxing", isOlympicSport: false)
print(chessBoxing.olympicStatus)
每次给amount赋值都执行didSet的内容,其实就是上面的计算过的属性
struct Progress {
var task: String
var amount: Int {
didSet {
print("\(task) is now \(amount)% complete")
}
}
}
var progress = Progress(task: "Loading data", amount: 0)
progress.amount = 30
progress.amount = 80
progress.amount = 100
struct City {
var population: Int
func collectTaxes() -> Int {
return population * 1000
}
}
let london = City(population: 9_000_000)
london.collectTaxes()
swift的结构体默认不让在方法里修改属性值,如果要修改需要添加mutating关键字,且实例对象是变量
struct Person {
var name: String
mutating func makeAnonymous() {
name = "Anonymous"
}
}
var person = Person(name: "Ed")
person.makeAnonymous()
let string = "Do or do not, there is no try."
print(string.count)//字符串长度
print(string.hasPrefix("Do"))//判断起始字符
print(string.uppercased())//大写
print(string.sorted())//排序
var toys = ["Woody"]
print(toys.count)
toys.append("Buzz")
toys.firstIndex(of: "Buzz")
print(toys.sorted())
toys.remove(at: 0)
不重载初始化函数
struct User {
var username: String
}
var user = User(username: "twostraws")
重载初始化函数之后,初始化函数没有参数,所以
struct User {
var username: String
init() {
username = "Anonymous"
print("Creating a new user!")
}
}
var user = User()
user.username = "twostraws"
struct Person {
var name: String
init(name: String) {
print("\(name) was born!")
self.name = name
}
}
正常情况每次都会执行FamilyTree
struct FamilyTree {
init() {
print("Creating family tree!")
}
}
struct Person {
var name: String
var familyTree = FamilyTree()
init(name: String) {
self.name = name
}
}
var ed = Person(name: "Ed")
添加lazy关键字之后,第一次调用的时候才会创建该属性
struct Person {
var name: String
lazy var familyTree = FamilyTree()
init(name: String) {
self.name = name
}
}
var ed = Person(name: "Ed")
ed.familyTree
静态属性属于结构体而不是该结构体的实例,所以调用时语法:
结构体.静态属性名
struct Student {
static var classSize = 0
var name: String
init(name: String) {
self.name = name
Student.classSize += 1
}
}
let ed = Student(name: "Ed")
let taylor = Student(name: "Taylor")
print(Student.classSize)
struct Person {
private var id: String
init(id: String) {
self.id = id
}
func identify() -> String {
return "My social security number is \(id)"
}
}
let ed = Person(id: "12345")
ed.identify()