Can anyone explain Swift Combine's Subject.eraseToAnySubject() method and where it should be used? - swift

I can see that Subject.eraseToAnySubject() returns the concrete Subject type AnySubject. I'm assuming this is using a type eraser pattern.
However, the apple docs provide almost no details: https://developer.apple.com/documentation/combine/passthroughsubject/3241547-erasetoanysubject
Can anyone explain how this works and where it should be used?
Also, would it be possible to use the some keyword to avoid using AnySubject?

In Combine, as you chain Publishers to Operators, the return type becomes complicated very quickly since it includes specific detail about each publisher in the chain.
For example a simple string Publisher with a filter and map Operator attached will have a return type of: <Filter<Map<Published<String, Error>>>>
eraseToAny uses a type eraser pattern to capture what's actually important about the return type. In the example given, adding an eraseToAnyPublisher will shorten the type to a more succinct <AnyPublisher<String, Error>>

Related

Why bother casting the return value since the type has been specified when calling the function?

I am learning Editor Script of Unity recently, and I come across a piece of code in Unity Manual like this:
EditorWindowTest window = (EditorWindowTest)EditorWindow.GetWindow(typeof(EditorWindowTest), true, "My Empty Window");
I don't know why bother casting the result with (EditorWindowTest) again since the type has been specified in the parameter field of GetWindow().
Thanks in advance :)
There are multiple overloads of the EditorWindow.GetWindow method.
The one used in your code snippet is one of the non-generic ones. It accepts a Type argument which it can use at runtime to create the right type of window. However, since it doesn't use generics, it's not possible to know the type of the window at compile time, so the method just returns an EditorWindow, as that's the best it can do.
You can hover over a method in your IDE to see the return type of any method for yourself.
When using one of the generic overloads of the GetWindow method, you don't need to do any manual casting, since the method already knows at compile time the exact type of the window and returns an instance of that type directly.
The generic variants should be used when possible, because it makes the code safer by removing the need for casting at runtime, which could cause exceptions.
If you closely look, GetWindow's return type is EditorWindow. Not the EditorWindowTest, so typecasting makes sense.
https://docs.unity3d.com/ScriptReference/EditorWindow.GetWindow.html

Is there a simple way to filter & narrow collections on instance type in assertj?

Can this be written as a single line?
assertThat(actualDeltas)
.filteredOn(delta -> delta instanceof Replacement)
.asInstanceOf(InstanceOfAssertFactories.list(Replacement.class))
I expected asInstanceOf to do the filtering. Alternatively, I searched for extractors or other concepts, but couldn't find any simple solution.
Is that possible with assertj?
By design, the purpose of asInstanceOf is only to provide type-narrowed assertions for cases where the type of the object under assertion is not visible at compile time.
When you provide InstanceOfAssertFactories.list(Replacement.class) as a parameter for asInstanceOf, you are telling AssertJ that you expect the object under assertion to be a List with elements of type Replacement.
While asInstanceOf will make sure that the object under test is a List, it will neither filter nor enforce that all the list elements are of type Replacement. The Replacement will ensure type-safety with subsequent methods that can be chained, for example with extracting(Function).
Currently, filteredOn(Predicate) or any other filteredOn variant is the right way to take out elements that should not be part of the assertion. If the filtering would happen outside (e.g., via Stream API), no asInstanceOf call would be needed as assertThat() could detect the proper element type based on the input declaration.

Documentation comment for loop variable in Xcode

