Last active
May 11, 2018 20:08
-
-
Save SwiftStudies/5a8e4d958ad526fbf82fc7038caabd3f to your computer and use it in GitHub Desktop.
Can anyone solve this problem with an extension for classes (non final) and return type from a prototype requirement on a static function?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
public protocol BigData { | |
static func cache(from path:String)->Self | |
} | |
extension String : BigData { | |
public static func cache(from path: String) -> String { | |
return (try? String(contentsOfFile: path)) ?? "Could not load" | |
} | |
} | |
class MyDatabase { | |
} | |
extension MyDatabase : BigData { | |
// static func cache(from path: String) -> BigData doesn't work, 'MyDatabase' doesn't conform to protocol "BigData" | |
static func cache(from path: String) -> Self { | |
// return MyDatabase() as Self doesn't work: 'Self' is only available in a protocol or as the result of a method in a class; did you mean 'MyDatabase'? | |
return MyDatabase() // Cannot convert return expression of type 'MyDatabase' to return type 'Self' | |
} | |
} | |
// I don't want the consumer of this API to have to cast... | |
let stringCache : String = String.cache(from: "/SomeFile.db") | |
let databaseCache : MyDatabase = MyDatabase.cache(from: "/SomeOtherFile.db") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use an associated type (thanks: https://twitter.com/XmasRights/status/995030099698348033) but then you can't pass around the protocol, only specific satisfactions of it https://gist.github.com/SwiftStudies/5a8e4d958ad526fbf82fc7038caabd3f/d62472907e37ce67bb99376fe90fd4607f740425