2
的情況:變通方法爲特定的泛型類型參數
我有兩個方案,一個用靜態方法:
protocol DataSourceable {
static func getMoreData<T: DataAccepting>(someObject: T)
}
protocol DataAccepting {
func accept(data: [Any])
}
extension DataAccepting where Self: UIViewController { }
它編譯罰款。
一旦我定義一個類與符合DataSourceable
類型參數:
class SampleViewController<T: DataSourceable>: UIViewController {...}
我得到一個Segmentation Fault: 11
和編譯器崩潰。
0 swift 0x0000000112445b6d PrintStackTraceSignalHandler(void*) + 45
1 swift 0x00000001124455b6 SignalHandler(int) + 470
2 libsystem_platform.dylib 0x00007fffa4bd9bba _sigtramp + 26
3 libsystem_platform.dylib 0x0000000000000002 _sigtramp + 1531077730
4 swift 0x000000010f8bd5bd swift::irgen::emitCategoryData(swift::irgen::IRGenModule&, swift::ExtensionDecl*) + 2285
5 swift 0x000000010f8c2425 swift::irgen::IRGenModule::emitGlobalDecl(swift::Decl*) + 1189
6 swift 0x000000010f8c1e85 swift::irgen::IRGenModule::emitSourceFile(swift::SourceFile&, unsigned int) + 133
7 swift 0x000000010f98dfe2 performIRGeneration(swift::IRGenOptions&, swift::ModuleDecl*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 1282
8 swift 0x000000010f85c1c7 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*) + 23687
9 swift 0x000000010f854265 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 17029
10 swift 0x000000010f81182d main + 8685
11 libdyld.dylib 0x00007fffa49cd255 start + 1
12 libdyld.dylib 0x00000000000000c6 start + 1533226610
**More_Stuff**...
While emitting IR for source file /xx/xx/xx/xx/xx/xx/xx/SampleViewController.swift
的最終目標是能夠做到這一點:
class SampleViewController<T: DataSourceable>: UIViewController, DataAccepting {
var intArray = [Int]()
func setup() {
T.getMoreData(dataAcceptor: self)
}
func accept(data: [Any]) {
intArray = data
}
}
struct SampleModel: DataSourceable {
static func getMoreData<T: DataAccepting>(dataAcceptor: T) {
var anIntArray = [Int]()
someObject.accept(anIntArray)
}
}
,然後作出SampleViewController<SampleModel>
。 這將允許我讓SampleModel處理控制器的採購數據。 SampleModel決定如何獲取數據,然後使用控制器上的accept()函數將數據提供給SampleController。
好吧,狗屎。 = /總是看到有效的Swift導致編譯器錯誤。 – Alexander
雖然如果你要將自我作爲一個參數傳遞,爲什麼首先使它成爲靜態方法呢?你可以使它成爲一個參數的實例方法,並調用'self.someProtocolMethod(num:0)' – Alexander
@AlexanderMomchliov嗯,我不確定這會實現相同的行爲。基本上符合'ProcotolA'的每個類型都需要一個可以接受'Int'和一個泛型類型爲'T'的對象的函數。讓我編輯我的問題,使其更復雜;)。 'someProtocolMethod()'中的'T'類型也有一個約束。 –