0
votes

First of, sorry for the title name. I’m not sure how else to ask this.

In swift, we can run the following code:

func setColor(to newColor: UIcolor) {
    self.color = newColor
}
setColor(to: .blue)

In dart, the only ways I know of doing that code is:

setColor(Color newColor){
    this.color = newColor;
}
setColor(Colors.blue);

Or

setColorTo({Color newColor}){
    this.color = newColor;
}
setColorTo(newColor: Colors.blue);

To me, the swift code is much cleaner. I personally like it when the code explains what is happening. E.g setColor(to: color).

I like it when you can choose one name for the code and another for the usage.

If you are to call setColor(color), you know what it is doing but is further away from normal English. You could also do setColorTo(newColor: color) but the word ‘to’ shouldn’t be in the function. Also calling it newColor makes it more verbose as it fits with the code and when calling the function.

Is there a way to use swift like syntax in dart?

1

1 Answers

2
votes

In Dart you would usually set the variable directly rather than use a unary function starting with set. That is:

this.color = Colors.blue;

Public non-final variables are perfectly fine, you can set them directly. If you want to do something more while setting, you would use a getter and setter with a private variable:

Color get color => _color;
set color(Color newColor) {   
  logColorChange(_color, newColor); 
  _color = newColor; 
}
// and then still write:
this.color = Color.blue;

If this isn't really a setter issue, but just a general parameter naming issue, then Dart does not allow you to provide different external and internal names for the same named parameter. If you want a different name, you will have to declare it in the method:

void setColor({Color to}) {
  Color newColor = to;
  this.color = newColor;
}

I am not aware of any previous request for such a feature, perhaps because named parameters in Dart are always optional, so they are not used as much as required positional parameters to begin with, and using setFoo(to: something) feels like overhead over just setFoo(something) or setFooTo(something).

"The determined Real Programmer can write FORTRAN programs in any language."

Dart is not Swift, it is different in many obvious and subtle ways. If you try to write Swift in Dart, you will be dissapointed. I recommend trying to write idiomatic Dart instead and see how that feels after a while.