Missing declaration with default argument - swift

Is this code wrong, or is this a known issue?
final class Foo {
//#inlinable #inline(_always)
static func bar(_ first: String = "default", _ second: Int) {
print(first,second)
}
}
Foo.bar(2)
Will result:

I don’t find this surprising in the way that some of the comments do. Arguments must always be supplied in order. In the total absence of labels, the only valid way to do that is to supply the first argument or both. Supplying a single argument thus means you need to supply a string. The default value doesn’t change any of that.
The error message is unhelpful as usual, and other languages may behave differently, but that doesn’t constitute a bug. If there’s anything to complain of, it’s that the compiler should have warned against the original method declaration, as the default value for the first parameter is otiose.

I would not say it is a bug more likely it is a feature. This code smells really bad codestyle...
You don't specify the names for the parameter which can lead to really bad things and assigning Int to String... I wouldn't be surprised
Now I don't wanna "educate" you how to write nice code, but the example you posted above really is not. It is just not very intuitive to write functions without label, this is perfect example why we should be using labels... Writing functions as suggested by Swift community works just awesome...
final class Foo {
//#inlinable #inline(_always)
static func bar(first: String = "default", second: Int) {
print(first,second)
}
}
Foo.bar(second: 2)
Why not just omit the underscores? :)

Related

Swift generics: How to represent 'no type'?

I am using Google's promises library, and I would like to create promise without any type (because I don't need any).
However, I am being forced to pick some type:
let promise = Promise<SomeType>.pending()
Is there a type I could pass in place of SomeType that would essentialy mean 'no type', when I need promises just for async flow and exception catching, but I don't want to return a specific value from a function?
For example, some type whose only valid value is nil?
I have encountered this problem in multiple places, the only workaround I found so far is to always provide a non-generic alternative, but it gets really tedious and leads to duplicate code.
Types are sets of values, like Int is the set of all integer numbers, String is the set of all sequences of characters and so on.
If you consider the number of items in the set, there are some special types with 0 items and 1 items exactly, and are useful in special cases like this.
Never is the type with no values in it. No instance of a Never type can be constructed because there are no values that it can be (just like an enum with no cases). That is useful to mark situations, code flow etc as 'can't happen', for example the compiler can know that a function that returns Never, can never return. Or that a function that takes Never can never be called. A function that returns Result<Int, Never> will never fail, but is in the world of functions returning Result types. But because never can't be constructed it isn't what you want here. It would mean a Promise that can't be fulfilled.
Void is the type with exactly 1 value. It's normally spelled () on the left and Void on the right, of a function definition. The value of a void is not interesting. It's useful to make a function that returns Void because those are like what other languages call subroutines or procedures. In this case it means a Promise that can be fulfilled but not with any value. It can only be useful for its side effects, therefore.
Is it a correct solution or a workaround if we create an empty class
class Default_Class : Codable {
}
and use this as Promise<Default_Class>.pending

how to extend optional chaining for all types

If we have optional values foo and bar, Swift will allow us to write:
foo?.doSomething(bar)
Which will evaluate to nil if foo is nil. But it will not let us write:
foo?.doSomething(bar?)
That is, optional chaining only works on the arguments outside a function call, not inside the argument list. (The reasons for this limitation are unclear, but here we are.)
Suppose I want to write an apply function that lets me move things into the jurisidiction of optional chaining, like so:
bar?.apply { foo?.doSomething($0) }
Here, apply is a generic function that takes one argument (in this case bar) and then executes the closure. So if either foo or bar is nil, the expression will be nil.
Here's what I’ve tried:
public protocol HasApply {}
extension HasApply {
public func apply<T>(_ f : (Self) -> T) -> T {
f(self)
}
}
That’s fine as far as it goes. But to make it work, I still have to explicitly apply the protocol to the types I care about:
extension Int : HasApply {}
OK, that makes it work with Int. But I don’t want to copy & paste for every type. So I try this:
extension AnyObject : HasApply {}
No, that won’t work: the error is Non-nominal type 'AnyObject' cannot be extended.
Hence the question: is there no way to make this generic function work as a protocol method?
is there no way to make this generic function work as a protocol method?
No, you must "explicitly apply the protocol to the types I care about".
However, you are in fact reinventing the wheel. This is the use case of flatMap/map. If both foo and bar are optional, you can write:
bar.flatMap { foo?.doSomething($0) }
Note the lack of ? after bar. You are calling flatMap on Optional, rather than bar's type. If doSomething returns T, the above expression will return T?.
If only bar is optional, use map:
bar.map { foo.doSomething($0) }
As Sweeper pointed out, the language already provides you the tool for this, in the form of the map/flatMap functions.
But you could also write
if let foo = foo, let bar = bar {
foo.doSomething(bar)
}
This is an easier to read, understand, and maintain code, with clearly transmits the intent: you want doSomething to be called if both the receiver of the call and its argument are non-nil.
Now, why it would not be a good idea for the language to have this feature built-in - it's due to the way the compiler processes the code: from left to right.
The optional chaining is a short-circuit operator, thus
foo?.someExpensiveComputation().doSomething(bar)
will stop at runtime as soon as it detects that foo is nil. Which means that someExpensiveComputation will not be executed. Not the same thing can be said about a construct like this:
foo?.someExpensiveComputation().doSomething(bar?)
Assuming foo is not nil, but bar is nil, the program will execute someExpensiveComputation just to find out that doSomething doesn't need execution. Thus, the short-circuit no longer applies.
Let's take another example, let's assume doSomething has two parameters:
foo?.doSomething(someExpensiveComputation(), bar)
Again, the compiler evaluates from left to right, thus the expensive computation will be performed, just to be thrown away once the program detects at runtime that the second argument is nil.
Now, yes, the compiler might implement some advanced heuristics of looking ahead for possible nil values, but this would be highly complicated and would add lots of performance penalties at runtime.
The bottom line, the compiler will provide you with short-circuits, as long as those are well-behaved, predictable, and don't overwhelm the compiler.

