How to check for an empty Optional array of strings in Java?
Optional<String>[]
is an array of Optional<String>
elements.
You'd rather want to have optional array of strings, so you need to change paramArray
type to Optional<String[]>
.
@PostMapping("/users")
@ResponseBody
public String saveUsers(@RequestParam Optional<String[]> paramArray) {
System.out.println("param " + paramArray);
String msg = "";
int i = 0;
if (paramArray.isEmpty()) {
msg = "paramArray is empty";
} else {
for (String paramArrayItem : paramArray.get()) {
msg += "param[" + i + "]" + paramArrayItem + "\n";
i++;
}
}
return msg;
}
Determine if Any.Type is Optional
Assuming that what you are trying to do is something like this:
let anyType: Any.Type = Optional<String>.self
anyType is Optional<Any>.Type // false
Sadly swift currently (as of Swift 2) does not support covariance nor contravariance and type checks directly against Optional.Type
cannot be done:
// Argument for generic parameter 'Wrapped' could not be inferred
anyType is Optional.Type // Causes error
An alternative is to make Optional
extend an specific protocol, and check for that type:
protocol OptionalProtocol {}
extension Optional : OptionalProtocol {}
let anyType: Any.Type = Optional<String>.self
anyType is OptionalProtocol.Type // true
How to tell Typescript that an item of an optional array cannot be undefined when passed as a function parameter
Type type of subfields is:
{ id: string }[] | undefined
The problem is that it is a union with undefined
. But you can use the Exclude
utility type to remove possibilities from a union.
For example:
type AB = 'a' | 'b'
type A = Exclude<AB, 'b'> // 'a'
Also, in general, you should get the type of an array by indexing it with number
, since that's the type that array's are indexed by.
So putting that together in your case:
const myFunc = (param: Exclude<T["node"]["subfields"], undefined>[number]) => {
//...
}
myFunc({ id: 'def' })
myFunc(undefined) // type error, as expected.
Or as @LindaPaiste points out NonNullable<T["node"]["subfields"]>
should work nicely as well.
Playground
However, rather than slicing off pieces of a large and complex type, it's often cleaner to make lots of small types and then assemble them together.
This may not be an option if importing from a library, but if the library's types are implemented in with this strategy, there may be a better type to import for your code.
For example:
interface Subfield {
id: string
}
// Not used in this example, but used in other parts of the application.
type T = {
node: {
id: string;
subfields?: ReadonlyArray<Subfield>;
};
}
// Now this is dead simple:
const myFunc = (param: Subfield) => {
//...
}
Playground
Why are elements of Array in this case optional?
I'm pretty sure that the first element of this array is not nil
Yes but it's implementation doesn't know that , it's written also in case no values exist so optional comes to rescue
extension Array {
@inlinable public var first: Element? { get }
}
Related Topics
How to Create a Cocoapod with .Swift
Is There Any Difference at All Between Suffix(From:) and Dropfirst(_:)
Swift 2 Mkmapviewdelegate Rendererforoverlay Compiler Warning
Which Optimization Level Should I Choose for Release
How to Call Completionhandler for Performfetchwithcompletionhandler in Swift
Performseguewithidentifier Not Working If Called from Viewdidload
Issues Scaling Sprite Width to Screen Width
Count Number of Instances of a Class Swift
How to Add a Menu to The Application in The Dock
Sknode Subclass Generates Error: Cannot Invoke Initializer for Type "X" with No Arguments
Why I Can Not Use Setvalue for Dictionary
How to Solve This Error: Thread 1: Exc_Resource Resource_Type_Memory (Limit=650 Mb, Unused=0X0)
Filtering Realm Objects with Swift
What Is The Default Value of The Padding Modifier in Swift
How to Get Textfields from Static Cells in UItableviewcontroller? Swift