Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit in Swift
As others said, do what it says.
Instead of:
present(vc, animated: true, completion: nil)
adding self gets:
self.present(vc, animated: true, completion: nil)
Implicit use of self in Swift closure
Since DogYearsTests inherits from XCTestCase, expectation is a method of your class, therefore you should call it with self.
Implicit use of 'self' in closure error when presenting a pop over in Swift 2.2
try this
let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ResetPasswordSuccessPopOver") as ResetPasswordSuccessPopOverViewController
or try this
let viewController = self.storyboard!.instantiateViewControllerWithIdentifier("ResetPasswordSuccessPopOver") as ResetPasswordSuccessPopOverViewController
Implicit self in @escaping Closures when Reference Cycles are Unlikely to Occur Swift 5.3
You still need to manually specify weak
and unowned
captures of self
. The only change SE-0269 results in is that you don't need to explicitly write out self.
when accessing instance properties/methods when acknowledging that you capture self
strongly by using [self]
.
In case of [weak self]
you still need to explicitly write self.
in the closure, but when using [unowned self]
, you can omit self.
just as when using [self]
.
execute { [weak self] in
x += 1 // Error: Reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit
}
execute { [weak self] in
self?.x += 1 // need to manually specify `self?.`
}
execute { [unowned self] in
x += 1 // compiles fine
}
How To run 'performSegue' in a function on Swift5?
When I saw a thread related error, I thought about how to it. And I thought it was an error caused by the asynchronous system. So I solved the problem through asynchronous execution.
DispatchQueue.main.async { self.performSegue(withIdentifier: "makeNickname", sender: self) }
Why is declaring self not required in structures where it's required in classes?
The purpose of including self
when using properties inside an escaping closure (whether optional closure or one explicitly marked as @escaping
) with reference types is to make the capture semantics explicit. As the compiler warns us if we remove self
reference:
Reference to property 'someProperty' in closure requires explicit use of 'self' to make capture semantics explicit.
But there are no ambiguous capture semantics with structs. You are always dealing with a copy inside the escaping closure. It is only ambiguous with reference types, where you need self
to make clear where the strong reference cycle might be introduced, which instance you are referencing, etc.
By the way, with class types, referencing self
in conjunction with the property is not the only way to make the capture semantics explicit. For example, you can make your intent explicit with a “capture list”, either:
Capture the property only:
class SomeClass {
var someProperty = 1
func someMethod(completion: @escaping () -> Void) { ... }
func anotherMethod() {
someMethod { [someProperty] in // this captures the property, but not `self`
print(someProperty)
}
}
}Or capture
self
:class SomeClass {
var someProperty = 1
func someMethod(completion: @escaping () -> Void) { ... }
func anotherMethod() {
someMethod { [self] in // this explicitly captures `self`
print(someProperty)
}
}
}
Both of these approaches also make it explicit what you are capturing.
Why do closures require an explicit `self` when they're all non-escaping by default in Swift 3?
In Swift 3, all closures are non-escaping by default
No, in Swift 3, only closure function arguments (i.e function inputs that are functions themselves) are non-escaping by default (as per SE-0103). For example:
class A {
let n = 5
var bar : () -> Void = {}
func foo(_ closure: () -> Void) {
bar = closure // As closure is non-escaping, it is illegal to store it.
}
func baz() {
foo {
// no explict 'self.' required in order to capture n,
// as foo's closure argument is non-escaping,
// therefore n is guaranteed to only be captured for the lifetime of foo(_:)
print(n)
}
}
}
As closure
in the above example is non-escaping, it is prohibited from being stored or captured, thus limiting its lifetime to the lifetime of the function foo(_:)
. This therefore means that any values it captures are guaranteed to not remain captured after the function exits – meaning that you don’t need to worry about problems that can occur with capturing, such as retain cycles.
However, a closure stored property (such as bar
in the above example) is by definition escaping (it would be nonsensical to mark it with @noescape
) as its lifetime not limited to a given function – it (and therefore all its captured variables) will remain in memory as long as the given instance remains in memory. This can therefore easily lead to problems such as retain cycles, which is why you need to use an explicit self.
in order to make the capturing semantics explicit.
In fact, case in point, your example code will create a retain cycle upon viewDidLoad()
being called, as someClosure
strongly captures self
, and self
strongly references someClosure
, as it's a stored property.
It's worth noting that as an extension of the "stored function properties are always escaping" rule, functions stored in aggregates (i.e structures and enumerations with associated values) are also always escaping, as there's no restrictions on what you do with such aggregates. As pointed out by pandaren codemaster, this currently includes Optional
– meaning that Optional<() -> Void>
(aka. (() -> Void)?
) is always escaping. The compiler might eventually make this a special case for function parameters though, given that optional is already built on a lot of compiler magic.
Of course, one place where you would expect to be able to use the @noescape
attribute is on a closure that’s a local variable in a function. Such a closure would have a predictable lifetime, as long as it isn’t stored outside of the function, or captured. For example:
class A {
let n = 5
func foo() {
let f : @noescape () -> Void = {
print(n)
}
f()
}
}
Unfortunately, as @noescape
is being removed in Swift 3, this won't be possible (What's interesting is that in Xcode 8 GM, it is possible, but yields a deprecation warning). As Jon Shier says, we’ll have to wait for it to be re-added to the language, which may or may not happen.
Related Topics
How to Reconnect Akplayer and Akmixer After Audiokit.Stop()
Compiling for iOS 10.3, But Module 'swiftuicharts' Has a Minimum Deployment Target of iOS 13.0
Can't Set @Ibinspectable Computed Property in UIview
Tintcolor Not Changing for UIbarbuttonitem for .Normal Stage in Case of iOS 13.2
Urlcomponents Queryitems Losing Percent Encoding When Mutated
Underlying Type for Tuple in Swift
Xcode8 Beta 6 - Urlsession with Completionhandler Argument Not Working
Geofire/Firebase Function Is Executing Handler Multiple Times in Swift
Converting Local Realms to Synced Realm
Arkit/Scenekit on iOS 14 Throws New Warning (Metal)
Swift: Simple Dispatchqueue Does Not Run & Notify Correctly
Uitextfield with a Placeholder Containing an Image and Text
Cannot Authenticate User for Aws Appsync with Swift Sdk
Swift: Trunc a Floating Number to Show It in a Label
How to Make a Function Operate on a Sequence of Optional Values
Adding Items to The Dock Menu from My View Controller in My Cocoa App