Posts

Showing posts with the label optional

Return null or new object using Optional object fields

Image
Clash Royale CLAN TAG #URR8PPP Return null or new object using Optional object fields We have a method, wherein we receive an Optional<SomeType> object. If the contained SomeType object is not null then we have to initialize a SomeOtherType object using the fields of the SomeType object and return that new object; otherwise we have to return null Optional<SomeType> SomeType SomeOtherType SomeType We found multiple different solutions where we perform this task with two statements, first retrieving the optional object and then second creating the other type object e.g. private SomeOtherType ourMethod() { SomeType someObject = getOptionalSomeTypeFromSomeWhere().orElse(null); return someObject != null ? new SomeOtherType(someObject.getField1(), someObject.getField2(), ...) : null; } Is it possible to cover this with one statement? So far we could not figure to do the null checks, accessing the fields, new object creation etc. all in one Basically a more complex case of...

Function throws AND returns optional.. possible to conditionally unwrap in one line?

Image
Clash Royale CLAN TAG #URR8PPP Function throws AND returns optional.. possible to conditionally unwrap in one line? I am using an SQLite library in which queries return optional values as well as can throw errors. I would like to conditionally unwrap the value, or receive nil if it returns an error. I'm not totally sure how to word this, this code will explain, this is what it looks like: func getSomething() throws -> Value? { //example function from library, returns optional or throws errors } func myFunctionToGetSpecificDate() -> Date? { if let specificValue = db!.getSomething() { let returnedValue = specificValue! // it says I need to force unwrap specificValue, // shouldn't it be unwrapped already? let specificDate = Date.init(timeIntervalSinceReferenceDate: TimeInterval(returnedValue)) return time } else { return nil } } Is there a way to avoid having to force unwrap there? Prior to updating to Swi...