I know that we can use
/// index variable
var i = 0
as a documentation comment for a single variable.
How can we do the same for a loop variable?
The following does not work:
var array = [0]
/// index variable
for i in array.indices {
// ...
}
or
var array = [0]
for /** index variable */ i in array.indices {
// ...
}
Background:
The reason why I don’t use "good" variable names is that I’m implementing a numerical algorithm which is derived using mathematical notation. It has in this case only single letter variable names. In order to better see the connection between the derivation and the implementation I use the same variable names.
Now I want to comment on the variables in code.
The use of /// is primarily intended for use of documenting the API of of a class, struct, etc. in Swift.
So if used before a class, func, a var/let in a class/struct, etc. you are attaching documentation to that code aspect that Xcode understands how to show inline. It doesn’t know how to pickup that information for things inside of function since at this time that is not the intention of /// (it may work for simple var/let but not likely fully on purpose).
Instead use a simple // code comment for the benefit of any those working in the code however avoid over documenting the code since good code is likely fairly self explaining to anyone versed in the language and adding unneeded documentations can get in the way of just reading the code.
This is a good reference for code documentation in Swift at this time Swift Documentation
I woud strongly push back on something like this if I saw it in a PR. i is a massively well adopted "term of art" for loop indices. Generally, if your variable declaration name needs to be commented, you need a better variable name. There are some exceptions, such as when it stores data with complicated uses/invariants that can't be captured in a better way in a type system.
I think commenting is one area that beginners get wrong, mainly from being misled by teachers or by not yet fully understanding the purpose of comments. Comments don't exist to create an english based, psuedo-programming language in which your entire app will be duplicated. Understanding the programming language is a minimal expectation out of contributors to a project. Absolutely no comments should be explaining programming language features. E.g. var x: Int = 0 // declares a new mutable variable called x, to the Int value 0, with the exception of tutorials for learning Swift.
Commenting in this manner might seem like it's helpful, because you could argue it explains things for beginners. That may be the case, but it's suffocating for all other readers. Imagine if novel had to define all the English words they used.
Instead, the goal of documentation to explain the purpose and the use of things. To answer such questions as:
Why did you implement something this way, and not another way?
What purpose does this method serve?
When will this method of my delegate be called?
Case Study: Equatable
For a good example, take a look at the documentation of Equatable
Some things to notice:
It's written for an audience of Swift developers. It uses many things, which it does not explain such as, arrays, strings, constants, variable declaration, assignment, if statements, method calls (such as Array.contains(_:)), string interpolation, the print function.
It explains the general purpose of this protocol.
It explains how to use this protocol
It explains how you can adopt this protocol for your own use
It documents contractual requirements that cannot be enforced by the type system.
Since equality between instances of Equatable types is an equivalence relation, any of your custom types that conform to Equatable must satisfy three conditions, for any values a, b, and c:
a == a is always true (Reflexivity)
a == b implies b == a (Symmetry)
a == b and b == c implies a == c (Transitivity)
It explains possible misconceptions about the protocol ("Equality is Separate From Identity")

Terminology of Optionals in Swift or other languages

In Swift the elements we manipulates all have types.
When we use theses types, we can add a '!', '?' or nothing to express their nullability.
What shall I call the '?' or '!' used to express this trait ?
A type decorator ? A decorator ? Operator ? Something else ?
What shall I call the type created when using this character ?
Is it a new type ? Is it a decorated type ? A type variation ?
The swift compiler, seems to consider them as new types, However my question is not implementation or language dependent and therefor I tagged it as language agnostic.
Edit: I'm looking for a language agnostic name. I understand with pranjalsatija's comment optionals are defined as compound type.
However, this is a language implementation detail.
I could rephrase my questions as:
What do you call a character with a special meaning when used it a type definition, and how to call the derived type.
This term should probably apply to capital casing constants in ruby as the concept is similar.
? on the end of the type isn’t a decorator or operator. It’s hardcoded syntactic sugar in Swift that allows you to shorten Optional<Thing> to Thing?.
The ? doesn’t really have a name (at least I’ve never heard anyone on the Swift team use one), in the language reference it’s just described as “the postfix ?”. The language grammar doesn’t put it in a syntactic category.
Similarly, [Thing] is shorthand for Array<Thing>, but there isn’t a name for the square brackets in this context.
Describing Option<Int> as “derived from” Int would be to misuse the term “derived”. You can if you want describe it as “Optional specialized for Int”.
In fact you may be looking for the language-agnostic term for how Swift allows you to build types (like Optional<T> or Array<T>) that apply to any kind of type T without having to care what T actually is. In which case the term would probably be generics.
! is a little different. When applied to a type name as in Thing!, it’s shorthand for ImplicitlyUnwrappedOptional<Thing>, in the same manner as ?.
! when applied to a variable of type Thing? is equivalent to a postfix operator that tests the optional and if it is nil, terminates your program, something like this:
postfix operator !<T>(value: T?) -> T {
if let unwrapped = value {
return unwrapped
}
else {
fatalError("unexpectedly found nil while unwrapping an Optional value")
}
}
so in this context, ! can be described as an operator. But not in the first context.
For the terminology a given language uses to describe optionals, see the Option type wikipedia page.
Optionals in Swift technically are completely different types, not variations of the same type. However, to a developer, they seem to be variations, so we'll treat them as such. The ? and the ! don't really have a set, specified name just yet, at least not that I know of. In a sense, you shouldn't be calling them type decorators, because optionals are really new types on their own. So to answer your question, the ? and the ! are parts of a type's name, more than anything else. And the new type created when using a ? or an ! is just that. A brand new type.
The type created using '?' is an Optional and '!' is an Implicitly Unwrapped Optional
I think the answer here may help you out, they refer to both as decorations
Here's a larger explanation about exclamation marks
And here's one for question marks

Benefit of explicitly providing the method return type or variable type in scala

