Skip to content

Instantly share code, notes, and snippets.

@SwiftStudies
Last active May 11, 2018 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SwiftStudies/5a8e4d958ad526fbf82fc7038caabd3f to your computer and use it in GitHub Desktop.
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?
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")
@SwiftStudies
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment