如何在Swift中知道从内存中删除了struct? [英] How in Swift to know that struct is deleted from Memory?

查看:119
本文介绍了如何在Swift中知道从内存中删除了struct?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在快速的 class 中,类型具有方法deinit(),我们可以在其中定义将从内存中删除的class实例.我们如何知道 struct 它将从内存中删除?

In swift class type has method deinit() in which we can define that instance of class will be removed from memory. How we can know for struct that it will be removed from memory?

例如,

struct Vehicle { ... }
var v: Vehicle? = Vehicle()
v = nil

推荐答案

结构超出范围时,它们将被释放.您不能将deinit放在结构中,但这是一种解决方法.您可以创建一个引用到一个类的结构,该类在释放时会打印一些东西.

Structs are deallocated when they go out of scope. You can't put a deinit in a struct, but here is a workaround. You can make a struct that has a reference to a class that prints something when deallocated.

class DeallocPrinter {
    deinit {
        print("deallocated")
    }
}

struct SomeStruct {
    let printer = DeallocPrinter()
}  

因此,在释放该结构时-如果尚未复制该结构的副本,则在释放该结构时,它将打印已释放的结构,因为DeallocPrinter将在该结构被释放的同时被释放.

So when the struct is deallocated - if you haven't made a copy of the struct, it'll print deallocated when it's deallocated, since the DeallocPrinter will be deallocated at the same time the struct is deallocated.

这篇关于如何在Swift中知道从内存中删除了struct?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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