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

我在使用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).") } }