Error: Redundant conformance of 'ViewController' to protocol with extension

前端 未结 2 554
野的像风
野的像风 2020-12-22 02:05

When I try this I get error:

class ViewController: UIViewController, UIScrollViewDelegate {
    ......
    }

extension ViewController: UIScrollViewDelegate          


        
相关标签:
2条回答
  • 2020-12-22 02:13

    The error is self-explaining. You don't have to conform to a protocol multiple times. You can either do 1)

    class ViewController: UIViewController, UIScrollViewDelegate {
        ......
        }
    

    or

    2)

    class ViewController: UIViewController {
                ......
                }
    
    
    extension ViewController: UIScrollViewDelegate { // No error
                ...
            }
    

    In case 1, you don't need an extension because the class itself adopts the protocol. The purpose of the extension is to add more functionality to the class. In case 2, it is clear that the extension adopts to the protocol.

    0 讨论(0)
  • 2020-12-22 02:23

    In the first code sample, you've already added conformance to UIScrollViewDelegate with the class declaration.

    Now, when you try to conform to UIScrollViewDelegate again with the extension, swift screams at you.

    For the second code sample the conformance is added in the extension. The class did not conform to UIScrollViewDelegate before the extension was added.

    0 讨论(0)
提交回复
热议问题