I am studying the swift programming language.
Now I'm looking at how opaque types works.
Why does it occur error: type of expression is ambiguous without more context? (Swift 5.1)
protocol NumericExpression {
associatedtype TNumeric: Numeric
var value: TNumeric { get }
}
struct Expression {
static func sum<TA: NumericExpression, TB: NumericExpression>(_ a: TA,_ b: TB) -> some NumericExpression
where TA.TNumeric == TB.TNumeric {
return NumericExpressionSum(a: a, b: b)
}
static func multi<TA: NumericExpression, TB: NumericExpression>(_ a: TA, _ b: TB) -> some NumericExpression
where TA.TNumeric == TB.TNumeric {
return NumericExpressionMulti(a: a, b: b)
}
}
extension Int: NumericExpression {
var value: Self {
return self
}
}
struct NumericExpressionSum<TA: NumericExpression, TB: NumericExpression>: NumericExpression
where TA.TNumeric == TB.TNumeric {
let a: TA
let b: TB
var value: TA.TNumeric { a.value + b.value }
}
struct NumericExpressionMulti<TA: NumericExpression, TB: NumericExpression>: NumericExpression
where TA.TNumeric == TB.TNumeric {
let a: TA
let b: TB
var value: TA.TNumeric { a.value * b.value }
}
No compile error.
Sample code with compile error:
var s1 = Expression.sum(1, 2)
var s2 = Expression.sum(2, 3)
var m1 = Expression.multi(s1, s2)
var m2 = Expression.multi(3, 4)
print(m1.value) // 15
print(m2.value) // 12
print(type(of: m1)) // NumericExpressionMulti<NumericExpressionSum<Int, Int>, NumericExpressionSum<Int, Int>>
print(type(of: m2)) // NumericExpressionMulti<Int, Int>
print(type(of: m1).TNumeric) // Int
print(type(of: m2).TNumeric) // Int
let m3 = Expression.multi(m1, m2) //Error: type of expression is ambiguous without more context
Does this work for swift 5.5?
Thanks!