在 swift 中有没有办法自定义变量命名的声明?

Is there a way to customise declarations for variable naming in swift?

我正尝试在字典中初始化一个值,如下所示,

var og:image: String

但是在og:之后它试图将以og作为变量的类型分配给site_name,这显然是错误的。

Is there a way to assign og:image as variable to String type using special or escape characters?

对此reference,apple并未对这种情况下的变量命名约定提供任何有意义的解释。

编辑-1:

这是澄清字典的代码片段 usage 在 JSON 解析数据结构中,

struct Metadata: Decodable{
    var metatags : [enclosedTags]
}
struct enclosedTags: Decodable{
    var image: String
    var title: String
    var description: String
    var og:site_name: String
}

您不能使用 :(冒号)。但如果你真的想要:

var ogCOLONimage: String

开个玩笑。您可以使用字典或类似的东西:

var images: [String: String] = ["og:image" : "your string"]

现在您可以使用 images["og:image"] 访问您的 og:image 数据。

Swift 允许您在命名变量时使用几乎任何字符。您甚至可以使用 Unicode 字符。

但是,有一些限制:

Constant and variable names can’t contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name.

表示,不能在变量名中使用:。但是,您可以使用与该符号相似的 Unicode 字符。根据您的需要,这可能是一个有效的解决方案。

这里有一个类似于 : 的 Unicode 字符列表,可用于变量名称:

(https://www.compart.com/en/unicode/based/U+003A)

根据您提供的示例,应该是这样的:

struct Metadata: Decodable{
    var metatags : [enclosedTags]
}
struct enclosedTags: Decodable{
    var image: String
    var title: String
    var description: String
    var og:site_name: String
}

事实证明 swift 在结构中变量的命名特异性方面有自己的特点,即 CodingKeys,所以对我来说,下面的命名约定有效,

   struct Metadata: Decodable{
        var metatags: [enclosedTags]

    }
        struct enclosedTags: Decodable{
            let image: String
            let title: String
            let description: String
            let siteName: String

            private enum CodingKeys : String, CodingKey{
                case image = "og:image", title = "og:title", description = "og:description", siteName = "og:site_name"
            }

@hamish 在评论中正确地指出了这一点(感谢伙伴!)