jjzjj

swift - 离开函数前执行代码

coder 2023-09-11 原文

我目前正在为 sqlite 数据库编写一些代码。我注意到在准备查询之后,我总是需要在退出函数之前完成查询 (sqlite3_finalize(statementPointer))。除了填写所有可能性之外,还有其他方法可以做到这一点吗?

例如:

func updateColumn(db: COpaquePointer, name: String, x: sqlite3_int64, y: String!=nil) -> Bool {
    var statement = "UPDATE MY_TABLE SET X=?"
    var statementPointer: COpaquePointer = nil
    if y != nil {
        statement += ", Y=?"
    }
    statement += " WHERE NAME=?"
    if sqlite3_prepare_v2(db, statement, -1, &statementPointer, nil) != SQLITE_OK {
        return false
    } else if sqlite3_bind_int64(statementPointer, 1, x) != SQLITE_OK {
        // Note this code here
        sqlite3_finalize(statementPointer)
        return false
    }

    if y != nil {
        if sqlite3_bind_text(statementPointer, 2, y, -1, nil) != SQLITE_OK {
            // Note this repetition
            sqlite3_finalize(statementPointer)
            return false
        }
    }

    if sqlite3_step(statementPointer) != SQLITE_DONE {
        // Note this repetition
        sqlite3_finalize(statementPointer)
        return false
    }
    // Note this repetition
    sqlite3_finalize(statementPointer)
    return true
}

当然,这只是我想来说明的。在实际代码中,还有许多其他 if 子句,我需要这些子句来完成它们的语句。

我知道这类似于 deinit 用于 swift 中的类,但是函数也有 deinit 吗?

例如(我希望它是这样但不起作用的代码):

func updateColumn(params...) -> Bool {
    // code...
    deinit {
        sqlite3_finalize(statementPointer)
    }
}

最佳答案

是的,有一个“deinit for functions”——它叫做defer :

A defer statement is used for executing code just before transferring program control outside of the scope that the defer statement appears in.

请注意,与您的假设示例不同,defer 语句必须出现在 之前 可能导致它执行清理的任何事情,而不是出现在封闭范围的末尾。一般来说,它是这样工作的:

func doStuff() {
    let resource = acquireResource()
    defer {
        cleanup(resource)
    }
    if something { return }
    doOtherStuff()
}

在这里,cleanup(resource) 被调用,无论函数是因为 if something 还是因为它到达其范围的末尾(在 doOtherStuff 之后)而退出()).

您不能像您所要求的那样将 defer 放在 if 中——它只会延迟到它所在范围的导出,所以它会在 if 主体的末尾执行。但是 defer 确实与 guard 组合得很好......在你的情况下,你可能想要这样的东西:

func updateColumn(db: COpaquePointer, name: String, x: sqlite3_int64, y: String!=nil) -> Bool {
    var statementPointer: COpaquePointer = nil
    //... Other stuff...

    guard sqlite3_prepare_v2(db, statement, -1, &statementPointer, nil) == SQLITE_OK
        else { return false }
    // after this you want any possible exit to do finalize, so put the defer here
    defer { sqlite3_finalize(statementPointer) }

    // every `return` after here, true or false, will execute the `defer` clause
    guard sqlite3_bind_int64(statementPointer, 1, x) == SQLITE_OK 
        else { return false }

    guard y != nil && sqlite3_bind_text(statementPointer, 2, y, -1, nil) == SQLITE_OK 
        else { return false }

    guard sqlite3_step(statementPointer) == SQLITE_DONE 
        else { return false }

    return true
}

关于swift - 离开函数前执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38864459/

有关swift - 离开函数前执行代码的更多相关文章

  1. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  2. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  3. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  4. ruby - 如何离开加入Arel? - 2

    Arel3.0.2提供了两个类来指定连接类型:Arel::Nodes::InnerJoin和Arel::Nodes::OuterJoin并使用InnerJoin默认。foo=Arel::Table.new('foo')bar=Arel::Table.new('bar')foo.join(bar,Arel::Nodes::InnerJoin)#innerfoo.join(bar,Arel::Nodes::OuterJoin)#outerfoo.join(bar,???)#left如果要生成左连接,如何连接两个表? 最佳答案 你可以使用

  5. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  6. ruby - Chef 执行非顺序配方 - 2

    我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul

  7. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  8. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  9. ruby-on-rails - 浏览 Ruby 源代码 - 2

    我的主要目标是能够完全理解我正在使用的库/gem。我尝试在Github上从头到尾阅读源代码,但这真的很难。我认为更有趣、更温和的踏脚石就是在使用时阅读每个库/gem方法的源代码。例如,我想知道RubyonRails中的redirect_to方法是如何工作的:如何查找redirect_to方法的源代码?我知道在pry中我可以执行类似show-methodmethod的操作,但我如何才能对Rails框架中的方法执行此操作?您对我如何更好地理解Gem及其API有什么建议吗?仅仅阅读源代码似乎真的很难,尤其是对于框架。谢谢! 最佳答案 Ru

  10. ruby - 为什么 Ruby 的 each 迭代器先执行? - 2

    我在用Ruby执行简单任务时遇到了一件奇怪的事情。我只想用每个方法迭代字母表,但迭代在执行中先进行:alfawit=("a".."z")puts"That'sanalphabet:\n\n#{alfawit.each{|litera|putslitera}}"这段代码的结果是:(缩写)abc⋮xyzThat'sanalphabet:a..z知道为什么它会这样工作或者我做错了什么吗?提前致谢。 最佳答案 因为您的each调用被插入到在固定字符串之前执行的字符串文字中。此外,each返回一个Enumerable,实际上您甚至打印它。试试

随机推荐