使用swift编译器的奇怪行为 [英] Strange behavior with swift compiler
问题描述
我在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语句并注释第二个,那么我得到编译器错误:
'value'
为什么会发生这种情况,即使我可以在println函数调用中访问这个成员吗?
EDIT :
为了使问题更清晰,请考虑以下代码:
struct point {
pre>
var x:UInt32
var y:UInt32
init :UInt32,y:UInt32){
self.x = x
self.y = y
}
}
func f ; int {
var arr = [point(x:0,y:0)]
return arr [0] .x
}
在这种情况下,编译器错误是:
UInt32不是可转换为Int
我的问题是:为什么编译器错误是不同的,即使两个情况下的问题是一样的吗?
解决方案
value
返回UInt32
。将它转换为Int
。startIndex] .value)
或者,您可以让函数返回
UInt32
as @GoodbyeStackOverflow mentions。func f() - > UInt32
I have the following function in swift:
func f() -> Int { let a = String("a") let b = a.unicodeScalars println(b[b.startIndex].value) //return b[b.startIndex].value return 1 }
If I uncomment the first return statement and comment the second one, then I get the compiler error:
Could not find the member 'value'
Why this happens even when I have access to this member in the println function call?
EDIT:
In order to make the question more clear, consider the following code:
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 }
In this case, the compiler error is:
UInt32 is not convertible to Int
My question is: Why the compiler errors are different even when the problem is the same in both cases?
解决方案
value
returns aUInt32
. Cast it to anInt
.return Int(b[b.startIndex].value)
Alternatively, you could have the function return a
UInt32
as @GoodbyeStackOverflow mentions.func f() -> UInt32
这篇关于使用swift编译器的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!