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

时间:2014-07-22 21:12:14

标签: ios swift

我在使用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错误?

1 个答案:

答案 0 :(得分:7)

回答我自己的问题......

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

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

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).")
    }
}
相关问题