gpt4 book ai didi

swift - 如何在 Swift 中声明一个元组并为其成员之一提供运行时函数

转载 作者:行者123 更新时间:2023-11-30 13:05:53 26 4
gpt4 key购买 nike

在 Swift 中是否有可能以及如何使元组的成员成为函数而不是数据值,类似于 JavaScript?如:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

示例(伪代码):


(标题:func get {
返回 the_title_i_want_to_choos_at_runtime ()
})

最佳答案

当然,因为函数是 Swift 中的一流对象。

import Foundation

typealias LazyEvalTuple = ( timeSince1970: (Void -> NSTimeInterval), now: (Void -> String) )

let lazyTup = LazyEvalTuple ( { return NSDate().timeIntervalSince1970 }, { return "\(NSDate())" } )

print(lazyTup.timeSince1970())
print(lazyTup.now())

// Do it again and observe different results, proving dynamic evaluation
print(lazyTup.timeSince1970())
print(lazyTup.now())

print(lazyTup.1)
print(lazyTup.0)

输出:

1473288631.22304
2016-09-07 22:50:31 +0000
1473288631.22619
2016-09-07 22:50:31 +0000
(Function)
(Function)

关于swift - 如何在 Swift 中声明一个元组并为其成员之一提供运行时函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39380026/

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