iOS
[Swift] Extension
Peppo
2021. 11. 9. 09:10
728x90
Extension?
스위프트의 강력한 기능 중 하나로.
기존 클래스, 구조체, 열거형 타입에 새로운 프로퍼티, 메서드, 이니셜라이저 등을 추가하여, 소스 코드에 접근하지 못하는 타입들도 확장해서 사용할 수 있다.
사용시 extension 이란 키워드를 사용하여 확장한다.
선언
extension 확장할 타입 이름 (e.g. Int) {
// 타입에 추가될 새로운 기능 구현
}
// 또는
extension 확장할 타입 이름: 프로토콜1, 프로토콜2 {
// 프로토콜 요구사항 구현
}
⭐️ 확장에 프로토콜 추가
아래와 같은 예시를 보면
struct Language {
let name: String
}
let sweetft: Language = .init(name: "sweetft")
let swift = sweetft
swift == sweetft // error Binary operator '==' cannot be applied
'==' 비교연산자를 사용하기 위해선 Equatable이라는 프로토콜을 채택해야 합니다.
struct Language: Equatable {
let sweetft: String
public static func == (lhs: Language, rhs: Language) -> Bool {
return lhs.sweetft == rhs.sweetft
}
}
이렇게 원본에다가 프로토콜을 채택해도 되지만
보통 프로토콜을 추가할때에는
원본은 원본에 관련된 함수들만 두고
extension을 이용하여
해당 프로토콜에 맞는 메서드만 구현하는것이 유지보수나 가독성면에서 좋습니다.
struct Language {
let sweetft: String
}
extension Language: Equatable {
public static func == (lhs: Language, rhs: Language) -> Bool {
return lhs.sweetft == rhs.sweetft
}
}
예제 하나 더 ,
class ViewController: UIViewController, UITableViewDataSource, UICollectionViewDataSource {
override func viewDidLoad() {
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
}
}
ViewController(원본)에 프로토콜이 여러개 달리면 코드가 지저분 하니까 어떻게 한다??
class ViewController: UIViewController {
override func viewDidLoad() {
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
}
}
extension을 사용해서 가독성 좋게 !!!
참고 : https://jusung.gitbook.io/the-swift-language-guide/language-guide/20-extensions
728x90