# 打破 Swift 结构体中的循环引用

+关注继续查看

## 在结构体中类的作用域

public final class OnDelete {
var closure: () -> Void
public init(_ c: () -> Void) {
closure = c
}
deinit {
closure()
}
}

struct DeletionLogger {
let od = OnDelete { print("DeletionLogger deleted") }
}

do {
let dl = DeletionLogger()
print("Not deleted, yet")
}

Not deleted, yet
DeletionLogger deleted

## 尝试从一个闭包中访问结构体

struct Counter {
let count = 0
let od = OnDelete { print("Counter value is \(count)") }
}

struct Counter {
let count = 0
var od: OnDelete? = nil
init() {
od = OnDelete { print("Counter value is \(self.count)") }
}
}

"Excellent!"，我现在很开心(I'm Angry!)。

struct Counter {
var count: Int
let od: OnDelete
init() {
let c = 0
count = c
od = OnDelete { print("Counter value is \(c)") }
}
}

struct Counter {
var count = 0
let od: OnDelete?
init() {
od = OnDelete { [count] in print("Counter value is \(count)") }
}
}

struct Counter {
var count = 0
var od: OnDelete?
init() {
od = OnDelete { print("Counter value is \(self.count)") }
}
}

## 疯狂的循环

do {
let c = Counter()
print("Not deleted, yet")
}

Not deleted, yet

%1 = alloc_box \$Counter, var, name "self", argno 1 // users: %2, %20, %22, %29

## 我们要怎样破解这个循环？

var c = Counter()
c.od = nil

## 复制行不通，共享引用怎么样？

struct Counter {
var count = 0
var od: OnDelete? = nil
static func construct() -> Counter {
var c = Counter()
c.od = OnDelete{
print("Value loop break is \(c.count)")
}
return c
}
}

do {
var c = Counter.construct()
c.count += 1
c.od = nil
}

struct Counter {
var count = 0
var od: OnDelete? = nil
static func construct() -> () -> () {
var c = Counter()
c.od = OnDelete{
print("Value loop break is \(c.count)")
}
return {
c.count += 1
c.od = nil
}
}
}

do {
var loopBreaker = Counter.construct()
loopBreaker()
}

Counter value is 1

# 一些观点

class Counter {
var count = 0
deinit {
print("Counter value is \(count)")
}
}

## 说在最后

Swift实用小册08:Class类的Struct结构体的使用
Swift实用小册08:Class类的Struct结构体的使用
151 0
Swift讲解专题十——类与结构体
Swift讲解专题十——类与结构体
47 0
16.Swift学习之结构体

851 0
swift4.1 系统学习十三 结构体(二)
965 0
swift4.1 系统学习十三 结构体(一)
/* 结构体 大部分语言中都会有结构体。swift中的结构体属于四大基本类型(函数、枚举、结构体、类)之一，他属于值类型。 标准库中的很多类型都是结构体类型，像Int、Float、String、Array。
893 0

2557 0
[译]Swift 结构体指针

1081 0
+关注

OpenStack Swift 海量小文件性能优化之路

From Java_Android to Swift iOS

Swift在Airbnb的应用实践