Safe extraction of a value from a chain of optionals

Swift Medium optionals

Task «Safe extraction of a value from a chain of optionals»

You are given a string containing integers separated by spaces. Some numbers may be missing (replaced by '?'). Write a function that takes a string, splits it into components, converts each component into an optional Int using Int($0). If the component is '?', it should be converted to nil. Then, from the resulting array of optionals, extract and sum all values that are not nil using a compact optional chain (e.g., via compactMap and reduce). If after processing there are no numbers left, return nil. Otherwise, return the sum as an Int. Input: a single string. Output: an integer or the string "nil".

Input Format

One line containing integers and/or '?' characters separated by spaces.

Output Format

An integer (the sum of all numbers not equal to nil) or the string "nil" if there are no numbers.

Examples

Example 1

INPUT
3 ? 7 ? 2
OUTPUT
12

Example 2

INPUT
? ? ?
OUTPUT
nil

Example 3

INPUT
3 cat apple dog
OUTPUT
3
main.swift