What am I doing wrong in Swift for calling this Objective-C block/API call?

后端 未结 3 1196
后悔当初
后悔当初 2021-01-20 01:40

I\'m using RedditKit to integrate Reddit into an app, and in Objective-C I called the API as follows (and it worked fine):

    [[RKClient sharedClient] signI         


        
相关标签:
3条回答
  • 2021-01-20 01:41

    Note: This issue is the same as in these questions:

    animateWithDuration:animations:completion: in Swift

    Properly referencing self in dispatch_async


    Thanks for adding the example project, the issue is as follows:

    From the Swift book: https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Closures.html

    One of the optimizations of Closures is:

    Implicit returns from single-expression closures

    So... the compiler thinks your closure is returning a value of NSURLSessionDataTask because it is the only line inside the closure block, thus changing the type of the argument.

    There are a few ways to solve this, none that are ideal...

    The idea is that any other line you add into the closure will fix it, so this will literally work:

          RKClient.sharedClient().signInWithUsername("username", password: "password", completion: { error -> () in
                let a = 1
                RKClient.sharedClient().frontPageLinksWithPagination(nil, completion: nil)
            })
    

    A slightly cleaner way to solve this would be:

    RKClient.sharedClient().signInWithUsername("username", password: "password", completion: { error in
        let client = RKClient.sharedClient()
        client.frontPageLinksWithPagination(nil, completion: nil)
    })
    

    This wouldn't be an issue if you simply had more code to put into that closure as well!

    0 讨论(0)
  • 2021-01-20 01:45

    It probably doesn't like your RKLink[]! type for collection as NSArray can theoretically contain any type of object. Try making collection an Array<AnyObject>! or just an NSArray! to confirm.

    0 讨论(0)
  • 2021-01-20 02:03

    For completeness here's some code that works:

        RKClient.sharedClient().frontPageLinksWithPagination(nil, completion: {
            (collection, pagination, error) in
            if let links = collection as? RKLink[] {
                for link in links {
                    println(link.title)
                }
            }
        })
    
    0 讨论(0)
提交回复
热议问题