Reputation: 21
When coding in Delphi, I can use this syntax to make my code better seen:
with person do begin
setFirstName("Frodo");
setLastName("Baggins");
setAge(25);
enableRing;
sendToQuest;
end;
That would be the same of:
person.setFirstName("Frodo");
person.setLastName("Baggins");
person.setAge(25);
person.enableRing;
person.sendToQuest;
That's only for code better looking, nothing else.
Is there any equivalent of Delphi's "with .. do" syntax in swift 2?
Upvotes: 1
Views: 481
Reputation: 33
You can now use keyPaths. Although it doesn't really improve readability, it does shorten nested properties.
struct ExampleStruct {
var somePropertyOfTheExampleStruct : CGPoint
}
var aVar = ExampleStruct(somePropertyOfTheExampleStruct: .zero)
// Change some values
aVar.somePropertyOfTheExampleStruct.x = 2.0
aVar.somePropertyOfTheExampleStruct.y = 3.0
// This does the same thing
let k = \ExampleStruct.somePropertyOfTheExampleStruct
aVar[keyPath: k].x = 2.0
aVar[keyPath: k].y = 3.0
Upvotes: 0
Reputation: 79
I did manage to simulate this effect with a simple function...
func with<T>(_ element: T, _ make: (T) -> ()) {
make(element)
}
In case you do not like < make > you can replace it with < `do` > works same...
and from:
minLat = Swift.max(location.coordinate.latitude, minLat)
minLong = Swift.max(location.coordinate.longitude, minLong)
maxLat = Swift.min(location.coordinate.latitude, maxLat)
maxLong = Swift.min(location.coordinate.longitude, maxLong)
I got:
with(location.coordinate) { c in
minLat = Swift.max(c.latitude, minLat)
minLong = Swift.max(c.longitude, minLong)
maxLat = Swift.min(c.latitude, maxLat)
maxLong = Swift.min(c.longitude, maxLong)
}
It came out pretty cute...
Upvotes: 2
Reputation: 612954
Is there any equivalent of Delphi's "with .. do" syntax in Swift 2?
No there is not.
Upvotes: 1
Reputation: 630
You can use the tuple type to set multiple fields of a struct. This has much better encapsulation than the with ... do
construct, although it looks like what you are trying to do would be better handled with an instance method.
Upvotes: 0