Last active
August 29, 2015 14:23
-
-
Save patricklynch/0ab26319bd46afd33886 to your computer and use it in GitHub Desktop.
Responder with generics
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
// A quick way to set up use of responder chain with a bit more type safety | |
// | |
// Created by Patrick Lynch on 6/28/15. | |
// Copyright © 2015 Patrick Lynch. All rights reserved. | |
import UIKit | |
protocol Responder { | |
func targetForAction<T, U: RawRepresentable where U.RawValue == Selector>( action: U, withSender sender: AnyObject?) -> T | |
} | |
extension UIResponder : Responder { | |
func targetForAction<T, U: RawRepresentable where U.RawValue == Selector>( action: U, withSender sender: AnyObject?) -> T { | |
if let responder = self.targetForAction( action.rawValue, withSender: sender ) as? T { | |
return responder | |
} | |
fatalError( "Unable to find responder in chain." ) | |
} | |
} | |
protocol FollowResponder { | |
func followUser( completion:(()->())? ) | |
func unfollowUser( completion:(()->())? ) | |
} | |
enum FollowAction: Selector { | |
case FollowUser = "followUser:" | |
case UnfollowUser = "unfollowUser:" | |
} | |
extension AppDelegate : FollowResponder { | |
func followUser( completion:(()->())? ) { | |
print( "Following user..." ) | |
completion?() | |
} | |
func unfollowUser( completion:(()->())? ) { | |
print( "Unfollowing user..." ) | |
completion?() | |
} | |
} | |
class ViewController: UIViewController { | |
@IBAction func onFollowButtonPressed( sender: AnyObject? ) { | |
let responder: FollowResponder = self.targetForAction( FollowAction.FollowUser, withSender: self ) | |
responder.followUser { | |
print( "User has been followed." ) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment