在 Xcode 中的 .Swift 文件之间传递数据 [英] Passing Data Between .Swift Files in Xcode

查看:29
本文介绍了在 Xcode 中的 .Swift 文件之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 swift 的新手,我在 Xcode 7 Beta 中有一个项目,我有扩展文件等.我的项目中有 3 个 .swift 文件(不是用于视图控制器),我想定义一个变量或在其中一个中保持不变,并在整个项目中访问它.例如在 First.swift 中定义一个 var,并在 Second 或 Third.swift 文件中访问它.我知道 Xcode 中的 NSUserDefaults,但我不想使用它.我也知道如何在视图控制器之间传递数据(使用 prepareforsegue 等)但我想在 .swift 文件之间传递数据.

i'm new to swift, i have a project in Xcode 7 Beta, and i have extension files and etc. i have 3 .swift files (not for view controllers) in my project, and i want to define a variable or constant in one of them and access that , all over the project. for example define a var in First.swift , and access to that in Second or Third.swift files. i know about NSUserDefaults in Xcode, but i don't want to use that. Also i know that how i can pass data between viewcontrollers (using prepareforsegue and etc.) but i want to pass data between .swift files.

推荐答案

一种方法是你可以将它们封装在 struct 中并且可以在任何地方访问.

One way to do it is you can encapsulate them in struct and can access anywhere.

你也可以在swift中定义静态变量或常量.封装在struct

You can define static variables or constant in swift also.Encapsulate in struct

struct MyVariables {
    static var yourVariable = "someString"
}

你可以在任何类或任何地方使用这个变量:

You can use this variable in any class or anywhere:

let string = MyVariables.yourVariable
println("Global variable:\(string)")

//Changing value of it
MyVariables.yourVariable = "anotherString"

或者您可以声明可以在任何地方访问的全局变量.

Or you can declare global variables which you can access anywhere.

参考来自这里.

这篇关于在 Xcode 中的 .Swift 文件之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