在字符串插值中使用选项时,内存泄漏 [英] Memory leaks when using optionals in string interpolation

查看:100
本文介绍了在字符串插值中使用选项时,内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Swift进行字符串插值时检测到内存泄漏。使用泄漏工具,它将泄漏的对象显示为Malloc 32字节,但没有负责的库或框架。这似乎是由字符串插值中的选项使用引起的。

I am detecting a memory leak when using string interpolation with Swift. Using the "Leaks" instrument, it shows the leaked object as a "Malloc 32 bytes", but no responsible library or frame. This seems to be caused by using optionals in string interpolation.

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).")
    }
}

但是,如果我简单地通过附加片段来构建字符串来替换字符串插值,没有内存泄漏。

However, if I replace the string interpolation with simply building a String by appending pieces, no memory leak.

    // 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 ?

Is there something I am doing wrong above, or just a Swift bug?

推荐答案

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

Answering my own question...

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

It seems conditional binding is the right way to go when using string interpolation, rather than using the optionals directly. Not sure why the compiler even allows that.

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

Note: If someone has a better answer or better explanation, please add a new answer.

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).")
    }
}

这篇关于在字符串插值中使用选项时,内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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