Swift에서 “순수한 가상 기능”을 만드는 표준 방법이 있습니까? 일 해야한다 , 그렇지 않은 경우, 컴파일 시간 오류가 발생합니다 모든 서브 클래스를 오버라이드 (override) 할, 그리고?
답변
두 가지 옵션이 있습니다.
1. 프로토콜 사용
수퍼 클래스를 클래스 대신 프로토콜로 정의
장점 : 각 “하위 클래스”(실제 하위 클래스가 아님)가 필요한 메서드를 구현하는지 컴파일 시간 확인
단점 : “수퍼 클래스”(프로토콜)는 메서드 나 속성을 구현할 수 없습니다.
2. 메서드의 슈퍼 버전에서 어설 션
예:
class SuperClass {
func someFunc() {
fatalError("Must Override")
}
}
class Subclass : SuperClass {
override func someFunc() {
}
}
장점 : 수퍼 클래스에서 메서드 및 속성 구현 가능
단점 : 컴파일 시간 확인 없음
답변
다음은 클래스에서 상속하고 프로토콜의 컴파일 시간 검사를 허용합니다. 🙂
protocol ViewControllerProtocol {
func setupViews()
func setupConstraints()
}
typealias ViewController = ViewControllerClass & ViewControllerProtocol
class ViewControllerClass : UIViewController {
override func viewDidLoad() {
self.setup()
}
func setup() {
guard let controller = self as? ViewController else {
return
}
controller.setupViews()
controller.setupConstraints()
}
//.... and implement methods related to UIViewController at will
}
class SubClass : ViewController {
//-- in case these aren't here... an error will be presented
func setupViews() { ... }
func setupConstraints() { ... }
}
답변
추상 클래스 / 가상 함수에 대한 지원은 없지만 대부분의 경우 프로토콜을 사용할 수 있습니다.
protocol SomeProtocol {
func someMethod()
}
class SomeClass: SomeProtocol {
func someMethod() {}
}
SomeClass가 someMethod를 구현하지 않으면 다음 컴파일 시간 오류가 발생합니다.
error: type 'SomeClass' does not conform to protocol 'SomeProtocol'
답변
“가상”메서드가 너무 많지 않은 경우 다른 해결 방법은 하위 클래스가 “구현”을 기본 클래스 생성자에 함수 개체로 전달하도록하는 것입니다.
class MyVirtual {
// 'Implementation' provided by subclass
let fooImpl: (() -> String)
// Delegates to 'implementation' provided by subclass
func foo() -> String {
return fooImpl()
}
init(fooImpl: (() -> String)) {
self.fooImpl = fooImpl
}
}
class MyImpl: MyVirtual {
// 'Implementation' for super.foo()
func myFoo() -> String {
return "I am foo"
}
init() {
// pass the 'implementation' to the superclass
super.init(myFoo)
}
}
답변
대답에 제안 당신은 주장 대 프로토콜을 사용할 수 있습니다 여기 에서 drewag
. 그러나 프로토콜에 대한 예가 없습니다. 여기에서 다루고 있습니다.
실험 계획안
protocol SomeProtocol {
func someMethod()
}
class SomeClass: SomeProtocol {
func someMethod() {}
}
이제 컴파일 타임에 확인되는 프로토콜을 구현하기 위해 모든 하위 클래스가 필요합니다. SomeClass가 someMethod를 구현하지 않으면 다음 컴파일 시간 오류가 발생합니다.
오류 : ‘SomeClass’유형이 ‘SomeProtocol’프로토콜을 따르지 않습니다.
참고 : 이것은 프로토콜을 구현하는 최상위 클래스에서만 작동합니다. 모든 하위 클래스는 프로토콜 요구 사항을 가볍게 무시할 수 있습니다. – 댓글 로memmons
역설
class SuperClass {
func someFunc() {
fatalError("Must Override")
}
}
class Subclass : SuperClass {
override func someFunc() {
}
}
그러나 어설 션은 런타임에서만 작동합니다.
답변
iOS 개발을 처음 접했기 때문에 이것이 언제 구현되었는지 확실하지 않지만 두 세계를 최대한 활용하는 한 가지 방법은 프로토콜 확장을 구현하는 것입니다.
protocol ThingsToDo {
func doThingOne()
}
extension ThingsToDo {
func doThingTwo() { /* Define code here */}
}
class Person: ThingsToDo {
func doThingOne() {
// Already defined in extension
doThingTwo()
// Rest of code
}
}
확장은 함수에 대한 기본값을 가질 수있게 해주는 반면 정규 프로토콜의 함수는 정의되지 않은 경우에도 컴파일 시간 오류를 제공합니다.