我在 swift 中有以下功能:
func f() -> Int
{
let a = String("a")
let b = a.unicodeScalars
println(b[b.startIndex].value)
//return b[b.startIndex].value
return 1
}
如果我取消注释第一个 return 语句并注释第二个,则会出现编译器错误:
Could not find the member 'value'
为什么即使我在 println 函数调用中有权访问该成员,也会发生这种情况?
编辑:
为了使问题更清楚,考虑以下代码:
struct point {
var x: UInt32
var y: UInt32
init (x: UInt32, y: UInt32) {
self.x = x
self.y = y
}
}
func f () -> Int {
var arr = [point(x: 0, y: 0)]
return arr[0].x
}
在这种情况下,编译器错误是:
UInt32 is not convertible to Int
我的问题是:为什么即使两种情况下的问题相同,编译器错误也会不同?
最佳答案
value
返回一个 UInt32
。将其转换为 Int
。
return Int(b[b.startIndex].value)
或者,您可以让函数返回一个 UInt32
,正如@GoodbyeStackOverflow 提到的那样。
func f() -> UInt32
关于swift - 快速编译器的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30334653/