gpt4 book ai didi

swift 元组有意外的打印结果

转载 作者:行者123 更新时间:2023-11-28 07:18:05 25 4
gpt4 key购买 nike

playground 中的以下代码按预期工作。

let abc = 5.0
let def = 10.0
let tuple = (a: abc, d: def)
println(" tuple Parts .0 = \(tuple.0) .1 = \(tuple.1) ")
println(" tuple Parts .a = \(tuple.a) .d = \(tuple.d) ")
println(" tuple Whole = \(tuple)")

Playground 控制台输出:

tuple Parts  .0 = 5.0  .1 = 10.0 
tuple Parts .a = 5.0 .d = 10.0
tuple Whole = (5.0, 10.0)

当将该代码放入 swift 类的函数中并完成构建/运行时,控制台显示:

tuple Parts  .0 = 5.0  .1 = 10.0
tuple Parts .a = 5.0 .d = 10.0
tuple Whole = (1.28601959704862e-313, 1.28601959783912e-313)

整体 显示的数字几乎为零。正在运行 Beta 2。

我忽略了什么?
同样令人好奇的是,将 println 行放在一个循环中会为 Whole 行的每次重复打印出略微不同的 e-313 值。

更多 对于那些请求其余代码的人来说,没有太多。

一个极简、快速且肮脏的“完整代码示例”是创建一个新项目,一个 iOS 应用程序,选择单 View 应用程序。选择了 Swift 语言。

向 View Controller 添加一个 tryTuple 函数,并在 viewDidLoad 中调用该函数。

ViewController.swift 看起来像:

import UIKit

class ViewController: UIViewController {

func tryTuple (marker:String) {

println("---- \(marker)")
let abc = 5.0
let def = 10.0
let tuple = (a: abc, d: def)
println(" tuple Parts .0 = \(tuple.0) .1 = \(tuple.1) ")
println(" tuple Parts .a = \(tuple.a) .d = \(tuple.d) ")
println(" tuple Whole = \(tuple)")
}

override func viewDidLoad() {
super.viewDidLoad()
tryTuple("TryTuple1")
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

运行这个(在 XCODE 中按下 Build and Run 光标,碰巧使用的是 iPhone 4s iOS 模拟器)产生这个控制台输出。

---- TryTuple1
tuple Parts .0 = 5.0 .1 = 10.0
tuple Parts .a = 5.0 .d = 10.0
tuple Whole = (1.28543029649464e-313, 1.28543029728515e-313)

所以仍然不是我所期望的。

最佳答案

在我看来像是一个错误。你不需要把它放到一个单独的函数中;只是把这个:

    let foo = (5.0, 10.0)
println("foo: \(foo)")

...据我所知,在 iOS 项目中进入 viewDidLoad 将重现问题在 32 位模拟器上运行时。这可以解释为什么你不能在 Playground 上重现它:我猜你的 Playground 是 64 位的。如果我在 4S 模拟器上运行上面的代码,它会打印零,如果我在 5S 模拟器上运行它,它会打印预期值。

我会 file a bug如果我是你。

关于swift 元组有意外的打印结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24356081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com