我正在使我的代码正常运行,除了警告是在编译时发出的事实之外,因为我自己学习,所以我真的不知道这些警告来自何处。如何修改代码(介于FIXME BEGIN和FIXME END之间)以使代码在没有警告的情况下进行编译?
代码:
protocol EqualsMethod {
// Notice that the type-keyword "Self" helps to solve the
// curriously recurring interface pattern for direct self-reference
// FIXME-begin
func equality(my: Self) -> Bool;
// FIXME-end
}
struct my_int : EqualsMethod {
// FIXME-begin
func equality(my: my_int) -> Bool{
if (my.value == value){
return true;
}
return false
}
// FIXME-end
var value: Int;
}
// Returns the index of an element if it exists
// nil otherwise
func findIndex
// FIXME-begin
<T: EqualsMethod>
// FIXME-end
(valueToFind: T, array:[T]) -> Int? {
// FIXME-begin
for (k, e) in array.enumerated(){
if (valueToFind.equality(my: e))
{
return k;
}
}
// FIXME-end
// Index not found
return nil
}
let ints = [my_int(value: 1),
my_int(value: 2),
my_int(value: 3),
my_int(value: 4),
my_int(value: 5)]
print(findIndex(valueToFind: my_int(value: 2), array: ints))
print(findIndex(valueToFind: my_int(value: 0), array: ints))
预期输出:
Optional(1)
nil
警告:
main.swift:49:7: warning: expression implicitly coerced from 'Int?' to 'Any'
print(findIndex(valueToFind: my_int(value: 2), array: ints))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.swift:49:7: note: provide a default value to avoid this warning
print(findIndex(valueToFind: my_int(value: 2), array: ints))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?? <#default value#>
main.swift:49:7: note: force-unwrap the value to avoid this warning
print(findIndex(valueToFind: my_int(value: 2), array: ints))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!
main.swift:49:7: note: explicitly cast to 'Any' with 'as Any' to silence this warning
print(findIndex(valueToFind: my_int(value: 2), array: ints))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
as Any
main.swift:50:7: warning: expression implicitly coerced from 'Int?' to 'Any'
print(findIndex(valueToFind: my_int(value: 0), array: ints))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.swift:50:7: note: provide a default value to avoid this warning
print(findIndex(valueToFind: my_int(value: 0), array: ints))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?? <#default value#>
main.swift:50:7: note: force-unwrap the value to avoid this warning
print(findIndex(valueToFind: my_int(value: 0), array: ints))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!
main.swift:50:7: note: explicitly cast to 'Any' with 'as Any' to silence this warning
print(findIndex(valueToFind: my_int(value: 0), array: ints))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
as Any
最佳答案
findIndex()
返回Int?
,然后print()
将其强制为Any
。
从警告开始,应用建议的修复程序之一:
print(findIndex(valueToFind: my_int(value: 2), array: ints) ?? -1) // one option
print(findIndex(valueToFind: my_int(value: 2), array: ints)!) // another option, may crash
print(findIndex(valueToFind: my_int(value: 2), array: ints) as Any) // third option