最近把项目优化了一遍,用了一些语法糖,语法糖可以提高编程序效率,别人阅读代码的时候会觉得你的代码很工整,有逼格,也方便维护。下面展示一些最近的优化示例。
var nickName: String?
var userHederSrc: String?
//使用时
func setUserInfo(){
if let nickName = nickName {
if let userHederSrc = userHederSrc {
print("nickName:\(nickName),userHederSrc:\(userHederSrc)")
}
}
}
宛如金字塔的层层嵌套,如果参数过多,简直无法想象。
var nickName: String?
var userHederSrc: String?
//使用时
func setUserInfo(){
guard let nickName = nickName, let userHederSrc = userHederSrc
else { return }
print("nickName:\(nickName),userHederSrc:\(userHederSrc)")
}
去除数组中的重复的元素
func removeStrSameElement(_ originArr: [String]) -> [String] {
return originArr.reduce([String]()) { $0.contains($1) ? $0 : $0 + [$1] }
}
func removeIntSameElement(_ originArr: [Int]) -> [Int] {
return originArr.reduce([Int]()) { $0.contains($1) ? $0 : $0 + [$1] }
}
// 打印结果:["a", "b", "d", "e", "c"]
print(removeStrSameElement(["a", "b", "a", "d", "e", "d", "b", "c"]))
// 打印结果:[1, 2, 3, 4, 5]
print(removeIntSameElement([1, 2, 3, 4, 2, 3, 5, 4]))
一种类型写一种,太累。
func removeSameElement<T: Equatable>(_ originArr: [T]) -> [T] {
return originArr.reduce([T]()) { $0.contains($1) ? $0 : $0 + [$1] }
}
// 打印结果:["a", "b", "d", "e", "c"]
print(removeSameElement(["a", "b", "a", "d", "e", "d", "b", "c"]))
// 打印结果:[1, 2, 3, 4, 5]
print(removeSameElement([1, 2, 3, 4, 2, 3, 5, 4]))
如果一个控制器里的Button特别的多,那添加Button点击事件的Selector 会觉得特别的臃肿。
class example{
lazy var button: UIButton = {
let button = UIButton()
button.addTarget(self, action:#selector(funcAClick), for: .touchUpInside)
return button
}()
@objc func funcAClick(){
print("exampleA:funcA")
}
...
}
优化方法:扩展Selector,整洁,点语法用起来更方便
class exampleBase{
lazy var button: UIButton = {
let button = UIButton()
button.addTarget(self, action: .funcAClick, for: .touchUpInside)
return button
}()
@objc func funcAClick(){
print("exampleA:funcA")
}
}
private extension Selector {
static let funcAClick = #selector(exampleBase.funcAClick)
...
}
遍历多种类型数组
var stringArray = ["A", "B", "C"]
var intArray = [1, 3, 4, 5, 6]
var doubleArray = [1.0, 2.0, 3.0]
func printStrArr(a: [String]) { for s in a { print(s) } }
func prIntArr(a: [Int]) { for i in a { print(i) } }
func printDoubleArr(a: [Double]) {for d in a { print(d) } }
printStrArr(a:stringArray)
prIntArr(a:intArray)
printDoubleArr(a:doubleArray)
短小精悍
var stringArray = ["A", "B", "C"]
var intArray = [1, 3, 4, 5, 6]
var doubleArray = [1.0, 2.0, 3.0]
extension Array{
func printArray() { for s in self { print(s) } }
}
stringArray.printArray()
intArray.printArray()
doubleArray.printArray()
遍历寻找符合条件的元素
let array = [1,2,3,4,5]
let dic = [1:"heihei1",2:"heihei1"]
for i in array{
for j in dic.keys{
if j == i && dic[j] != nil {
print(i)
}
}
}
let array = [1,2,3,4,5]
let dic = [1:"heihei1",2:"heihei2"]
for i in array where dic[i] != nil {
print(i)
}
多用枚举替换字符串,字符串容易敲错
switch season {
case "spring": print("spring: do something")
case "summer": print("summer: do something")
case "autumn": print("autumn: do something")
case "winter": print("winter: do something")
default: print("Fuck")
}
enum Season { case spring, summer, autumn,winter }
var season = Season.spring
switch season {
case .spring: print("spring: do something")
case .summer: print("summer: do something")
case .autumn: print("autumn: do something")
case .winter: print("winter: do something")
}
var userHeaderSrc: String?
var defaultSrc = "http://baidu.com"
var userUseSrc = ""
if let userSrc = userHeaderSrc { userUseSrc = userSrc } else
{ userUseSrc = defaultSrc }
var userHeaderSrc: String?
var defaultSrc = "http://baidu.com"
var colorToUse = userChosenColor ?? defaultColor
筛选出能被2整除的值
var newEvens = [Int]()
for i in 1...10 {
if i % 2 == 0 { newEvens.append(i) }
}
print(newEvens) // [2, 4, 6, 8, 10]
过滤器(filter)可以更简单的实现,也使代码更整洁
var evens = Array(1...10).filter { $0 % 2 == 0 }
print(evens) // [2, 4, 6, 8, 10]
常规解法
func minMax(arr:[Int])->(Int,Int) {
var min:Int = arr[0]
var max:Int = arr[0]
for i in 0..<arr.count {
if arr[i] < min {
min = arr[i]
}
if arr[i] > max {
max = arr[i]
}
}
return (min,max)
}
var findArr:[Int] = [100,5,6,8,3,7,9,10,0,40,1,2]
minMax(arr:findArr)
过滤器(filter)可以更简单的实现,也使代码更整洁
var findArr:[Int] = [100,5,6,8,3,7,9,10,0,40,1,2]
findArr.min()
findArr.max()
func sum(x: Int, y: Int) -> Int { return x + y }
var result = sum(x: 1, y: 1) // 2
不需要记住有关的名字和变量,只要一个$符号
var sumBlock: (Int, Int) -> (Int) = { $0 + $1 }
sumBlock(1, 1) // 2