美文网首页
swift 4.0 泛型

swift 4.0 泛型

作者: 透支未来 | 来源:发表于2018-01-29 09:06 被阅读183次

    泛型

    
    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
           pringElemtFormArr(a: stringArr)
            pringElemtFormArr(a: intArr)
            pringElemtFormArr(a: doubleArr)
            
            
            donoting(x: 123)
            donoting(x: "123")
            donoting(x: true)
            
            
        }
    
        var stringArr = ["hi","hello","bye"]
        var intArr = [1,2,3]
        var doubleArr = [1.1,2.2,3.3]
    
        //普通方法
        func printAreingArr(a:[String]) {
            for s in a {
                print(s)
            }
        }
    
        func pringIntArr(a:[Int]) {
            for i in a {
                print(i)
            }
        }
        
        
        //泛型的方法 T代表任意类型
        func pringElemtFormArr<T>(a:[T]) {
            for element in a {
                print(element)
            }
        }
        func donoting<T>(x:T) -> T {
            return x
        }
    }
    

    Swift中mutating关键字

    Swift中protocol的功能比OC中强大很多,不仅能再class中实现,同时也适用于struct、enum。
    使用 mutating 关键字修饰方法是为了能在该方法中修改 struct 或是 enum 的变量,在设计接口的时候,也要考虑到使用者程序的扩展性。所以要多考虑使用mutating来修饰方法。

    
    import UIKit
    
    struct GenericArr<T> {
        var items = [T]()  //创建数组
        
        mutating func push(item:T) {
            items.append(item)
        }
    }
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
           var myPhone = ["ipone5","iphone6","iphone7"]
            var LisaArr = GenericArr(items: myPhone)
            LisaArr.push(item: "iphon7 plus")
            print( LisaArr.items)
        }
    
    }
    
    
    

    相关文章

      网友评论

          本文标题:swift 4.0 泛型

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