Swift의 전역 상수 파일
Objective-C 프로젝트에서 알림 이름 및 키와 같은 항목을 저장하기 위해 글로벌 상수 파일을 사용하는 경우가 많습니다.NSUserDefaults
다음과 같습니다.
@interface GlobalConstants : NSObject
extern NSString *someNotification;
@end
@implementation GlobalConstants
NSString *someNotification = @"aaaaNotification";
@end
스위프트에서 정확히 같은 일을 어떻게 합니까?
네임스페이스로서의 구조체
IMO에서 이러한 유형의 상수를 처리하는 가장 좋은 방법은 구조를 만드는 것입니다.
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
실제 사례
이것은 기술적인 해결책일 뿐이며, 내 코드의 실제 구현은 다음과 같습니다.
struct GraphicColors {
static let grayDark = UIColor(0.2)
static let grayUltraDark = UIColor(0.1)
static let brown = UIColor(rgb: 126, 99, 89)
// etc.
}
그리고.
enum Env: String {
case debug
case testFlight
case appStore
}
struct App {
struct Folders {
static let documents: NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
static let temporary: NSString = NSTemporaryDirectory() as NSString
}
static let version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
static let build: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String
// This is private because the use of 'appConfiguration' is preferred.
private static let isTestFlight = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
// This can be used to add debug statements.
static var isDebug: Bool {
#if DEBUG
return true
#else
return false
#endif
}
static var env: Env {
if isDebug {
return .debug
} else if isTestFlight {
return .testFlight
} else {
return .appStore
}
}
}
저는 파티에 조금 늦었습니다.
여기서 내가 상수 파일을 관리하는 방법이 무엇이든 간에 개발자가 코드를 빠르게 작성할 때 더 의미가 있습니다.
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"
}
}
사용자 정의 글꼴의 경우
//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"
}
}
앱에서 사용되는 모든 키에 대해
//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"
}
}
색 상수의 경우:
//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 프로젝트의 상수라는 공통 그룹으로 래핑할 수 있습니다.
자세한 내용은 이 비디오를 참조하십시오.
정적 특성을 가진 구조체를 사용하는 @Francescu의 방법을 선호하지만 전역 상수와 변수를 정의할 수도 있습니다.
let someNotification = "TEST"
그러나 로컬 변수/상수 및 클래스/구조 속성과 달리 전역은 암묵적으로 게으릅니다. 즉, 처음 액세스할 때 초기화됩니다.
권장 판독값: 전역 및 로컬 변수 및 Swift의 전역 변수는 변수가 아닙니다.
열거형을 고려합니다.이들은 논리적으로 분리하여 별도의 사용 사례에 사용할 수 있습니다.
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
.
상수.swift
import Foundation
let kBaseURL = NSURL(string: "http://www.example.com/")
ViewController.swift
var manager = AFHTTPRequestOperationManager(baseURL: kBaseURL)
또는 GlobalConstants.swift:
import Foundation
let someNotification = "aaaaNotification"
다른 사람들이 언급했듯이, 클래스 외부에 선언된 모든 것은 글로벌합니다.
싱글톤을 생성할 수도 있습니다.
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()
" 스에접로", " 그고사클래스의모다든"로 지정합니다.YourClassName.sharedInstance
에서 한 은 ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ
1: 새 Swift 파일 만들기
합니다.2: 그안구조및정적상만수다듭니를.
YourStructName: "StructName.base"를 합니다. URL
참고: 생성 후 초기화는 시간이 거의 걸리지 않으므로 2-5초 후에 다른 뷰 컨트롤러에 표시됩니다.
import Foundation
struct YourStructName {
static let MerchantID = "XXX"
static let MerchantUsername = "XXXXX"
static let ImageBaseURL = "XXXXXXX"
static let baseURL = "XXXXXXX"
}
앱에 글로벌 상수를 설정하려면 별도의 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)
대소문자를 구분하지 않는 열거형도 사용할 수 있습니다.
장점 - 인스턴스화할 수 없습니다.
enum API {
enum Endpoint {
static let url1 = "url1"
static let url2 = "url2"
}
enum BaseURL {
static let dev = "dev"
static let prod = "prod"
}
}
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
}
이제 Apple로부터 배웠습니다.
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)
Apple에서 배우는 것은 모든 사람이 할 수 있는 방법이며 코드 품질을 쉽게 홍보할 수 있습니다.
알림의 경우 다음과 같은 확장 기능을 사용할 수 있습니다.
extension Notification.Name {
static let testNotification = "kTestNotification"
}
그리고 이렇게 사용합니다.NotificationCenter.default.post(name: .testNotification, object: nil)
스위프트 4 버전
Notification Center의 이름을 생성하려는 경우:
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"
}
색
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
}
}
기타의 경우 - 모든 것이 승인된 답변과 동일합니다.
swiftdocs에 따르면 글로벌 변수는 파일 범위에서 선언됩니다.
전역 변수는 함수, 메서드, 폐쇄 또는 유형 컨텍스트 외부에 정의된 변수입니다.
swift 파일(예: Constnats.swift)을 생성하고 상수를 다음과 같이 선언합니다.
// Constants.swift
let SOME_NOTIF = "aaaaNotification"
구조, 구조 또는 클래스 이름을 언급할 필요 없이 프로젝트의 어디에서나 호출할 수 있습니다.
// MyViewController.swift
NotificationCenter.default.post(name: SOME_NOTIF, object: nil)
코드 가독성을 위해 이것이 훨씬 낫다고 생각합니다.
언급URL : https://stackoverflow.com/questions/26252233/global-constants-file-in-swift
'programing' 카테고리의 다른 글
--assume-unchanged로 표시된 파일 목록을 얻을 수 있습니까? (0) | 2023.05.07 |
---|---|
레일 4 LIKE 쿼리 - ActiveRecord가 인용문을 추가합니다. (0) | 2023.05.07 |
[]와 []의 차이점은 무엇입니까? (0) | 2023.05.07 |
pyMongo를 사용하여 ISO 날짜 만들기 (0) | 2023.05.02 |
이클립스에서 "Debug Perspective로 자동 전환" 모드를 해제하려면 어떻게 해야 합니까? (0) | 2023.05.02 |