* 1>生成String类型的hh,如果为nil,则返回""
postfix operator ~~
postfix func ~~(
v: String?
) -> String {
return v == nil ? "" : v!
}
var foo : String?
var hh = foo~~
*2> sequence基础 1
for i in sequence(first: 1, next: { $0 * 2}){
// $0 代表 first 然后 在将 $0返回给first
if i > 100 {
break
}
print(i) // 1 2 4 8 16 32 64
}
//另一种写法
for _ in sequence(first: 1, next: {
//返回nil就是结束
print($0)
let number = $0 * 2
return number <= 100 ? $0 * 2 : nil
}){}
- sequence基础 2
let fibonacci = sequence(state: (0,1)) {(state: inout (Int, Int)) -> Int? in
defer {state = (state.1, state.0 + state.1)}
return state.0
}
//只取10 个数
for number in fibonacci.prefix(10){
print(number)
}
- sequence基础 3 返回(0,0)~(5,2)的所有组合
for i in cartesianSequence(xCount: 5, yCount: 2){
print("x : \(i.x) y : \(i.y)")
}
func cartesianSequence(xCount : Int , yCount : Int) -> UnfoldSequence<SeqPointType , Int> {
assert(xCount > 0 && yCount > 0 , "必须是整数")
return sequence(state: 0, next: {
(index : inout Int) -> SeqPointType? in
guard index < xCount * yCount else {return nil}
defer {index += 1}
print(index)
return (x: index % xCount, y : index / xCount)
})
}
3. <a href = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd=NS_REQUIRES_NIL_TERMINATION&rsv_pq=bde9f19c0000d37b&rsv_t=412deZWuo0iQXSD1Mczsoqd1eS%2B6uPz%2F09L4BL95LtUNUDeRUQE4UKElEAs&rqlang=cn&rsv_enter=1&rsv_sug3=1">NS_REQUIRES_NIL_TERMINATION</a>
4. <a href ="">NSAssert</a>
5.关键字 <a href = "#">@autoclosure </a>
func add(l : Bool, _ r : @autoclosure ()->Bool) -> Bool {
guard l else {
return false
}
return r()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if add(l: true, true ) {
print("进行操作")
}
}
6. swift 锁
func synchronized(lock: AnyObject, closure: () -> ()) {
objc_sync_enter(lock)
closure()
objc_sync_exit(lock)
}
7.Stride函数
let numbers = [1,2,3,4,5,6]
let damp = stride(from: 0, through: numbers.count, by: 2)
for item in damp {
print(item) // 0 2 4
}
8. 数学
<code>let num = exp(1.0)</code> e的1次方
9. split 根据字符串拆分 , <code>maxSplits</code> : 拆分次数
let lipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
let words = lipsum.characters.split(separator: " ").map(String.init)
let words2 = lipsum.characters.split(separator: " ", maxSplits: 1, omittingEmptySubsequences: true).map(String.init)
10. lazy
let counts = words.lazy.map({ $0 })
for i in counts {
print(i)
}
11.sorted : 排序
let dict = ["k1":3,"k2":2]
let keys = Array(dict.keys)
let sortedKeys = keys.sorted(by: {
let v1 = dict[$0]
let v2 = dict[$1]
return v1! < v2!
})
print(sortedKeys) // k2 k1