Swift学习之枚举的泛性

作者: 冷武橘 | 来源:发表于2022-05-12 16:16 被阅读0次

    一、关联值为泛型类型

     enum Result1<Success, Failure>{
       case success(Success),failure(Failure)
    }
    
    enum Result2<Success>{
    
      case success(Success),  failure(String)
    }
    
    
    enum Result3<Failure>{
    
      case success(Int), failure(Failure) 
    }
    
     let result1 =  Result1<Int,String>.success(1)
     let result2 =  Result2<Int>.success(1) 
     let result3 =  Result3.failure(4)
    

    在以上的例子中,关联值是为Success或Failure类型,而Success或Failure类型是声明的一个泛型类型,所以当你要给枚举的成员变量的关联值存储一个值时,你就需要先去告诉枚举此时真实需要的是什么类型。例如:Result1<Int,String>就告诉,此时Success是Int类型,Failure是String。当然像 let result3 = Result3.failure(4),可以让编译器自动推断处是Int时,就可以省略。

    二、在闭包中的使用

    闭包表达式

     enum Result1<Success, Failure>{
       case success(Success),failure(Failure)
    }
    
        let fn = { (v1:Result1<Int,Int>) -> () in
                switch v1 {
                      case .success(let a):  print(a)
                      case  let .failure(b):  print(b)
                }
            }
                
            let fn1 = { (v1:Result1<Int,String>) -> () in
                switch v1 {
                      case .success(_):  print("测试")
                      case  .failure(_):  print("测试")
                }
            }
           
            let fn2 = { (v1:Result1<String,String>) -> () in
                print("测试")
            }
            fn(Result1<Int,Int>.success(1))
            fn1(Result1<Int,String>.failure("fff"))
            fn2(Result1<String,String>.failure("hhh"))
    

    闭包作为参数类型

     enum Result1<Success, Failure>{
       case success(Success),failure(Failure)
    }
    
    func exec(fn: (Result1<Int,Int>) -> ()) {
            fn(Result1.success(200))
            fn(Result1.failure(12))
        }
        
        func exec1(fn: (Result1<String,Int>) -> ()) {
            fn(Result1.success("成功"))
            fn(Result1.failure(12))
        }
        
        exec{ (result:Result1<Int,Int>) in
                    switch result{
                    case .success(let a) :print(a)
                    case .failure(let b):print(b)
                   }
            }
            
            exec1 { response in
                switch response{
                case .success(let a) :print(a)
                case .failure(let b):print(b)
               }
            }
    

    三、Swift 5之Result类型

    https://www.jianshu.com/p/78ad789577df
    https://www.jianshu.com/p/a3712edc9367

    public enum Result<Success, Failure> where Failure : Error{
        case success(Success)
        case failure(Failure)
    }
    

    很显然Result类型就是枚举的泛性在闭包中使用的最大实践

    相关文章

      网友评论

        本文标题:Swift学习之枚举的泛性

        本文链接:https://www.haomeiwen.com/subject/mrasurtx.html