浅谈swift 开发技巧

参考链接

1、extension UIView

extension UIView {
    func addSubviews(_ subviews: UIView...) {
        subviews.forEach(addSubview)
    }
}
    lazy var view1: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 200))
        view.backgroundColor = .red
        return view
    }()
    lazy var view2: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 300, width: 100, height: 200))
        view.backgroundColor = .green
        return view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubviews(view1,view2)
    }

forEach与forin的区别

       let array = ["one", "two", "three", "four"]
        array.forEach { (element) in
            if element == "two" {
                return
            }
            print("foreach:" + element)
        }

result:

foreach:one
foreach:three
foreach:four

        let array = ["one", "two", "three", "four"]
        for element in array {
            if element == "two" {
                return
            }
            print("forin:" + element)
        }

result:

forin:one

在ForIn 循环中使用return的话,会立即跳出当前的循环体。然而在forEach中,还会继续遍历剩余元素。

2、extension UILabel

extension UILabel {
    static func initForTitle() -> UILabel {
        let label = UILabel()
        label.font = .boldSystemFont(ofSize: 27)
        label.textColor = .darkGray
        label.numberOfLines = 1
        //根据label的宽度自动更改文字的大小
        label.adjustsFontSizeToFitWidth = true
        label.minimumScaleFactor = 0.2
        //文本基线的行为
//        label.baselineAdjustment = .alignBaselines
        label.textAlignment = .center
        label.backgroundColor = .red
        return label
    }
}
    func test() {
        let label = UILabel.initForTitle()
        label.frame = CGRect(x: 0, y: 600, width: 400, height: 80)
        label.text = "中华人民共和国"
        view.addSubview(label)
    }

3、extension UIColor

extension UIColor {
    // UIColor(r: 95, g: 199, b: 220)
    convenience init(r: Int, g: Int, b: Int) {
        self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: 1.0)
    }
    // UIColor(hex: 0x5fc7dc)
    convenience init(hex:Int) {
        self.init(r:(hex >> 16) & 0xff, g:(hex >> 8) & 0xff, b:hex & 0xff)
    }
}
label.textColor = UIColor(hex: 0x5fc7dc)

4、滑动关闭键盘

// Dismiss your keyboard when you are
// scrolling your tableView down interactively.
tableView.keyboardDismissMode = .interactive

5、自动填充

// To enable security code autofill on a UITextField we need to set the textContentType property to .oneTimeCode.
otpTextField.textContentType = .oneTimeCode

6、数组筛选

        let array = [1, 4, 6, 7, 8]
        let sort = array.filter {$0 % 2 == 0}
        print(sort)//[4, 6, 8]
        let array2 = ["a", "12", "csd", "4567", "88888"]
        let sort2 = array2.filter {$0.count > 3}
        print(sort2)//["4567", "88888"]

7、guard 校验

/*
  What makes the “guard” statement truly stand out,
  however, is that unwrapped optional values remain
  available in the rest of the code block.
*/

private func fetchContents() {
    webService.fetchCategories { [weak self] (response) in
        // Optional Binding for self
        guard let self = self else { return }
        self.createloadMoreRequest(content: response)               
    }
}

private func createloadMoreRequest(content: Content?) {
    // Optional Binding for content
    guard let content = content else { return }
    let categoryId = content.categoryId
    self.loadMore(id: categoryId)
}

8.array的操作

// Use .first(where: (Int) throws -> Bool)
// to retrieve first elemen in an array which contains
// the same conditional objects.
let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
if let firstNegative = numbers.first(where: { $0 < 0 }) {
    print("The first negative number is \(firstNegative).")
}
// Prints "The first negative number is -2."

9.array判断条件

        // The following code uses this method to test whether all
        // the names in an array have at least five characters:
        let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
        let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 })
        // allHaveAtLeastFive == true
        //是否都小于10
        let digits = 0...9
        let areAllSmallerThanTen = digits.allSatisfy { $0 < 10 }
        print(allHaveAtLeastFive,areAllSmallerThanTen)

10.defer延迟执行

    override func viewDidLoad() {
        super.viewDidLoad()
        print("start")
        test()
        print("end")
    }
    func test() {
        defer { print("End of the function") }
        print("Main body of the simleDefer function")
    }
    
    
//start
//Main body of the simleDefer function
//End of the function
//end

11.inout的使用

    func test() {
        var n1 = 10, n2 = 20
        swapNumber(num1: &n1, num2: &n2)
        print(n1,n2)
    }
    func swapNumber( num1: inout Int, num2: inout Int) {
        let temp = num1
        num1 = num2
        num2 = temp
    }

