如何“变强"? Swift 2.0中可选的使用警卫的自我保护 [英] How to "strongify" optional self using guard in Swift 2.0

查看:66
本文介绍了如何“变强"? Swift 2.0中可选的使用警卫的自我保护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个关于以下问题的类似问题如何回答weakify/strongify自我,但我想知道如何使用自我"而不会因if let引起的向右漂移:

There's a similar question about how to weakify/strongify self, which is answered, but I'm wondering how to use "self" without rightward-drifting caused by if let:

Welcome to Apple Swift version 2.0 (700.0.59 700.0.72). Type :help for assistance.
  2> import Foundation
  3> class Foo {
  4.     func guardOptSelf() -> () throws -> Void {
  5.         return { [weak self] in
  6.             guard let self = self else { throw NSError(domain: "I was destroyed!", code: 1, userInfo: nil) }
  7.             self.doSomethingNonOptionalSelf()         
  8.         }
  9.     }
  10. }
repl.swift:6:19: error: pattern matching in a condition requires the 'case' keyword
            guard let self = self else { throw NSError(domain: "I was destroyed!", code: 1, userInfo: nil) }
                  ^
                  case
repl.swift:6:23: error: binary operator '~=' cannot be applied to two 'Foo?' operands
            guard let self = self else { throw NSError(domain: "I was destroyed!", code: 1, userInfo: nil) }

推荐答案

可以影子self;您只需要反引号即可表明您知道自己在做什么".例如:

You can shadow self; you just need backticks to indicate that "you know what you're doing". For example:

foo.doSomethingAsyncWithBar(bar) { [weak self] result in
    guard let `self` = self else { return }
    self.receivedResult(result)
}

或者,在您的示例中:

2> import Foundation
3> class Foo {
4.     func guardOptSelf() -> () throws -> Void {
5.         return { [weak self] in
6.             guard let `self` = self else { throw NSError(domain: "I was destroyed!", code: 1, userInfo: nil) }
7.             self.doSomethingNonOptionalSelf()         
8.         }
9.     }
10. }

这篇关于如何“变强"? Swift 2.0中可选的使用警卫的自我保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