lecture4_Today.png
Notes
1.String.index
The characters in a string
A string is made up of Unicodes, but there's also the concept of a Character.
A character is what a human would perceive to be a single lexical character.
This is true even if a single Character is made up of multiple Unicodes.
一个字符串是由Unicode组成的,但也有character的概念。
一个character就是一个人认为是一个单一的字符,如:1,a,b,...
但是一个character可能是由多个Unicode组成,如(cafe vs. café), e是有一个Unicode组成的,看作是一个character,é是由2个Unicode组成的,也看作是一个character。
对String的索引使用String.index而不是使用index。
如果想要使用Int对string进行索引,可以先将string转成Array,然后对数组进行索引。
let s = "Hello"
let sArray = Array(s) // ["H", "e", "l", "l", "o"]
2.NSAttributedString
Creating and using an NSAttributedString
let attributes: [NSAttributedString.Key: Any] = [
.strokeColor: UIColor.orange,
.strokeWidth: 5.0
]
let attribText = NSAttributedString(string: "Flips: 0", attributes: attributes)
flipCountLabel.attributedText = attribText
3.IBOutlet didSet
下面这个func是用来更新label的,并且设定label的text的strokeColor以及strokeWidth。
func updateFlipCountLabel() {
let attributes: [NSAttributedString.Key: Any] = [
.strokeColor: UIColor.orange,
.strokeWidth: 5.0
]
let attribText = NSAttributedString(string: "FlipCount: \(flipCount)", attributes: attributes)
flipCountLabel.attributedText = attribText
}
由于给定了一个默认值,在展示默认值的时候没有调用didSet里面的内容,所以默认值的展示不会有strokecolor以及strokeWidth
private var flipCount = 0 {
didSet {
updateFlipCountLabel()
}
}
但是在连接IBOutlet的时候,设定了默认值,在这个时候可以再调用一次func updateFlipCountLabel()
@IBOutlet private weak var flipCountLabel: UILabel! {
didSet {
updateFlipCountLabel()
}
}
4.Closures
Swift中只有Class和Closure是引用类型。
将改变闭包的函数写出闭包的形式
func changeSign(operand: Double) -> Double { return -operand }
var operation: (Double) -> Double
1.将除函数名称以外的内容移过来
operation = (operand: Double) -> Double { return -operand }
2.将左大括号移到开始的地方,在return前面加上 in 关键字
operation = { (operand: Double) -> Double in return -operand }
3.Swift可以推断类型,它知道你return的是一个Double类型,它也知道你的operation是一个Double类型的。
operation = { (operand: Double) in return -operand }
operation = { (operand) in return -operand }
4.如果return后面只有一行代码的话,可以将return省略
operation = { (operand: Double) in return -operand }
operation = { (operand) in -operand }
5.你可以将第一个参数的名字改为$0,第二个参数的名字改为$1...,这样你就不需要想参数的名称了,这样可以直接省略in
operation = { -$0 }
Example:
let result = operation(4.0) // -4.0
5.闭包用于属性的初始化
这种初始化对于lazy的属性初始化非常有用。
var someProperty: Type = {
// construct the value of someProperty here
return < the constructed value>
}()
// 末尾的()用于执行闭包












网友评论