I think the essence of your question is: why not use a private function instead of an ugly nested function?
Simply put, nested functions can facilitate reading and encapsulation.
Readability
- . . , ( , ). , , !
, , , . ? . , . , .
, 5 , 3 , , , , .
, , , .
, . . , . , , self
. , .
, , , :
extractAllHebrewNames()
extractAllAmericanNames()
extractAllJapaneseNames()
, printName ( ), , , / . ( . .) .
, " " " ".
, ( -, ).
. .
: ""
func doSomething(){
nested()
func nested(){
}
}
:
func doSomething(){
func nested(){
}
nested()
}
, , ,
:
, self
.
. :
Call to method 'doZ' in closure requires explicit 'self.' to make capture semantics explicit
. ,
class P {
var name: String
init(name: String) {
print("p was allocated")
self.name = name
}
func weaklyNested() {
weak var _self = self
func doX() {
print("nested:", _self?.name as Any)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
doX()
}
}
func stronglyNested() {
func doZ() {
print("nested:", name)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
doZ()
}
}
deinit {
print("class P was deinitialized")
}
}
class H {
var p: P
init(p: P) {
self.p = p
}
}
var h1: H? = H(p: P(name: "john"))
h1?.p.weaklyNested()
h1 = nil
var h2: H? = H(p: P(name: "john"))
h2?.p.stronglyNested()
h2 = nil
tl;dr :
weak var _self = self
self
weak
.- :( .
. ?