我练形体的时候玩得很开心.
我想实现我的解决方案as中的functions和Int
中的extension中的一个,因为我喜欢拥有漂亮语法的 idea .该函数本身如下所示:
func decomposed(_ n: Int) -> [Int] {
if n > 10 {
return n.decomposed(n / 10) + [n % 10]
} else {
return [n]
}
}
现在,我试着把它当作extension来实现.由于我想要像420.decomposed()
一样使用它,所以我想我需要instance作为default argument.我接着说:
extension Int {
func decomposed(_ n: Int = self) -> [Int] {
if n > 10 {
return n.decomposed(n / 10) + [n % 10]
} else {
return [n]
}
}
}
然而,这是它变得更加棘手的部分.编译器告诉我error: cannot find 'self' in scope
.
在阅读了方法in the docs之后,我求助于使用Int?
默认参数.现在,该扩展实现为:
extension Int {
func decomposed(_ n: Int? = nil) -> [Int] {
var _n = n ?? self
if _n > 10 {
return _n.decomposed(_n / 10) + [_n % 10]
} else {
return [_n]
}
}
}
I don't like the look of the _n
, though.
I would love to use self as the default argument. Is that possible? Or are we stuck with hackity hacks until the judgement day?