Swift- Where 常见用法

1,551 阅读1分钟
func test1() {
        
        // 1.是UILabel类型的才进入循环体
        for label in self.view.subviews where label is UILabel {
            print(label)
        }
        
        // 2.第二种实现方式
        for case let label as UILabel in view.subviews {
            print(label)
        }
        
        
        // 3.过滤
        let name = ["name","name2"]
        for nm in name where nm.hasPrefix("name") {
            print(nm)
        }
        
        
    }
    
    func test2() {
        // 1.遍历中包含可选值
        let cles:[String?] = ["name",nil,"name1"]
        for name in cles where name != nil {
            print(name!)
        }
        
        // 2.优化写法
        for case let name? in cles {
            print(name)
        }
    }
    
    // MARK: - nil的用法
    func test3 () {
        let name = returnOptionalName() ?? "name11"
        print(name)
    
    }
    
    func returnOptionalName() -> String? {
        return nil
    }
    
    // MARK: - Swift的类型转换和过滤数组
    func test4() {
        let myCustomViews = self.view.subviews.flatMap {
            $0 as! UILabel
        }
    }
    
    // MARK: - 进制转换
    func test5() {
     let str = String(12, radix: 16) // 十进制转16进制
    }