【发布时间】:2015-06-15 23:13:31
【问题描述】:
问题嵌入在 cmets 以及此处:
- 如何在参数列表中为泛型 T 定义默认值?
- 在 Swift 中复制参数时,是指针还是对象?
- XCode Beta 7 告诉我无法更改“head”,因为它是“let”,请参阅代码
- 任何类似 Swift 的方法来循环检查 nil 以避免展开?
链表实现:
public class Node<T>
{
public var data: T
public var next: Node<T>?
//1.
//How can I define a default datatype for T?
//In C++ I would let T ctor do it: "data: T = T()" gives
//error: 'T' cannot be constructed because it has no accessible initializers
public init(data: T, next: Node<T>?)
{
self.data = data
self.next = next
}
}
func print<T>(head: Node<T>)
{
var tmp = head //2. Is this a copy of a pointer or an object?
print(tmp.data)
while(tmp.next != nil) //3. Any Swiftier way to do it?
{
tmp = tmp.next!
print(tmp.data)
}
}
func insert<T>(head: Node<T>, _ value: T)
{
var tmp = head
while tmp.next != nil
{
tmp = tmp.next!
}
tmp.next = Node<T>(data: value, next: nil)
}
var head = Node<Int>(data: 1, next: nil)
insert(head, 2)
insert(head, 4)
insert(head, 8)
insert(head, 16)
print(head)
还有,还有其他的cmets吗?我对 Swift 很陌生
【问题讨论】: