swift - 快速编译器的奇怪行为

标签 swift compiler-errors

我在 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/

相关文章:

ios - 如何防止用户名在 Firebase 中重复注册?

swift - 在 Swift 中获取带有字符串的枚举

macos - OS X 10.8 上的 CMAKE、Clang 和 C++v11

compiler-construction - 我有一种语言需要确定我的流控制语句谓词是重言式还是矛盾

c - GTK+ 海湾合作委员会 : undefined reference to all gtk functions when linking

objective-c - 模拟 CoreMotion iOS 模拟器

ios - swift Balloons.playground 无法打开

c++ - g++坏了?无法向类添加新方法

ios - 视觉布局约束对应的代码是什么?

c++ - #define 的 "Declaration does not declare anything"错误