This question may be very silly, but I am a little confused which is the best way to do in scala.
In scala, compiler does the type inference and assign the most closest(or may be Restrictive) type for each variable or a method.
I am new to scala, and from many sample code/ libraries, I have noticed that in many places people are not explicitly providing the types for most of the time. But, in most of the code I wrote, I was/still am explicitly providing the types. For eg:
val someVal: String = "def"
def getMeResult() : List[String]= {
val list:List[String] = List("abc","def")
list
}
The reason I started to write this especially for method return type is that, when I write a method itself, I know what it should return. So If I explicitly provide the return type, I can find out if I am making any mistakes. Also, I felt it is easier to understand what that method returns by reading the return type itself. Otherwise, I will have to check what the return type of the last statement.
So my questions/doubts are :
1. Does it take less compilation time since the compiler doesn't have to infer much? Or it doesn't matter much ?
2. What is the normal standard in the scala world?
From "Scala in Depth" chapter 4.5:
For a human reading a nontrivial method implementation, infering the
return type can be troubling. It’s best to explicitly document and
enforce return types in public APIs.
From "Programming in Scala" chapter 2:
Sometimes the Scala compiler will require you to specify the result
type of a function. If the function is recursive, for example, you
must explicitly specify the function’s result type.
It is often a good idea to indicate function result types explicitly.
Such type annotations can make the code easier to read, because the
reader need not study the function body to figure out the inferred
result type.
From "Scala in Action" chapter 2.2.3:
It’s a good practice to specify the return type for the users of the
library. If you think it’s not clear from the function what its return
type is, either try to improve the name or specify the return type.
From "Programming Scala" chapter 1:
Recursive functions are one exception where the execution scope
extends beyond the scope of the body, so the return type must be
declared.
For simple functions perhaps it’s not that important to show it
explicitly. However, sometimes the inferred type won’t be what’s
expected. Explicit return types provide useful documentation for the
reader. I recommend adding return types, especially in public APIs.
You have to provide explicit return types in the following cases:
When you explicitly call return in a method.
When a method is recursive.
When two or more methods are overloaded and one of them calls another; the calling method needs a return type annotation.
When the inferred return type would be more general than you intended, e.g., Any.
Another reason which has not yet been mentioned in the other answers is the following. You probably know that it is a good idea to program to an interface, not an implementation.
In the case of return values of functions or methods, that means that you don't want users of the function or method to know what specific implementation of some interface (or trait) the function returns - that's an implementation detail you want to hide.
If you write a method like this:
trait Example
class ExampleImpl1 extends Example { ... }
class ExampleImpl2 extends Example { ... }
def example() = new ExampleImpl1
then the return type of the method will be inferred to be ExampleImpl1 - so, it is exposing the fact that it is returning a specific implementation of trait Example. You can use an explicit return type to hide this:
def example(): Example = new ExampleImpl1
The standard rule is to use explicit types for API (in order to specify the type precisely and as a guard against refactoring) and also for implicits (especially because implicits without an explicit type may be ignored if the definition site is after the use site).
To the first question, type inference can be a significant tax, but that is balanced against the ease of both writing and reading expressions.
In the example, the type on the local list is not even a "better java." It's just visual clutter.
However, it should be easy to read the inferred type. Occasionally, I have to fire up the IDE just to tell me what is inferred.
By implication, methods should be short enough so that it's easy to scan for the result type.
Sorry for the lack of references. Maybe someone else will step forward; the topic is frequent on MLs and SO.
2. The scala style guide says
Use type inference where possible, but put clarity first, and favour explicitness in public APIs.
You should almost never annotate the type of a private field or a local variable, as their type will usually be immediately evident in their value:
private val name = "Daniel"
However, you may wish to still display the type where the assigned value has a complex or non-obvious form.
All public methods should have explicit type annotations. Type inference may break encapsulation in these cases, because it depends on internal method and class details. Without an explicit type, a change to the internals of a method or val could alter the public API of the class without warning, potentially breaking client code. Explicit type annotations can also help to improve compile times.
The twitter scala style guide says of method return types:
While Scala allows these to be omitted, such annotations provide good documentation: this is especially important for public methods. Where a method is not exposed and its return type obvious, omit them.
I think there's a broad consensus that explicit types should be used for public APIs, and shouldn't be used for most local variable declarations. When to use explicit types for "internal" methods is less clear-cut and more a matter of judgement; different organizations have different standards.
1. Type inference doesn't seem to visibly affect compilation time for the line where the inference happens (aside from a few rare cases with implicits which are basically compiler bugs) - after all, the compiler still has to check the type, which is pretty much the same calculation it would use to infer it. But if a method return type is inferred then anything using that method has to be recompiled when that method changes.
So inferring a method (or public variable) that's used in many places can slow down compilation (particularly if you're using incremental compilation). But inferring local or private variables, private methods, or public methods that are only used in one or two places, makes no (significant) difference.