如何在swift中定义泛型类中的静态常量? [英] How to define static constant in a generic class in swift?

查看:510
本文介绍了如何在swift中定义泛型类中的静态常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那么你如何在Swift中定义泛型类常量?



问题



对于普通类,您可以像这样定义它们:

  class C {
static let k = 1
}

让a = Ck // 1

但是如果你对泛型类也做同样的事情:

  class C< T> {
static let k = 1
}

编译:
$ b


通用类型中尚不支持静态存储的属性

那么如何解决这个问题呢?

我目前的解决方案

<现在,我使用 struct 来解决这个问题:

  struct CConstant {
static let K = 1
}

这不是在泛型类的范围内定义,但它适用于我。 您有更好的解决方案吗?

-



ps:我的第一个问题在这里,所以请帮助我改进这个问题,如果你认为这是必要的话)

您可以定义全局常量与 fileprivate 私有访问级别在同一个 .swift 文件在哪里你的泛型类被定义。所以它在这个文件之外是不可见的,并且不会污染全局(模块)名称空间。



如果您需要从当前文件外部访问此常量,则声明它作为内部(默认访问级别)或 public 并将其命名为 ClassConstant ,所以很明显它与 Class



有关 Swift 3中的访问级别


So how do you define generic class constants in Swift?

The problem

For a "normal" class you can define them like this:

class C {
    static let k = 1
}

let a = C.k // 1

But if you do the same on a generic class:

class C<T> {
    static let k = 1
}

You get the following error on compilation:

Static stored properties not yet supported in generic types

So how to solve this?

My current solution

Right now, I'm using struct to solve this:

struct CConstant {
     static let K = 1
 }

This is not defined in the scope of the generic class but it works for me. Do you have a better solution?

--

ps: this is my first question here, so please help me improve this question if you think it is necessary =)

解决方案

You can define global constant with fileprivate or private access level in the same .swift file where your generic class is defined. So it will not be visible outside of this file and will not pollute global (module) namespace.

If you need to access this constant from outside of current file then declare it as internal (default access level) or public and name it like ClassConstant so it will be obvious that it relates to Class.

Read more about access levels in Swift 3.

这篇关于如何在swift中定义泛型类中的静态常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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