12.准换大小写

        let cast = ["Name", "NAME", "namE"]
        let lowerCast = cast.map { $0.lowercased() }
        print(lowerCast)//["name", "name", "name"]
        let count = cast.map { $0.count }
        print(count)//[4, 4, 4]

13.筛选

        let array = ["1", "3", "three", "4///", "5", "let"]
        let numberArray: [Int?] = array.map { Int($0) }
        let number2Array:[Int] = array.compactMap { Int($0) }
        print(numberArray)//[Optional(1), Optional(3), nil, nil, Optional(5), nil]
        print(number2Array)//[1, 3, 5]

14.排序

        let array = [11, 3,  25, 17]
        let sorted = array.sorted(by: >)
        print(sorted)//[25, 17, 11, 3]

15.自定义运算符

  • inflx 中
infix operator ∈
func ∈ <T: Equatable>(lhs: T, rhs: [T]) -> Bool {
    return rhs.contains(lhs)
}


        let month = "September"
        if month ∈ ["April", "June", "September", "November"] {
            print("\(month) has 30 days.")
        }
        //September has 30 days.
  • prefix
// 前置:返回2的n次方
prefix operator  ^

prefix func ^ (vector: Double) -> Double {
    return pow(2, vector)
}

print(^5)  // 32.0
  • postfix
postfix operator ^
postfix func ^ (vector: Int) -> Int {
    return vector * vector
}


 print(5^)  // 25

16.获取枚举中有多少个case(swift4.2新特性)

    enum CompassDirection: CaseIterable {
        case east, west, south, north
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        print("there are \(CompassDirection.allCases.count) directions")
        for direction in CompassDirection.allCases {
            print("i want to go \(direction)")
        }
    }
there are 4 directions
i want to go east
i want to go west
i want to go south
i want to go north

17.对数组进行乱序操作

        var array = ["name", 1, true, "age", 6, "liuxingxing"] as [Any]
        let shuffledArray = array.shuffled()
        print(shuffledArray)
        array.shuffle()
        print(array)
[6, "age", "name", true, 1, "liuxingxing"]
[6, "liuxingxing", true, "name", "age", 1]

18.计算属性

class Person {
    var name: String?
    var surname: String?
    var fullname: String? {
        guard let name = name, let surname = surname else {
            return nil
        }
        return "\(name)\(surname)"
    }
}



        let person = Person()
        person.name = "xingxing"
        person.surname = "liu"
        print(person.fullname)

19.静态属性

    struct Constant {
        static let baseUrl = "https://xxxxxxx"
        static let backgroundColor = UIColor.red
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let myUrl = URL(string: Constant.baseUrl)
        view.backgroundColor = Constant.backgroundColor
    }

20.类方法与静态方法(类方法子类可以重写,静态方法没法重写)

error: Cannot override static method

class Service {
    class func fetchData() {
        print("this is Service")
    }
    static func sendData() {
        print("this is static method")
    }
}
class MovieService: Service {
    override class func fetchData() {
        print("this is movieService")
    }
    //error: Cannot override static method
//    override static func sendData() {
//        print("this is movieService")
//    }
}

21.懒加载

class DataImporter {
    //假使这个类需要初始化需要很长时间
    var filename = "data.text"
}
class DataManager {
    lazy var importer = DataImporter()
    var data = [String]()
}



    override func viewDidLoad() {
        super.viewDidLoad()
        let manager = DataManager()
        manager.data.append("a data")
        manager.data.append("more data")
        //此时DataImporter的实例还没有被初始化
    }

22.当函数有返回值时,却没有接收这个返回值,会发生警告Result of call to 'add()' is unused,可以通过@discardableResult来抑制该警告

    var number = 10
    override func viewDidLoad() {
        super.viewDidLoad()
        //Result of call to 'add()' is unused
       add()
       print(number)
    }
    @discardableResult
    func add() -> Int {
        number += 1
        return number
    }

23.使用元组作为返回值

    override func viewDidLoad() {
        super.viewDidLoad()
        let statistics = calculate(scores: [1, 2, 3, 4, 5])
        print(statistics.max)//5
        print(statistics.min)//1
        print(statistics.sum)//15
        print(statistics.2)//15
    }
    func calculate(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
        guard let min = scores.min(), let max = scores.max() else {
            fatalError("scores is nil")
        }
        //map,reduce,filter
        
        //public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
        //0 是为 initialResultw赋值的,为初始化值
        let sum = scores.reduce(0){ $0 + $1 }//如果将0更改为5,那么sum将由15更改为20
        
//        let numberSum = numbers.reduce(0, { x, y in
//            x + y
//        })
        return (min, max, sum)
    }

