将“nil”值赋给Swift中的一般类型变量

前端之家收集整理的这篇文章主要介绍了将“nil”值赋给Swift中的一般类型变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我认为var值:T = nil导致下面的错误,因为XCode不能将nil值转换为通用类型T.
  1. class Node<T> {
  2. var value: T = nil
  3. var next: Node
  4.  
  5. init(value: T) {
  6. self.value = value
  7. self.next = Node()
  8. }
  9.  
  10. init() {
  11. self.next = Node()
  12. }
  13. }

错误消息读取

Could not find an overload for ‘_coversion’ that accepts the supplied
arguments

有没有办法为Swift中的变量分配nil值?

您需要将变量声明为可选项:
  1. var value: T? = nil

不幸的是,这似乎触发了一个未实现的编译器功能

  1. error: unimplemented IR generation feature non-fixed class layout

您可以通过使用NSObject的类型约束声明T来解决它:

  1. class Node<T:NSObject> {
  2. var value: T? = nil
  3. var next: Node
  4.  
  5. init(value: T) {
  6. self.value = value
  7. self.next = Node()
  8. }
  9.  
  10. init() {
  11. self.next = Node()
  12. }
  13. }

猜你在找的Swift相关文章