如何在swift中创建接受任何类型的Int或Uint的函数(并计算关于param类型的位数需求)
这是一个非常简单的递归函数:
func lap (n: Int) -> Int {
if n == 0 { return 0 }
return lap (n - 1)
}
Run Code Online (Sandbox Code Playgroud)
如果我想将其转换为闭包:
let lap = {
(n: Int) -> Int in
if n == 0 { return 0 }
return lap (n - 1)
}
Run Code Online (Sandbox Code Playgroud)
我收到一个编译器错误:"变量在其自己的初始值中使用"
这里等于重载
class MyClass {
...
val string: String = ...
override operator fun equals(other: Any?): Boolean {
if (other != null) else { return false }
if (other is MyClass && string == other.string) { return true }
if (other is String && string == other) { return true }
return false
}
...
}
Run Code Online (Sandbox Code Playgroud)
这个想法是能够比较:
myClass1 = MyClass("ABCDEF")
myClass2 = MyClass("ABC123")
myClass1 == fsPath2 >> false
or
myClass1 == "ABC123" >> false
Run Code Online (Sandbox Code Playgroud)
但预编译显示:运算符 '==' 不能应用于 'MyClass' 和 'String'
任何想法?
在下面的示例中,如何引用当前对象实例以利用输出重载的机会?
class Shape {
private:
double _length, _width;
double straight(double value) {
if (value<0) { return -value; }
if (value==0) { return 1; }
return value;
}
public:
Shape() { setDims(1,1); }
Shape(double length, double width) {
setDims(length, width); }
void setDims(double length, double width) {
_length=straight(length); _width=straight(width); }
friend ostream &operator<<(ostream &output, Shape &S) {
output << S._length << "," << S._width; return output; }
void display() { cout << [THIS] << endl; }
};
int main(int argc, const …Run Code Online (Sandbox Code Playgroud)