Ios 以迅捷的速度通过街区
在我的应用程序I中,用户只有在登录时才能执行各种操作 例如,“喜欢”一幅画 当未登录的用户尝试执行这些操作时,我希望显示一个登录屏幕,如果登录成功,则立即执行该操作。(如果他们已经登录,则会立即执行该操作。) 下面是一些伪代码:Ios 以迅捷的速度通过街区,ios,iphone,swift,Ios,Iphone,Swift,在我的应用程序I中,用户只有在登录时才能执行各种操作 例如,“喜欢”一幅画 当未登录的用户尝试执行这些操作时,我希望显示一个登录屏幕,如果登录成功,则立即执行该操作。(如果他们已经登录,则会立即执行该操作。) 下面是一些伪代码: // in view controller, user taps like block variable likeBlock = { likePicture(id) } if loggedin perform likeBlock else appDel
// in view controller, user taps like
block variable likeBlock = { likePicture(id) }
if loggedin
perform likeBlock
else
appDelegate.attemptLoginWithViewController(thisViewController)
andSuccess(likeBlock) andFailure(showError)
endif
func likePicture(id:int) {
}
// in appDelegate
attemptLoginWithViewController(vc) andSuccess(likeBlock) andFailure(showError) {
displayLogin, with success (perform likeBlock on vc)
andFailure (perform showError on vc)
}
我无法在Swift中计算出这种块传递的语法。我该怎么做呢?实际上可能比你想象的要容易 当您有一个声明的函数(如
likePicture
)时,您可以将该函数分配给一个变量:
func likePicture(id:int) {
println("Picture \(id) liked")
}
let like = likePicture
if loggedIn {
// then call the stored function
like(1) // prints "Picture 1 liked"
} // etc
因此,除非您想做一些额外的事情,例如在将输入传递到函数之前操纵输入,否则无需声明块来调用它(在Swift中,这些块称为闭包表达式)
因为您可以像对待任何其他值一样对待函数,这意味着您可以这样做:
func hatePicture(id:int) {
println("Picture \(id) hated")
}
let action = someUserInput() ? likePicture : hatePicture
// later...
action(1) // performs liking or hating of picture depending which was picked
所需要的是,可以分配给变量的不同函数都具有相同的类型(即签名、声明等),在这种情况下,它们都是(Int)->Void
类型,即接受一个整数参数而不返回任何内容
因此,要声明接收liking函数作为参数的函数,可以执行以下操作:
func attemptLoginWithViewController(vc: WhateverVCType, #onSuccess: (Int)->Void, #onFailure: (Int)->Void) {
// call onSuccess(id) or onFailure(id) depending
}
// and to call it:
attemptLoginWithViewController(vc, onSuccess: likePicture) { println("aargh kerbang") }
(注意,我没有提供失败函数,而是使用了尾随闭包,但这里的要点是使用
func
定义的函数,使用闭包表达式定义的函数可以互换)谢谢。在我的问题中,我需要像(1)一样将其传递给appDelegate的attemptLogin函数(如果它们未登录)。然后,我需要在原始视图控制器上执行类似(1)的操作(如果登录成功),或者如果不成功,则执行其他操作。我该如何传递这个suff?我现在不在安装了Swift的计算机上,所以请注意我的代码中可能存在的打字/语法错误,但我认为这没关系