ios – 在字符串插值中使用选项时内存泄漏

我在使用 Swift进行字符串插值时检测到内存泄漏.使用“泄漏”工具,它将泄漏的对象显示为“Malloc 32字节”,但没有负责的库或框架.这似乎是由字符串插值中的选项使用引起的.
class MySwiftObject
{
    let boundHost:String?
    let port:UInt16

    init(boundHost: String?,port: UInt16)
    {
        if boundHost {
            self.boundHost = boundHost!
        }
        self.port = port

        // leaks
        println("Server created with host: \(self.boundHost) and port: \(self.port).")
    }
}

但是,如果我通过附加片段简单地构建String来替换字符串插值,则不会发生内存泄漏.

// does not leak
    var message = "Server created with host: "
    if self.boundHost
    {
        message += self.boundHost!
    }
    else
    {
        message += "*"
    }
    message += " and port: \(self.port)"
    println(message)

上面有什么我做错了,或者只是一个Swift bug?

解决方法

回答我自己的问题……

在使用字符串插值时,条件绑定似乎是正确的方法,而不是直接使用选项.不知道为什么编译器甚至允许这样做.

注意:如果有人有更好的答案或更好的解释,请添加新的答案.

init(boundHost: String?,port: UInt16)
{
    if boundHost {
        self.boundHost = boundHost!
    }
    self.port = port

    if let constBoundHost = self.boundHost
    {
        println("Server created with host: \(constBoundHost) and port: \(self.port).")
    }
    else
    {
        println("Server created with host: * and port: \(self.port).")
    }
}

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...