How to make a class conform to a protocol in Swift?

前端 未结 3 1555
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 03:29

in Objective-C:

@interface CustomDataSource : NSObject 

@end

in Swift:

class CustomDataSource         


        
3条回答
  •  -上瘾入骨i
    2020-12-08 04:13

    A class has to inherit from a parent class before conform to protocol. There are mainly two ways of doing it.

    One way is to have your class inherit from NSObject and conform to the UITableViewDataSource together. Now if you want to modify the functions in the protocol, you need to add keyword override before the function call, like this

    class CustomDataSource : NSObject, UITableViewDataSource {
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
    
            // Configure the cell...
    
            return cell
        }
    }
    

    However this sometimes gets your code messy because you may have many protocols to conform to and each protocol may have several delegate functions. In this situation, you can separate the protocol conforming code out from the main class by using extension, and you do not need to add override keyword in the extension. So the equivalent of the code above will be

    class CustomDataSource : NSObject{
        // Configure the object...
    }
    
    extension CustomDataSource: UITableViewDataSource {
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
    
            // Configure the cell...
    
            return cell
        }
    }
    

提交回复
热议问题