Skip to content

Commit 61b7b3b

Browse files
authored
Merge pull request #28626 from xedin/rdar-57668763
[ConstraintSystem] Fix a case of too eager force optional unwrap with…
2 parents 81071c0 + 08baf67 commit 61b7b3b

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

lib/Sema/CSSimplify.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2660,6 +2660,17 @@ repairViaOptionalUnwrap(ConstraintSystem &cs, Type fromType, Type toType,
26602660
if (fromUnwraps <= toUnwraps && !fromObjectType->is<TypeVariableType>())
26612661
return false;
26622662

2663+
// If the result of optional chaining is converted to
2664+
// an optional contextual type represented by a type
2665+
// variable e.g. `T?`, there can be no optional mismatch
2666+
// because `T` could be bound to an optional of any depth.
2667+
if (isa<OptionalEvaluationExpr>(anchor) && toUnwraps > 0) {
2668+
auto last = locator.last();
2669+
if (last && last->is<LocatorPathElt::ContextualType>() &&
2670+
toObjectType->is<TypeVariableType>())
2671+
return false;
2672+
}
2673+
26632674
auto result =
26642675
cs.matchTypes(fromObjectType, toObjectType, matchKind,
26652676
ConstraintSystem::TypeMatchFlags::TMF_ApplyingFix, locator);

test/Constraints/optional.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,3 +402,21 @@ func sr_11104() {
402402
bar(["hello"].first)
403403
// expected-error@-1 {{cannot convert value of type 'String?' to expected argument type 'Int'}}
404404
}
405+
406+
// rdar://problem/57668873 - Too eager force optional unwrap fix
407+
408+
@objc class Window {}
409+
410+
@objc protocol WindowDelegate {
411+
@objc optional var window: Window? { get set }
412+
}
413+
414+
func test_force_unwrap_not_being_too_eager() {
415+
struct WindowContainer {
416+
unowned(unsafe) var delegate: WindowDelegate? = nil
417+
}
418+
419+
let obj: WindowContainer = WindowContainer()
420+
if let _ = obj.delegate?.window { // Ok
421+
}
422+
}

0 commit comments

Comments
 (0)