宏 - > - >>在Clojure

时间:2015-08-23 13:31:09

标签: clojure macros

->>import GameKit class GameViewController: UIViewController,UIGestureRecognizerDelegate, GKGameCenterControllerDelegate { var score: PointsLabel! override func viewDidLoad() { super.viewDidLoad() //initiate gamecenter func authenticateLocalPlayer(){ let localPlayer = GKLocalPlayer.localPlayer() localPlayer.authenticateHandler = {(GameViewController, error) -> Void in if (GameViewController != nil) { self.presentViewController(GameViewController!, animated: true, completion: nil) } else { print((GKLocalPlayer.localPlayer().authenticated)) } } } } @IBAction func leaderboard(sender: UIButton) { saveHighscore(score) showLeader() } //send high score to leaderboard func saveHighscore(score:Int) { //check if user is signed in if GKLocalPlayer.localPlayer().authenticated { let scoreReporter = GKScore(leaderboardIdentifier: "Leaderboard_01") scoreReporter.value = Int64(score) let scoreArray: [GKScore] = [scoreReporter] GKScore.reportScores(scoreArray, withCompletionHandler: {error -> Void in if error != nil { print("error") } }) } } //shows leaderboard screen func showLeader() { let vc = self.view?.window?.rootViewController let gc = GKGameCenterViewController() gc.gameCenterDelegate = self vc?.presentViewController(gc, animated: true, completion: nil) } } //hides leaderboard screen func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) { gameCenterViewController.dismissViewControllerAnimated(true, completion: nil) } 宏只是为了使代码更具可读性还是还有其他特定功能?

1 个答案:

答案 0 :(得分:7)

线程优先(->)和线程最后(->>)是为了使代码更具可读性。但那已经非常重要了!

它允许取消嵌套函数调用(例如取自clojuredocs):

;; Arguably a bit cumbersome to read:
user=> (first (.split (.replace (.toUpperCase "a b c d") "A" "X") " "))
"X"

;; Perhaps easier to read:
user=> (-> "a b c d" 
           .toUpperCase 
           (.replace "A" "X") 
           (.split " ") 
           first)

它还允许您强调某些事情。例如,考虑:

(-> {... }
    ...
    ...
    (count)) 

(count (...(... {...})))

在第一个示例中,很明显您从地图开始,然后对其执行某些操作。在第二个中,很明显你算了一些东西。

偏好取决于您想要提出的内容。

此外,-> vs ->>的选择是一个明确的视觉指标:您是否在收藏品上运作?这很明显(这是Clojure中的一个约定,将集合作为最后一个参数)。

所以是的,它只是“可读”,但这是构建程序的一个非常重要的部分,而Clojure为您提供了自然地读取代码的工具。选择一种解决方案时,我会尝试考虑the way Clojure will be read