Swift   发布时间:2022-04-29  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在Swift中输入IIFE的推断大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
IIFE(立即调用函数表达式)在 JavaScript中使用了很多模式.
斯威夫特也看起来像支持那样.像这样:

let one = { 1 }
/// one: () -> Int

显式类型声明和常量复原函数效果很好.

let one:Int = { $0 }(1)
/// one: Int

但恒定返回功能不能推断出自己的类型.

let one = { $0 }(1)
/// sourceKitservice
///    Terminated
///
/// Editor functionality
/// temporarily limited.

我强迫像sHell一样运行它.

// inferred.swift

#!/usr/bin/xcrun swift

var i:Int = 0
let id = { $0 }(i)

println(id)

有什么我错过或做了我有错误的styntax?

解决方法

我相信我已经看到一些东西将Swift的这个构造的实现称为“被称为闭包”,但我现在没有找到它.

请注意你的第@L_262_10@例子:

let one = { 1 }

……不是@L_262_10@叫做封闭的东西.它定义了@L_262_10@闭包,但没有调用它.因为它没有参数,所以在通过在大括号后放置@L_262_10@空参数列表来定义它的同时调用它:

let one = { 1 }()

您也可以使用类型推断来执行此操作:

let one = { $0 }(1)  // one: (int) = 1

let i = 1            // i: Int = 1
let one = { $0 }(i)  // one: (int) = 1

这些对我来说在beta 5上工作,但不是如果我用var而不是let声明. (每当你看到编译器或sourceKit崩溃时,它可能对file a bug有好处.)

调用的闭包对于设置延迟初始化的存储属性非常有用 – 第@L_262_10@针对属性的get运行闭包例如,您将在Xcode项目模板中注意到它们用于设置Core Data堆栈:

lazy var managedObjectContext: NsmanagedObjectContext? = {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that Could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    if coordinator == nil {
        return nil
    }
    var managedObjectContext = NsmanagedObjectContext()
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

在这种情况下,必须明确给出类型 – 因为闭包可以返回nil,它的返回类型必须是可选的,但类型检查器不能告诉什么类型的可选.

大佬总结

以上是大佬教程为你收集整理的在Swift中输入IIFE的推断全部内容,希望文章能够帮你解决在Swift中输入IIFE的推断所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。