Desmond
Desmond

Reputation: 787

How can I init this kind of Enum which contains properties and no constructor in Swift?

In Alamofire, I find there is a enum:

public enum Result<Value, Error : ErrorType> {
case Success(Value)
case Failure(Error)
/// Returns `true` if the result is a success, `false` otherwise.
public var isSuccess: Bool { get }
/// Returns `true` if the result is a failure, `false` otherwise.
public var isFailure: Bool { get }
/// Returns the associated value if the result is a success, `nil` otherwise.
public var value: Value? { get }
/// Returns the associated error value if the result is a failure, `nil` otherwise.
public var error: Error? { get }
}

In struct Response, I will need to give its constructor a Result.

 public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Alamofire.Result<Value, Error>)

But sadly, I find there is no init inside struct Response and every property only has a getter. So how could I init a Response and use it to init struct Response?

Upvotes: 0

Views: 81

Answers (2)

Danielle Cohen
Danielle Cohen

Reputation: 667

I usually use this:

Response(request: NSURLRequest(), response: NSHTTPURLResponse(), data: NSData(), result: Result<String,NSError>.Success("lalala"))

Thats the easiest way.

Upvotes: 2

fluidsonic
fluidsonic

Reputation: 4676

Like this:

Response(request: NSURLRequest(), response: NSHTTPURLResponse(), data: NSData(), result: Result<String,NSError>.Success("abc"))

or this:

let result: Result<String,NSError> = .Success("abc")
Response(request: NSURLRequest(), response: NSHTTPURLResponse(), data: NSData(), result: result)

You need to use the full Result<…> because Swift can only ever infer one of the generic type arguments.

Upvotes: 2

Related Questions