1

Let's say I have some variable with type

let someVariable: SomeType<AnotherType?>

and I am sure that this concrete instance not contain any nil of AnotherType?. Is there is general way to convert it to SomeType<AnotherType>? For example, I need this convert for use someVariable in some function.

Yury
  • 6,044
  • 3
  • 19
  • 41
  • 1
    Possible duplicate of http://stackoverflow.com/questions/34563161/how-can-i-write-a-function-that-will-unwrap-a-generic-property-in-swift-assuming – Benjamin Lowry Sep 27 '16 at 07:42
  • @BenjaminLowry disagree. Question that you link is about `SequenceType` and about removing `nil` cases. In my question there is no `nil` cases and general type. – Yury Sep 27 '16 at 07:55
  • 2
    `SomeType` and `SomeType` are different and unrelated types. Without concrete information (such as how an instance of SomeType can be created) this might be difficult to answer. – Martin R Sep 27 '16 at 07:59
  • And what does it mean that *"that this concrete instance not contain any nil of AnotherType?"* ? From the given declaration it is not clear if `AnotherType?` is the type of some property in `SomeType`. – Martin R Sep 27 '16 at 08:14
  • @MartinR I trying to imagine general case, when I don't know much about `SomeType`. Your tips was helpful, thank you – Yury Sep 27 '16 at 09:08

1 Answers1

0

It could go along these lines:

protocol _Optional {
    associatedtype _Wrapped
    func unveil() -> _Wrapped?
}

extension Optional: _Optional {
    typealias _Wrapped = Wrapped
    func unveil() -> _Wrapped? { return self }
}

extension SomeType where T: _Optional {
    func rewrap() -> SomeType<T._Wrapped>? {
        guard let _value = value.unveil() else { return nil }
        return SomeType<T._Wrapped>(value: _value)
    }
}

struct SomeType<T> {
    let value: T
}

let someValue = SomeType<Int?>(value: 42)       // SomeType<Int?>
let rewrappedValue = someValue.rewrap()         // SomeType<Int>?
let forceUnwrappedValue = someValue.rewrap()!   // SomeType<Int>

Specifics depend on details of the particular implementation for SomeType (I use a simplest assumption in my example).

0x416e746f6e
  • 9,872
  • 5
  • 40
  • 68