24.属性观察者

    struct MyClass {
        var name: String {
            willSet {
                print("value is \(name)")
                print("value will be \(newValue)")
            }
            didSet {
                print("value is \(name)")
                print("value was \(oldValue)")
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        var test = MyClass(name: "LXX")//此时并未调用willset和didSet,数据"再次赋值"的时候才会调用,即使和原来的值一样也会再次调用
        test.name = "DLL"
    }

value is LXX
value will be DLL
value is DLL
value was LXX

25.属性只读public private(set)

    struct MyClass {
        public private(set) var name: String
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        var test = MyClass(name: "LXX")
        print(test.name)
        //编译错误:Cannot assign to property: 'name' setter is inaccessible
        //test.name = "DLL"
    }

26.数组拼接成字符串,字符串拆分成数组

    override func viewDidLoad() {
        super.viewDidLoad()
        let names = ["DLL", "LXX", "LMY"]
        let nameString = names.joined()
        print(nameString)//默认拼接
        let nameString2 = names.joined(separator: "-")
        print(nameString2)//以"-"拼接
        let array = nameString2.split(separator: "-")
        print(array)//以"-"拆分成c数组
    }
    
    
DLLLXXLMY
DLL-LXX-LMY
["DLL", "LXX", "LMY"]

27.switch的"穿透"效果

    override func viewDidLoad() {
        super.viewDidLoad()
        let integerToDescribe = 5
        var description = "The number \(integerToDescribe) is"
        switch integerToDescribe {
        case 2, 3, 5, 7, 11, 13, 17, 19:
            description += " a prime number, and also"
            fallthrough
        default:
            description += " an integer."
        }
        print(description)
    }
    
    
    The number 5 is a prime number, and also an integer.

28.泛型函数

    override func viewDidLoad() {
        super.viewDidLoad()
        var num1 = 3
        var num2 = 9
        swapTwoValues(&num1, &num2)
        print(num1)
        print(num2)
    }
    func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
        let temp = a
        a = b
        b = temp
    }

29.快速交换

    override func viewDidLoad() {
        super.viewDidLoad()
        var num1 = "abc"
        var num2 = "efg"
        var num3 = "hij"
        print(num1)
        print(num2)
        print(num3)
        (num1, num2, num3) = (num2, num3, num1)
        print(num1)
        print(num2)
        print(num3)
    }
    
    
abc
efg
hij


efg
hij
abc

30.Builder Pattern

protocol Builder {}

extension Builder {
    public func with(configure: (inout Self) -> Void) -> Self {
        var this = self
        configure(&this)
        return this
    }
}
//让NSObject遵守该协议
extension NSObject: Builder {}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//    let tab = UITableView().with(configure: <#T##(inout UITableView) -> Void#>)
    private let baseTableView = UITableView(frame: CGRect(x: 0, y: 0, width: 100, height: 200), style: .plain).with { (tableView) in
        tableView.backgroundColor = .red
        tableView.separatorColor = .darkGray
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 10.0, right: 0)
        tableView.allowsMultipleSelection = true
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.frame = CGRect(x: 100, y: 200, width: 300, height: 300)//此时这里的位置是有效的
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(baseTableView)
        baseTableView.delegate = self
        baseTableView.dataSource = self
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "99999"
        return cell
    }
}
image.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,820评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,648评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,324评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,714评论 1 297
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,724评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,328评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,897评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,804评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,345评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,431评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,561评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,238评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,928评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,417评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,528评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,983评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,573评论 2 359

推荐阅读更多精彩内容

  • 参考资源《swifter》https://github.com/iOS-Swift-Developers/Swif...
    柯浩然阅读 1,450评论 0 6
  • 这是16年5月份编辑的一份比较杂乱适合自己观看的学习记录文档,今天18年5月份再次想写文章,发现简书还为我保存起的...
    Jenaral阅读 2,767评论 2 9
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,111评论 1 32
  • 简友们,Hello!我们是柴宝庄园主。欢迎来到柴宝庄园,接下来,您将参观柴宝庄园!既清爽又可爱的庄园。准备好了吗?...
    许宸瑞阅读 390评论 0 1
  • 6:55我就起来了 不知昨晚几点睡得 不过很早 昨晚做了两个梦 睡得也不好 或许是我太想家了 想念家里的感觉 这个...
    waterlily77阅读 91评论 0 0