How to Turn an Array of Nullable Items into a Nullable Array Based on Whether Any of the Items Are Null

How do I turn an array of nullable items into a nullable array based on whether any of the items are null?

Here's how I would write it:

let source = [1, 2, nil] as [Int?]
var result : [Int]? = {
for i in source {
if i == nil {
return nil
}
}
return source.map {$0!}
}()

But that doesn't really meet your "inefficient" consideration. Someone has to look through the array to see if it contains nil, so nothing is lost by looping and doing that; but the inefficiency is that we loop twice, because map is a loop. If you really hate that, here's a way out:

var result : [Int]? = {
var temp = [Int]()
for i in source {
if let i = i {
temp.append(i)
} else {
return nil
}
}
return temp
}()

Lots of very idiomatic Swifties in those formulations, I think!

Why does this produce a nullable array / How to create non-nullable array

While the type is int[]?, you won't get warnings if you try to access it. The language design team decided to always treat var as nullable reference type, and rely on DFA (DataFlow Analysis) for when to produce warnings. This isn't specific to arrays. See dotnet/csharplang#3662 for detailed discussion.

Also, from var keyword docs:

When var is used with nullable reference types enabled, it always implies a nullable reference type even if the expression type isn't nullable.

Nullable reference types on object array

This answer is just for completeness, so that the answer is not only in the comments

The problem is not with the declaration of your method and it's parameters, but instead with the call. You are creating an array of non-nullable objects and initializing it with one null. You should instead create an array of nullable objects like this: new object?[] { null }

To answer your confusion with the method declarations:

The nullability operator always referes to the previous type.

So in object[]? the nullability operator applies only to the array. This means that null and an array of non-nullable objects would fit this type.

When you write object?[], the nullability operator applies only to object. This means that a non-nullable array of nullable objects matches this type.

How to convert an int array to a nullable int array?

Another aproach by using Array.ConvertAll method

var values = new[] {1, 2, 3, 4};
var nullableValues = Array.ConvertAll(ints, value => new int?(value));

Or with providing generic types explicitly

var nullableValues = Array.ConvertAll<int, int?>(ints, value => value);

Create Array without nullable types from Array with nullable types

array.requireNoNulls() returns same array Array<T?> with non-optional type Array<T> (But throws IllegalArgmentException if any of the item found null).

if you are sure that your array doesn't have null then you can typecast.

array as Array<String>

nullable array of nullable values in nestjs code first graphql

You need to set @Field(() => [String], { nullable: 'itemsAndList' }) as described in the docs

When the field is an array, we must manually indicate the array type in the Field() decorator's type function, as shown below:

@Field(type => [Post])
posts: Post[];

Hint
Using array bracket notation ([ ]), we can indicate the depth of the array. For example, using [[Int]] would represent an integer matrix.

To declare that an array's items (not the array itself) are nullable, set the nullable property to 'items' as shown below:

@Field(type => [Post], { nullable: 'items' })
posts: Post[];`

If both the array and its items are nullable, set nullable to 'itemsAndList' instead.

Convert array from nullable type to non-nullable of same type?

To convert an array of one type to an array of another type, use the Array.ConvertAll method:

byte?[] data = { 1, 0, 18, 22, 255 };
byte[] result = Array.ConvertAll(data, x => x ?? 0);

This is simpler, easier, and faster than using LINQ.

How can I persist an array of a nullable value in Protobuf-Net?

using ProtoBuf;
using ProtoBuf.Meta;
using System;
[ProtoContract]
class Foo
{
[ProtoMember(1)]
public double?[] Values { get; set; }
}
static class Program
{
static void Main()
{
// configure the model; SupportNull is not currently available
// on the attributes, so need to tweak the model a little
RuntimeTypeModel.Default.Add(typeof(Foo), true)[1].SupportNull = true;

// invent some data, then clone it (serialize+deserialize)
var obj = new Foo { Values = new double?[] {1,null, 2.5, null, 3}};
var clone = Serializer.DeepClone(obj);

// check we got all the values back
foreach (var value in clone.Values)
{
Console.WriteLine(value);
}
}
}


Related Topics



Leave a reply



Submit