Passing the calling object as a parameter in a chained method in Swift

Not sure if the title makes sense or not. I've been searching for an answer for a while, and having trouble putting into words what I am looking for.
When you call certain built in methods on a String in Swift you would do something like this.
someString.lowerCased()
How does the lowerCased() method get someString as it's parameter to modify?
Basically, I am writing an extension for the String type that checks certain things about the string and throws an error if certain conditions aren't met. So I would like to just be able to write
someString.checkString()
But instead, right now, I am having to write it as
someString.checkString(stringToCheck: someString)
I swear I remember reading something about this a long time ago, but can't remember anything about it now.
Use self. Useless but to the point example:
extension String {
func checkString(ifLongerThan number: Int) -> Bool {
return self.characters.count > number
}
}

I can't figure out how this switch statement is working?

func performMathAverage (mathFunc: String) -> ([Int]) -> Double {
switch mathFunc {
case "mean":
return mean
case "median":
return median
default:
return mode
}
}
I got this example from a swift learning book and its speaking of the topic of returning function types and this is just a part of the whole program I didn't want to copy and paste it all. My confusion is that the book says:
"Notice in performMathAverage , inside the switch cases, we return
either mean , median , or mode , and not mean() , median() , or mode()
. This is because we are not calling the methods, rather we are
returning a reference to it, much like function pointers in C. When
the function is actually called to get a value you add the parentheses
suffixed to the function name. Notice, too, that any of the average
functions could be called independently without the use of the
performMathAverage function. This is because mean , median , and mode
are called global functions ."
The main question is: "Why are we not calling the methods?"
and what do they mean we are returning a reference to it??
What do they mean by reference? Im just confused on this part.
You stated your main question as:
"Why are we not calling the methods?" and what do they mean we are returning a reference to it??
This is a little tricky to grasp at first, but what it's saying is that we don't want the result of the function, we want the function itself.
Sometimes things like this are easier to understand w/ a type alias:
Starting w/ [Int] -> Int, what we're saying there is "a function that takes an array of Ints and returns a single Int"
Let's make a type alias for clarity:
typealias AverageFunction = [Int] -> Int
Now our function (from your example) looks like this:
func performMathAverage(mathFunc: String) -> AverageFunction {
Although, the naming conventions here are pretty confusing since we're not performing anything, instead let's call it like this:
func getAverageFunctionWithIdentifier(identifier: String) -> AverageFunction {
Now it's very clear that this method is functioning like a factory that returns us an average function based on the identifier we provide. Now let's look at the implementation:
func getAverageFunctionWithIdentifier(identifier: String) -> AverageFunction {
switch identifier {
case "mean":
return mean
case "median":
return median
default:
return mode
}
}
So now, we're running a switch on the identifier to find the corresponding function. Again, we're not calling the function because we don't want the value, we want the function itself. Let's look at how we would call this:
let averageFunction = getAverageFunctionWithIdentifier("mean")
Now, averageFunction is a reference to the mean function which means we can use it to get the mean on an array of integers:
let mean = averageFunction([1,2,3,4,5])
But what if we wanted to use a different type of average, say median? We wouldn't have to change anything except for the identifier:
let averageFunction = getAverageFunctionWithIdentifier("median")
let median = averageFunction([1,2,3,4,5])
This example is pretty contrived, but the benefits of this is that by abstracting a function out to it's type (in this case [Int] -> Int, we can use any function that conforms to that type interchangeably.
This is functional programming!
This has to do with the functional programming aspects of swift. Here functions are treated like first class citizens meaning you can treat them like variables.
Why are we not calling the methods?
You are not calling the methods, because you have no argument to apply. The point of the function is to determine which function you would like to use. Of course the name of the function is terrible and does not accurately represent what the function does. It should be more like func determineMathFuncToUse, then you could use it like
var myFunc = determineMathFuncToUse("median")
// Now, you would be able to use myFunc just like you would use median
// e.g. myFunc(some_array) == median(some_array)
This is pretty easy to understand. In Swift you can store references to functions (the closest you can achieve in Objective-C is the reference to block).
func performMathAverage (mathFunc: String) -> ([Int]) -> Double
This is the function whose return type is:
([Int]) -> Double
As you can see the return type of this function is a function which accepts an array of Int and returns Double.
And in code you see that it returns one of three functions: mean, mode, and median. Each of these functions accepts an array of Int and returns Double.
Due to this code below:
let meanFunc = performMathAverage("mean")
let mean = meanFunc(someIntArray)
is identical to:
let mean = mean(someIntArray)
I hope this helps.
The reason why functions are NOT executed in code is because this example illustrates how you can STORE reference to functions.
It might be difficult to understand why you would want to do it in this particular case, but, hey, printing "Hello world" also seems meaningless :)
You are referring to an example in a tutorial so it is not strange that they are oversimplifying things. However, believe me, that in a real world there are many cases in which storing references to functions is very-very useful!
One obvious example is when you want to store reference to some completion handler which you want to execute at the end of some lengthy operation. And which can be different depending on the context from which you initiated this operation.
To answer your question, you are effectively returning the function itself, and not the result of calling that function. In this case, it lets you choose a function (using the switch statement) and evaluate it later. A helpful way to think about it is that functions are also a type of variable, and you can pass them around as well as evaluate them.
As a general stylistic thing, it's good practice to end each case with a break. It makes no difference here because return will also end the execution of the function, but without a break, all code after the correct case will be executed, not just the code within the correct case. Running into another case statement doesn't break out of the switch statement by itself.
Why are we not calling the methods?
Presumably, the method will be called later. The purpose of the switch statement is to return a function that can be used later.
What do they mean we are returning a reference to it? ... What do they mean by reference?
The "reference" language is a bit confusing - functions are reference types, but that isn't super important to what is going on. You can think of it as just returning a function.
The bottom line is that functions in swift can be used like any other type - they can be stored in variable or constants, they can be passed into a function as a parameter, and they can be returned from a function.
In this case, you have a function that is designed to return a function. If you want to obtain the mean, you pass the string "mean" and the function will return a new function that will obtain the mean when you call it.

Create and run a Selector with several parameters for class functions

I have a situation where I use a class to do a number of conversions with a large number of rules which have the general form of:
private class func rule0(inout account: String, _ version: Int) -> String? {
return nil; // Use default rule.
}
The function names just increase the rule number: rule1, rule2 etc...
I get the rule number from an external source and now want to find a generic way to call the right rule function depending on the given rule number. I could use a big switch statement, but I'm more interested in generating a selector from a string and call that.
My attempts led me to:
let ruleFunction = Selector("rule\(rule):_:");
let result = ruleFunction(&account, version);
but that only causes this error on the second line:
'(inout String, #lvalue Int) -> $T4' is not identical to 'Selector'
What is the right way to accomplish that? And btw, what means "$T4"? That error message is hard to understand, to say it friendly.
Additional note: I'm aware of approaches using a timer or detouring to Obj-C, but am rather interested in a direct and pure Swift solution. How is the Selector class to be used? Can it be used to directly call what it stands for? How do classes like NSTimer use it (detour to Obj-C?)?
A couple of approaches that don't use Selector. If all of the "rules" have the same signature, then you could either put them in an array, with the index of the function in the array indicating the rule number, like this:
let functionArray = [rule0, rule1, rule2, rule3] // etc...
Then, when it is time to call the function, you just access the one you want with a subscript:
let result = functionArray[ruleNumber](account, version)
You could do the same thing with a dictionary that looked something like this:
let functionDict = ["rule0": rule0, "rule1": rule1] // etc...
And then get the function using the string value that you create when you get the rule number from your external source:
let result = functionDict["rule\(ruleNumber)"]?(account, version)
The dictionary approach would work better if you weren't able to guarantee that rule0 would always be at index 0 in the array.
A caution, though: I have tried this and I've been able to get it to work without the inout keyword, but not with it. I don't know if it is a bug, or what, but Swift doesn't seem to want to let me create arrays or dictionaries of functions that take inout parameters.
If you absolutely require the inout parameter for your function to work, then my suggestion won't help. If there is a way to do what you want without the inout, then this might be the solution for you.