在我的Objective-C项目中,我经常使用全局常量文件来存储NSUserDefaults
的通知名称和键等内容。它看起来像这样:
@interface GlobalConstants : NSObject
extern NSString *someNotification;
@end
@implementation GlobalConstants
NSString *someNotification = @"aaaaNotification";
@end
我如何在Swift中做同样的事情?
答案 0 :(得分:715)
IMO处理这类常量的最佳方法是创建一个Struct。
struct Constants {
static let someNotification = "TEST"
}
然后,例如,在您的代码中调用它:
print(Constants.someNotification)
编辑:如果你想要一个更好的组织,我建议你使用分段子结构
struct K {
struct NotificationKey {
static let Welcome = "kWelcomeNotif"
}
struct Path {
static let Documents = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
static let Tmp = NSTemporaryDirectory()
}
}
然后你可以使用例如K.Path.Tmp
答案 1 :(得分:91)
我很晚才参加聚会。
无论我如何管理常量文件,以便在编写swift代码时对开发人员更有意义。
FOR URL:
//URLConstants.swift
struct APPURL {
private struct Domains {
static let Dev = "http://test-dev.cloudapp.net"
static let UAT = "http://test-UAT.com"
static let Local = "192.145.1.1"
static let QA = "testAddress.qa.com"
}
private struct Routes {
static let Api = "/api/mobile"
}
private static let Domain = Domains.Dev
private static let Route = Routes.Api
private static let BaseURL = Domain + Route
static var FacebookLogin: String {
return BaseURL + "/auth/facebook"
}
}
对于CUSTOMFONTS:
//FontsConstants.swift
struct FontNames {
static let LatoName = "Lato"
struct Lato {
static let LatoBold = "Lato-Bold"
static let LatoMedium = "Lato-Medium"
static let LatoRegular = "Lato-Regular"
static let LatoExtraBold = "Lato-ExtraBold"
}
}
适用于APP中使用的所有密钥
//KeyConstants.swift
struct Key {
static let DeviceType = "iOS"
struct Beacon{
static let ONEXUUID = "xxxx-xxxx-xxxx-xxxx"
}
struct UserDefaults {
static let k_App_Running_FirstTime = "userRunningAppFirstTime"
}
struct Headers {
static let Authorization = "Authorization"
static let ContentType = "Content-Type"
}
struct Google{
static let placesKey = "some key here"//for photos
static let serverKey = "some key here"
}
struct ErrorMessage{
static let listNotFound = "ERROR_LIST_NOT_FOUND"
static let validationError = "ERROR_VALIDATION"
}
}
FOR COLOR CONSTANTS:
//ColorConstants.swift
struct AppColor {
private struct Alphas {
static let Opaque = CGFloat(1)
static let SemiOpaque = CGFloat(0.8)
static let SemiTransparent = CGFloat(0.5)
static let Transparent = CGFloat(0.3)
}
static let appPrimaryColor = UIColor.white.withAlphaComponent(Alphas.SemiOpaque)
static let appSecondaryColor = UIColor.blue.withAlphaComponent(Alphas.Opaque)
struct TextColors {
static let Error = AppColor.appSecondaryColor
static let Success = UIColor(red: 0.1303, green: 0.9915, blue: 0.0233, alpha: Alphas.Opaque)
}
struct TabBarColors{
static let Selected = UIColor.white
static let NotSelected = UIColor.black
}
struct OverlayColor {
static let SemiTransparentBlack = UIColor.black.withAlphaComponent(Alphas.Transparent)
static let SemiOpaque = UIColor.black.withAlphaComponent(Alphas.SemiOpaque)
static let demoOverlay = UIColor.black.withAlphaComponent(0.6)
}
}
您可以将这些所有文件包装在Xcode项目中名为常量的公共组中。
更多观看此video
答案 2 :(得分:28)
虽然我更喜欢@ Francescu的方式(使用具有静态属性的结构),但您也可以定义全局常量和变量:
let someNotification = "TEST"
但请注意,与局部变量/常量和类/结构属性不同,globals是隐式延迟的,这意味着它们在第一次访问时会被初始化。
建议阅读:Global and Local Variables,以及Global variables in Swift are not variables
答案 3 :(得分:20)
Constant.swift
import Foundation
let kBaseURL = NSURL(string: "http://www.example.com/")
ViewController.swift
var manager = AFHTTPRequestOperationManager(baseURL: kBaseURL)
答案 4 :(得分:18)
考虑枚举。这些可以在逻辑上分解为单独的用例。
enum UserDefaultsKeys: String {
case SomeNotification = "aaaaNotification"
case DeviceToken = "deviceToken"
}
enum PhotoMetaKeys: String {
case Orientation = "orientation_hv"
case Size = "size"
case DateTaken = "date_taken"
}
当您遇到互斥选项时会发生一个独特的好处,例如:
for (key, value) in photoConfigurationFile {
guard let key = PhotoMetaKeys(rawvalue: key) else {
continue // invalid key, ignore it
}
switch (key) {
case.Orientation: {
photo.orientation = value
}
case.Size: {
photo.size = value
}
}
}
在此示例中,您将收到编译错误,因为您尚未处理PhotoMetaKeys.DateTaken
的情况。
答案 5 :(得分:14)
或者只是在GlobalConstants.swift中:
import Foundation
let someNotification = "aaaaNotification"
答案 6 :(得分:7)
像其他人一样,提到在课堂外宣布的任何内容都是全球性的。
你也可以创建单身人士:
class TestClass {
static let sharedInstance = TestClass()
// Anything else goes here
var number = 0
}
如果您想要使用此课程中的某些内容,例如写:
TestClass.sharedInstance.number = 1
如果您现在从项目的任何位置编写println(TestClass.sharedInstance.number)
,则会将1
打印到日志中。这适用于各种对象。
tl; dr:每当您想要在全局类中创建所有内容时,请向该类添加static let sharedInstance = YourClassName()
,并使用前缀{{1}来处理该类的所有值}
答案 7 :(得分:4)
我在Swift项目中做了什么
1:创建新的Swift文件
2:在其中创建结构和静态常量
3:对于使用,只需使用YourStructName.baseURL
注意:创建初始化后需要很少的时间,因此它会在2-5秒后显示在其他视图控制器中。
import Foundation
struct YourStructName {
static let MerchantID = "XXX"
static let MerchantUsername = "XXXXX"
static let ImageBaseURL = "XXXXXXX"
static let baseURL = "XXXXXXX"
}
答案 8 :(得分:2)
对于通知,您可以使用扩展名,如下所示:
extension Notification.Name {
static let testNotification = "kTestNotification"
}
并像NotificationCenter.default.post(name: .testNotification, object: nil)
答案 9 :(得分:1)
<强>颜色强>
extension UIColor {
static var greenLaPalma: UIColor {
return UIColor(red:0.28, green:0.56, blue:0.22, alpha:1.00)
}
}
<强>字体强>
enum CustomFontType: String {
case avenirNextRegular = "AvenirNext-Regular",
avenirDemiBold = "AvenirNext-DemiBold"
}
extension UIFont {
static func getFont(with type: CustomFontType, size: CGFloat) -> UIFont {
let font = UIFont(name: type.rawValue, size: size)!
return font
}
}
对于其他 - 一切都与接受的答案相同。
答案 10 :(得分:1)
根据swift docs全局变量在文件范围内声明。
全局变量是在任何函数,方法,闭包或类型上下文之外定义的变量
只需创建一个swift文件(例如:Constnats.swift)并在那里声明你的常量:
// Constants.swift
let SOME_NOTIF = "aaaaNotification"
并从项目的任何位置调用它,而无需提及struct,enum或class name。
// MyViewController.swift
NotificationCenter.default.post(name: SOME_NOTIF, object: nil)
我认为这对于代码可读性来说要好得多。
答案 11 :(得分:1)
向Apple学习是最好的方法。
例如,Apple的键盘通知:
extension UIResponder {
public class let keyboardWillShowNotification: NSNotification.Name
public class let keyboardDidShowNotification: NSNotification.Name
public class let keyboardWillHideNotification: NSNotification.Name
public class let keyboardDidHideNotification: NSNotification.Name
}
现在我向苹果学习:
extension User {
/// user did login notification
static let userDidLogInNotification = Notification.Name(rawValue: "User.userDidLogInNotification")
}
此外,NSAttributedString.Key.foregroundColor
:
extension NSAttributedString {
public struct Key : Hashable, Equatable, RawRepresentable {
public init(_ rawValue: String)
public init(rawValue: String)
}
}
extension NSAttributedString.Key {
/************************ Attributes ************************/
@available(iOS 6.0, *)
public static let foregroundColor: NSAttributedString.Key // UIColor, default blackColor
}
现在我从Apple学习:
extension UIFont {
struct Name {
}
}
extension UIFont.Name {
static let SFProText_Heavy = "SFProText-Heavy"
static let SFProText_LightItalic = "SFProText-LightItalic"
static let SFProText_HeavyItalic = "SFProText-HeavyItalic"
}
用法:
let font = UIFont.init(name: UIFont.Name.SFProText_Heavy, size: 20)
向苹果学习是每个人都可以做的事情,并且可以轻松地提高代码质量。
答案 12 :(得分:0)
Swift 4版本
如果要为NotificationCenter创建名称:
extension Notification.Name {
static let updateDataList1 = Notification.Name("updateDataList1")
}
订阅通知
NotificationCenter.default.addObserver(self, selector: #selector(youFunction), name: .updateDataList1, object: nil)
发送通知
NotificationCenter.default.post(name: .updateDataList1, object: nil)
如果您只想使用带有变量的类:
class Keys {
static let key1 = "YOU_KEY"
static let key2 = "YOU_KEY"
}
或者:
struct Keys {
static let key1 = "YOU_KEY"
static let key2 = "YOU_KEY"
}
答案 13 :(得分:0)
要在我的应用程序中包含全局常量,这是我在单独的 Swift 文件中所做的:
import Foundation
struct Config {
static let baseURL = "https://api.com"
static APIKeys {
static let token = "token"
static let user = "user"
}
struct Notifications {
static let awareUser = "aware_user"
}
}
易于使用,并且可以像这样调用任何地方
print(Config.Notifications.awareUser)
答案 14 :(得分:0)
也可以使用无大小写的枚举。
优点-它们无法实例化。
enum API {
enum Endpoint {
static let url1 = "url1"
static let url2 = "url2"
}
enum BaseURL {
static let dev = "dev"
static let prod = "prod"
}
}