What does an ampersand (&) mean in the Swift language?

前端 未结 5 445
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 02:29

I know about the ampersand as a bit operation but sometimes I see it in front of variable names. What does putting an & in front of variables do?

5条回答
  •  醉梦人生
    2020-12-01 03:11

    There's another function of the ampersand in the Swift language that hasn't been mentioned yet. Take the following example:

    protocol Foo {}
    protocol Bar {}
    
    func myMethod(myVar: Foo & Bar) {
        // Do something
    }
    

    Here the ampersand syntax is stating that myVar conforms to both the Foo and Bar protocol.

    As another use case, consider the following:

    func myMethod() -> UIViewController & UITableViewDataSource {
        // Do something
    }
    

    Here we're saying that the method returns a class instance (of UIViewController) that conforms to a certain protocol (UITableViewDataSource). This is rendered somewhat obsolete with Swift 5.1's Opaque Types but you may see this syntax in pre-Swift 5.1 code from time to time.

提交回复
热议问题