Using enum With Integers in Swift - ios

I'd like to know how can I limit the set of values that I can pass to function as an argument (or to class as a property). Or, in other words, the logic that I want to implement, actually, is to make function or a class accept only particular values. I've come up with an idea to use enum for it. But the caveat here is that I can't use pure integers with the 'case' like so:
enum Measure {
case 1, 2, 3
}
Is there any way to implement what I want?

enum Measure:Int{
case ONE = 1
case TWO = 2
case THREE = 3
}
//accept it as argument
func myMethod(measure:Measure){
switch measure {
case .ONE:...
case .TWO:...
case .THREE
}
}
//call the method with some raw data
myMethod(Measure(rawValue:1)!)
//or call the method with
myMethod(Measure.ONE)

But why are you trying to implement it. Swift by default does not allow to pass more or fewer arguments than defined on the definition of that function or class.
So if you have a simple function which takes just one argument, then no one can pass less or more than one argument while calling your function. And if he would try to do so then the swift compiler won't allow him/her to do so.
So logically the conclusion is you don't need to develop anything like that.
If your scenario is different then what I m thinking please let me know by adding comment or writing another question in a simpler or understandable way.

Related

What does it mean <> in method?

I have this method
#override
Response<BodyType> convertResponse<BodyType, SingleItemType>(
Response response) {
final Response dynamicResponse = super.convertResponse(response);
final BodyType customBody =
_convertToCustomObject<SingleItemType>(dynamicResponse.body);
return dynamicResponse.replace<BodyType>(body: customBody);
}
What does it mean <BodyType> and <BodyType, SingleItemType> in this method?
These are called generics in Dart (in fact, they are called the same in other similar programming languages).
The main idea behind generics is that you could reuse the same code without relying on a specific data/return type. Imagine List in Dart. You could have a list of integers (List<int>), a list of strings (List<String>), a list of your custom objects (List<CustomType>) - the type is not hardcoded and it could be adjusted based on your needs.
Also, you could say that it would be easier just to use dynamic or Object types that would cover most of these cases. However, generics brings you type safety, and the method type itself becomes a parameter.
Here is the official documentation about generics.

Restricting var to result of #keyPath()

I really like an idea of using #keyPath() for safety reason. Now, I want to give my enum case an associated value with the name of some property.
My question is - are there any ways to force compilation check on associated value to give me a guarantee that this path is existed?
Though it doesn't work, what I want is something like this:
enum MissingKeysError {
case propIsMissing(checkedExistedPropertyHere: String)
}
I understand that #keyPath only returns me a string, but I really would like to use similar mechanism for my associated value.

Practical application of backticks in Swift

From this document:
To use a reserved word as an identifier, put a backtick (`) before and after it.
I'm curious about the practical application of this. When would you actually want to name something `class`, `self`, etc.?
Or, relatedly, why did the designers of Swift allow this, rather than just forbidding us from using reserved words as identifiers?
The most important usage is the interaction with other languages that have different keywords.
From Swift you can call C and Obj-C functions.
Now, consider for example that you need to call a C function called guard. However, that's a keyword in Swift, therefore you have to tell the compiler that you don't want to use it as a keyword but as an identifier, e.g.:
`guard`()
There are multiple keywords in Swift that are widely used as method/function names, e.g. get and set. For many contexts Swift is able to figure out the difference but not always.
In some cases using guard give us nice example for this purpose.In such scenario I need check self variable life time if not exist anymore (current controller deallocated) I don't want to execute rest of code.
guard let `self` = self else {
return
}

swift closure cannot override Any

Maybe it's a stupid question, but I couldn't find any solutions yet. So, my problem is, that is have an event emitter protocol with a function like this:
mutating func on(eventName:String, action:((Any?)->())) {
//..
}
And I want to use it to inform the listeners whenever an event is triggered with some information. Access token for the "login" event for example.
appSessionHadler.on("login") { (weak data: String?) in
//...
}
And than I get an error, that I cannot invoke "on" with that argument list of type. Of course it works with Any:
appSessionHadler.on("login") { (weak data: Any?) in
//...
}
Everything conforms to Any, so I'm a but confused. Can someone explain this, please!
I could solve this with a Generic protocol, but it still frustrates me that it does not works like this.
You're making a promise the compiler can't keep. The on function is free to call action with any kind of data at all. But the function you passed only accepts String. What is the system supposed to do if on includes the following code (directly or indirectly):
action(1)
1 is not a String, so type safety would be broken. The compiler can't let you do that.
Another way to think about this is that on takes a function of type F, and you are passing a supertype of F rather than a subtype of F. String is a subtype of Any. But function parameters work in the reverse order. (String)->Void is a supertype of (Any)->Void. So this is the same as passing a variable of type Any to a function that requires String. Formally we say that functions are contravariant in their parameters and covariant in their return values. You can read more on that in Type Variance in Swift.
As you suspect, generics are the right answer here. Any is almost always the wrong tool. And Any? is one of the hardest types to work with in Swift, so I'd definitely avoid that one at all costs. (Optional is itself a subtype of Any, and Swift has automatic promotion to Optional, so it is very common when you have Any? to start getting double Optionals and worse.)

Groovy method overloading

I have two domain classes on which I want a method in my service to operate. The method of the service will do very similar things to both objects and the property in those objects that it works with is in both objects with the same name. So, instead of making two methods like this:
calculateTotalBalancesInd(IndividualRecord indRec) {
//do something with indRec.accountsList
}
calculateTotalBalancesEnt(EntityRecord entRec) {
//do something with entRec.accountsList
}
is there a neat way (overloading?) to make one method that can operate on either object?
Thank you
Groovy has duck typing. Simply make your method like this:
def calculateTotalBalancesEnt(rec) {
rec.accountsList
}
Duck typing is explained here: http://www.objectpartners.com/2013/08/19/optional-typing-in-groovy/
Another approach, perhaps a bit safer:
create the above method, but make it private and call it from both the public methods you defined. This way the api remains cleaner, statically typed, but the implementation will be groovy.
In addition to duck typing per adam0404's answer, you can use switch to incorporate type specific operations. Groovy's switch statement supports dispatching on instance type.
def calculateTotalBalancesEnt(rec) {
// common operations on rec.accountsList
switch (rec) {
case IndividualRecord:
// IndividualRecord specific
break
case EntityRecord:
// EntityRecord specific
break
}
}

Resources