这是我的一段代码,
protocol Configuration {
static var url: String { get }
static var username: String { get }
static var password: String { get }
}
protocol Server {
associatedtype Profile: Configuration
associatedtype Payment: Configuration
associatedtype Images: Configuration
}
struct Development: Server {
struct Profile: Configuration {
static var url: String { return "http://google.com" }
static var username: String { return "abc" }
static var password: String { return "xyz" }
}
struct Payment: Configuration {
static var url: String { return "http://bing.com" }
static var username: String { return "abc" }
static var password: String { return "xyz" }
}
struct Images: Configuration {
static var url: String { return "http://duckduckgo.com" }
static var username: String { return "abc" }
static var password: String { return "xyz" }
}
}
struct Production: Server {
struct Profile: Configuration {
static var url: String { return "http://amazon.com" }
static var username: String { return "pqr" }
static var password: String { return "xyz" }
}
struct Payment: Configuration {
static var url: String { return "http://facebook.com" }
static var username: String { return "pqr" }
static var password: String { return "xyz" }
}
struct Images: Configuration {
static var url: String { return "http://orkut.com" }
static var username: String { return "pqr" }
static var password: String { return "xyz" }
}
}
问题是我想获取我的'结构'(取决于我的环境)。我需要类似的东西,
struct Environment {
static func current() -> Any:Server {
if #DEBUG
return Development
#endif
return Production
}
}
但是不可能返回确认我的协议的特定类型。
对此或不同方法的任何建议都会有所帮助。
答案 0 :(得分:4)
“发展”和“生产”是价值观,而不是类型。您不需要此处的协议,也不应使用它们。只需创建您需要的值并将其返回:
seguidores = followers[2]
datacount = seguidores.attrs['data-count']
答案 1 :(得分:1)
您可以返回通用类型,或者只需执行以下操作:
struct Config {
static var BaseURL: URL {
switch Environment.current {
case .debug:
return URL(string: "https://...dev.com")!
case .staging:
return URL(string: "https://...staging.com")!
case .release:
return URL(string: "https://...production.com")!
}
}
}
答案 2 :(得分:0)
只需返回Server
,而不是Any:Server
:
static func current() -> Server {
if #DEBUG
return Development
#endif
return Production
}