gpt4 book ai didi

swift - 如何访问函数内的变量然后使用它?

转载 作者:行者123 更新时间:2023-11-30 10:17:49 24 4
gpt4 key购买 nike

我正在尝试访问函数 checkUser() 内的变量 i。接下来是 if 语句,if i == 0 应该 println("Displaying Picture of Others")

底部的代码不起作用,因为函数 checkUser 不返回 i 值,并且我收到错误:使用未解析的标识符 'i ',但是经过摸索并将代码调整为:

func checkUser() -> (Int?) {
var i = 0
return (i)
}

var (i) = checkUser()
if i == 0{
println("Value is set")
}

并实现它,我得到一个错误int is not conversion to void。我有哪些选择可以使其发挥作用?

<小时/>
func checkUser(){
var reqest = PFUser.query()

reqest.whereKey("username", equalTo: self.user.username)
reqest.whereKey("check", equalTo: true)
reqest.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!)-> Void in
if error == nil {
println("Successfully retrieved \(objects.count) item.")

var i = objects.count // variable that holds objects.count

if let objects = objects as? [PFObject] {
for object in objects {
println(object.objectId)
if object["check"] as Bool == true{
println("Displaying Picture of You")
}
}
}
} else {
// Log details of the failure
println("Error: \(error) \(error.userInfo!)")
}
}

if i == 0{
println("Displaying Picture of Someone else")
}
}

最佳答案

如果你想根据请求的结果计数显示别人的图片,你可以调用一个函数,而不是创建和检查条件:

func checkUser(){
var reqest = PFUser.query()

reqest.whereKey("username", equalTo: self.user.username)
reqest.whereKey("check", equalTo: true)
reqest.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!)-> Void in
if error == nil {
println("Successfully retrieved \(objects.count) item.")

if (objects.count == 0) {
displayPicture()
}

if let objects = objects as? [PFObject] {
for object in objects {
println(object.objectId)
if object["check"] as Bool == true{
println("Displaying Picture of You")
}
}
}
} else {
// Log details of the failure
println("Error: \(error) \(error.userInfo!)")
}
}

displayPicture() {
println("Displaying Picture of someone else")
}
}

关于swift - 如何访问函数内的变量然后使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29204105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com