Last active
May 18, 2019 08:44
-
-
Save T-Pham/44fe5b7c3a669db34d856b54e15f278a to your computer and use it in GitHub Desktop.
Checking array type issue in Swift
This file contains hidden or 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 | |
// Alamofire | |
enum AlamofireReponse<T, E> { | |
case Success(T) | |
case Failure(E) | |
} | |
func responseJSON(alamofireReponse: AlamofireReponse<AnyObject, NSError> -> Void) { | |
alamofireReponse(.Success([["type": "not_object"], ["type": "not_object"]])) | |
} | |
// ObjectMapper | |
protocol Mappable { | |
init() | |
} | |
// AlamofireObjectMapper | |
func responseObject<T: Mappable>(alamofireReponse: AlamofireReponse<T, NSError> -> Void) { | |
alamofireReponse(.Success(T())) | |
} | |
func responseArray<T: Mappable>(alamofireReponse: AlamofireReponse<[T], NSError> -> Void) { | |
alamofireReponse(.Success([T(), T()])) | |
} | |
// RealmSwift | |
class Object {} | |
func add(object: Object) { | |
print("adding single object works") // This line would run | |
} | |
func add<T: SequenceType where T.Generator.Element: Object>(objects: T) { | |
print("adding multiple objects works") // This line would not | |
} | |
// My code | |
final class Post: Object, Mappable {} | |
final class Comment: Object, Mappable {} | |
enum MyResponse<T> { | |
case Success(T) | |
case Failure(NSError) | |
} | |
func myRequestJSON(completionHandler: (MyResponse<AnyObject> -> Void)) { | |
responseJSON { alamofireReponse in | |
handleResponse(alamofireReponse, completionHandler: completionHandler) | |
} | |
} | |
func myRequestObject<T: Mappable>(completionHandler: (MyResponse<T> -> Void)) { | |
responseObject { alamofireReponse in | |
handleResponse(alamofireReponse, completionHandler: completionHandler) | |
} | |
} | |
func myRequestArray<T: Mappable>(completionHandler: (MyResponse<[T]> -> Void)) { | |
responseArray { alamofireReponse in | |
handleResponse(alamofireReponse, completionHandler: completionHandler) | |
} | |
} | |
func handleResponse<T>(alamofireReponse: AlamofireReponse<T, NSError>, completionHandler: (MyResponse<T> -> Void)) { | |
switch alamofireReponse { | |
case .Success(let data): | |
if let object = data as? Object { | |
add(object) | |
} else if let array = data as? [Object] { | |
add(array) | |
} | |
completionHandler(.Success(data)) | |
case .Failure(let error): | |
completionHandler(.Failure(error)) | |
} | |
} | |
// Usage | |
myRequestJSON { response in | |
} | |
myRequestObject { (response: MyResponse<Post>) in | |
} | |
myRequestArray { (response: MyResponse<[Post]>) in | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment