Swift의 함수 매개 변수로 프로토콜을 준수하는 클래스
Objective-C에서는 프로토콜에 적합한 클래스를 메서드 매개 변수로 지정할 수 있습니다.예를 들어, 다음과 같은 방법만 허용할 수 있습니다.UIViewController에 부합하는UITableViewDataSource:
- (void)foo:(UIViewController<UITableViewDataSource> *)vc;
Swift에서 이 작업을 수행할 방법을 찾을 수 없습니다(아마 아직은 불가능할 것입니다).다음을 사용하여 여러 프로토콜을 지정할 수 있습니다.func foo(obj: protocol<P1, P2>)하지만 물체가 특정 클래스에 속한다고 어떻게 요구합니까?
정의할 수 있습니다.foo일반 함수로 사용하고 형식 제약 조건을 사용하여 클래스와 프로토콜을 모두 요구합니다.
스위프트 4
func foo<T: UIViewController & UITableViewDataSource>(vc: T) {
.....
}
Swift 3 (Swift 4에서도 작동)
func foo<T: UIViewController>(vc:T) where T:UITableViewDataSource {
....
}
스위프트 2
func foo<T: UIViewController where T: UITableViewDataSource>(vc: T) {
// access UIViewController property
let view = vc.view
// call UITableViewDataSource method
let sections = vc.numberOfSectionsInTableView?(tableView)
}
Swift 4에서는 다음과 같은 새로운 & 기호를 사용하여 이를 달성할 수 있습니다.
let vc: UIViewController & UITableViewDataSource
Swift 문서에서는 다음과 같은 where 절과 함께 형식 제약 조건을 사용할 것을 제안합니다.
func someFunction<C1: SomeClass where C1:SomeProtocol>(inParam: C1) {}
이렇게 하면 "inParam"이 "SomeClass" 유형임을 보장하며 "SomeProtocol"도 준수합니다.쉼표로 구분된 여러 where 절을 지정할 수도 있습니다.
func itemsMatch<C1: SomeProtocol, C2: SomeProtocol where C1.ItemType == C2.ItemType, C1.ItemType: SomeOtherProtocol>(foo: C1, bar: C2) -> Bool { return true }
스위프트 5:
func foo(vc: UIViewController & UITableViewDataSource) {
...
}
위에 있는 제롬의 대답입니다.
Swift 3을 사용하면 다음을 수행할 수 있습니다.
func foo(_ dataSource: UITableViewDataSource) {
self.tableView.dataSource = dataSource
}
func foo(_ delegateAndDataSource: UITableViewDelegate & UITableViewDataSource) {
//Whatever
}
이 방법은 어떻습니까?
protocol MyProtocol {
func getTableViewDataSource() -> UITableViewDataSource
func getViewController() -> UIViewController
}
class MyVC : UIViewController, UITableViewDataSource, MyProtocol {
// ...
func getTableViewDataSource() -> UITableViewDataSource {
return self
}
func getViewController() -> UIViewController {
return self
}
}
func foo(_ vc:MyProtocol) {
vc.getTableViewDataSource() // working with UITableViewDataSource stuff
vc.getViewController() // working with UIViewController stuff
}
Swift 5에 대한 업데이트:
func yourFun<V: YourClass>(controller: V) where V: YourProtocol
2015년 9월 참고:이것은 스위프트 초기의 관찰이었습니다.
그것은 불가능해 보입니다.Apple은 일부 API에서도 이러한 문제를 안고 있습니다.다음은 iOS 8(베타 5 기준)에 새로 도입된 클래스의 한 예입니다.
UIInputViewController의textDocumentProxy속성:
목표-C에서 다음과 같이 정의됩니다.
@property(nonatomic, readonly) NSObject<UITextDocumentProxy> *textDocumentProxy;
스위프트에서:
var textDocumentProxy: NSObject! { get }
Apple 문서 링크: https://developer.apple.com/library/prerelease/iOS/documentation/UIKit/Reference/UIInputViewController_Class/index.html #//apple_ref/occ/instp/UIInputViewController/textDocumentProxy
언급URL : https://stackoverflow.com/questions/24051396/class-conforming-to-protocol-as-function-parameter-in-swift
'programing' 카테고리의 다른 글
| Visual Studio Code를 사용한 Mocha 중단점 (0) | 2023.09.01 |
|---|---|
| XML에서 RecyclerView 앱:layoutManager="를 설정하는 방법은 무엇입니까? (0) | 2023.09.01 |
| 별칭 접두사를 사용하여 쿼리의 모든 열 (0) | 2023.09.01 |
| HTML5 자리 표시자 CSS 패딩 (0) | 2023.09.01 |
| MySQL: 트리거 시 오류 1064(42000) (0) | 2023.09.01 |