从Swift中的函数返回数组

时间:2015-07-29 04:50:08

标签: arrays swift

所以我对swift和object-c也有点新意,并且想知道是否有人可以帮助我。

我以前经常创建一个utils文件,我在编程中经常使用这些函数。

在这种情况下,我试图从另一个swift文件调用一个函数并返回一个数据数组。

例如在我的mainViewController.swift中调用函数:

var Data = fbGraphCall()

在Utils.swift文件中,我有一个函数,我试图让它返回收集的数据数组。

func fbGraphCall() -> Array<String>{

var fbData: [String] = [""]

if (FBSDKAccessToken.currentAccessToken() != nil){

    // get fb info
    var userProfileRequestParams = [ "fields" : "id, name, email, about, age_range, address, gender, timezone"]

    let userProfileRequest = FBSDKGraphRequest(graphPath: "me", parameters: userProfileRequestParams)

    let graphConnection = FBSDKGraphRequestConnection()

    graphConnection.addRequest(userProfileRequest, completionHandler: { (connection: FBSDKGraphRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
        if(error != nil) {

            println(error)

        } else {

            // DEBUG
            println(result)


            let fbEmail = result.objectForKey("email") as! String

            // DEBUG
            println(fbEmail)

            fbData.append("\(fbEmail)")

            let fbID = result.objectForKey("id") as! String


            if(fbEmail != "") {
                PFUser.currentUser()?.username = fbEmail
                PFUser.currentUser()?.saveEventually(nil)
            }

            println("Email: \(fbEmail)")

            println("FBUserId: \(fbID)")


        }


    })

    graphConnection.start()
}

println(fbData)
return fbData
}

我可以确认我使用我的调试语句从Facebook获取fbEmail和fbID,但正如我所说,我仍然是关于如何返回数据的新方法。

理想情况下,我通常需要一个数组,如果它有多个值或者能够获取像Data.fbEmail, Data.fbID这样的数据,或者数组可能像["email" : "email@gmail.com", "id" : "1324134124zadfa"]那样

当我点击返回语句时它的空白..所以不确定为什么常量不保留值或将值传递到我的fbData数组中..我尝试fbData.append(fbEmail)例如..

对可能出错的任何想法?

1 个答案:

答案 0 :(得分:2)

graphConnection.addRequest是一个异步函数,你试图synchronously返回字符串数组。这不会起作用,因为graphConnection.addRequest是在后台完成的,以避免阻塞主线程。因此,不是直接返回数据,而是制作完成处理程序。您的功能将成为这个:

func fbGraphCall(completion: ([String]) -> Void, errorHandler errorHandler: ((NSError) -> Void)?) {
    if (FBSDKAccessToken.currentAccessToken() != nil) {
        // get fb info
        var userProfileRequestParams = [ "fields" : "id, name, email, about, age_range, address, gender, timezone"]

        let userProfileRequest = FBSDKGraphRequest(graphPath: "me", parameters: userProfileRequestParams)

        let graphConnection = FBSDKGraphRequestConnection()

        graphConnection.addRequest(userProfileRequest, completionHandler: { (connection: FBSDKGraphRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
            if(error != nil) {
                println(error)
                errorHandler?(error!)
            } else {
                var fbData = [String]() // Notice how I removed the empty string you were putting in here.
                // DEBUG
                println(result)


                let fbEmail = result.objectForKey("email") as! String

                // DEBUG
                println(fbEmail)

                fbData.append("\(fbEmail)")

                let fbID = result.objectForKey("id") as! String


                if(fbEmail != "") {
                    PFUser.currentUser()?.username = fbEmail
                    PFUser.currentUser()?.saveEventually(nil)
                }

                println("Email: \(fbEmail)")

                println("FBUserId: \(fbID)")

                completion(fbData)
            }


        })

        graphConnection.start()
    }
}

我添加了完成处理程序和根据需要执行的错误处理程序块。

现在,在通话网站,您可以执行以下操作:

fbGraphCall( { println($0) // $0 refers to the array of Strings retrieved }, errorHandler:  { println($0) // TODO: Error handling  }) // Optionally you can pass `nil` for the error block too incase you don't want to do any error handling but this is not recommended.

修改

为了使用变量,您可以在呼叫站点

执行此类操作
 fbGraphCall( { array in
      dispatch_async(dispatch_get_main_queue(), {  // Get the main queue because UI updates must always happen on the main queue.
             self.fbIDLabel.text = array.first // array is the array we received from the function so make sure you check the bounds and use the right index to get the right values.
             self.fbEmailLabel.text = array.last 
      })
 }, errorHandler:  { 
        println($0) 
        // TODO: Error handling  
  })