Swift 在接受可选元素的通用函数中返回展开的元素?
Swift returning unwrapped Element in a generic function that takes in optional Element?
这里的想法是接受一个可选元素和 return 空数组或嵌入了非可选元素的数组。写了一个快速的通用解决方案,但我收到错误 Using '!' is not allowed here; perhaps '?' was intended?
。
有没有办法解包元素并在 return 值中使用它?
public func arrayWithOptional(optional: Element?) -> [Element!] {
if let optional = optional {
return [optional]
}
return []
}
您可以使您的函数通用:
public func arrayWithOptional<Element>(optional: Element?) -> [Element] {
if let optional = optional {
return [optional]
}
return []
}
这里的想法是接受一个可选元素和 return 空数组或嵌入了非可选元素的数组。写了一个快速的通用解决方案,但我收到错误 Using '!' is not allowed here; perhaps '?' was intended?
。
有没有办法解包元素并在 return 值中使用它?
public func arrayWithOptional(optional: Element?) -> [Element!] {
if let optional = optional {
return [optional]
}
return []
}
您可以使您的函数通用:
public func arrayWithOptional<Element>(optional: Element?) -> [Element] {
if let optional = optional {
return [optional]
}
return []
}