Codable
s 에서 작동하는 방법이 있으며 무엇보다도 다음을 수행합니다.
func doWhatever<T>() -> T? where T: Codable {
var myName = String(describing: T.self)
return nil // or whatever
}
그런 다음 myName
런타임에 클래스 이름을 가져와 T
.
이제 이것에 Codable
대한 custom
이름 을 제공해야합니다 .
그래서 내가 some protocol
제공하는 이름 을 따르기 위해 내 모든 코드 (수백 개의 모델)를 편집 할 수 있지만 , 나는 정말로 그것을 피하고 싶다.
Swift에는 사용자 정의 속성이 없기 때문에 이것을 조합했습니다.
protocol MetadataProvidingCodable {
static func customName() -> String
}
그런 다음 내 일반에서 다음을 T
준수 하는지 확인할 수 있습니다 .
func doWhatever<T>() -> T? where T: Codable {
var myName = String(describing: T.self)
if T.self is MetadataProvidingCodable.Type {
myName = ... // Get customName() from T without an instance???
}
return nil // or whatever
}
하지만 내 문제는 T
인스턴스가 없어도 유형 에 대해 정적 func를 호출 할 수 있어야한다는 것 입니다 T
. 가능합니까?
다음 T.self
과 MetadataProvidingCodable.Type
같이 캐스트를 입력 할 수 있습니다 .
func doWhatever<T>() -> T? where T: Codable {
var myName = String(describing: T.self)
if let type = T.self as? MetadataProvidingCodable.Type {
myName = type.customName()
}
return nil // or whatever
}
편집 : 어떻게 든 공통 논리를 별도의 함수로 옮길 수 있다면 및 doWhatever()
모두를 준수하는 유형을 반환하는 다른 함수로 함수를 재정의 할 수 있습니다 .Codable
MetadataProvidingCodable
그런 다음 컴파일러는 반환 유형에 따라 어떤 함수가 호출되는지 알아냅니다.
func doWhatever<T>() -> T? where T: Codable {
print("doWhatever: Codable")
var myName = String(describing: T.self)
return nil
}
func doWhatever<T>() -> T? where T: Codable & MetadataProvidingCodable {
print("doWhatever: Codable & MetadataProvidingCodable")
var myName = T.customName()
return nil
}
struct Example1: Codable {}
struct Example2: Codable, MetadataProvidingCodable {
static func customName() -> String {
return "Example2"
}
}
let example1: Example1? = doWhatever()
let example2: Example2? = doWhatever()
// prints
// doWhatever: Codable
// doWhatever: Codable & MetadataProvidingCodable
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다