gpt4 book ai didi

swift - 以= {}()结尾的变量名称是什么Swift?

转载 作者:搜寻专家 更新时间:2023-11-01 06:24:57 25 4
gpt4 key购买 nike

我一直在挖掘 Swift 文档,试图找到下面的 Swift 语法的名称。

static let taskDateFormat: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}()

我不知道如何称呼这种语法。我对 = {} () 组件感到困惑。这个叫什么?

最佳答案

它是为 taskDateFormat 属性生成默认 DateFormatter 值的代码。

根据 Swift 手册(强调我的):

https://docs.swift.org/swift-book/LanguageGuide/Initialization.html

Setting a Default Property Value with a Closure or Function

If a stored property’s default value requires some customization or setup, you can use a closure or global function to provide a customized default value for that property. Whenever a new instance of the type that the property belongs to is initialized, the closure or function is called, and its return value is assigned as the property’s default value.

Note that the closure’s end curly brace is followed by an empty pair of parentheses. This tells Swift to execute the closure immediately. If you omit these parentheses, you are trying to assign the closure itself to the property, and not the return value of the closure.

基本上,代码将 taskDateFormat 属性预初始化为新的 DateFormatter 对象,并在 taskDateFormat< 之前设置 dateStyle 属性 属性已设置。

关于swift - 以= {}()结尾的变量名称是什么Swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57718999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com