NerdzUtils

NerdzUtils 是一个 Swift 框架,旨在通过提供一系列实用工具类和扩展来简化和增强常见的开发任务。该框架分为三个主要文件夹:


目录:



- 扩展 (Foundation)

Array+Safe

Array+Safe 扩展为 Array 类型添加了一个下标 (safe),允许通过索引安全地访问元素。它通过在请求的索引超出数组边界时返回 nil 来帮助防止索引越界错误。

用法

// Create an array
let myArray = [1, 2, 3, 4, 5]

// Access elements safely using the 'safe' subscript
if let element = myArray[safe: 2] {
    print("Element at index 2: \(element)")
} 
else {
    print("Index 2 is out of range.")
}

// Try accessing an element at an out-of-range index
if let element = myArray[safe: 10] {
    print("Element at index 10: \(element)")
} 
else {
    print("Index 10 is out of range.")
}


Bundle+CurrentAppVersion

Bundle+CurrentAppVersion 扩展为 Bundle 类型添加了一个计算属性 appVersion。此属性提供了一种便捷的方式来从应用程序的 Info.plist 文件中检索当前应用程序版本。

用法

let currentVersion = Bundle.main.appVersion


CGSize+Dimentions

CGSize 的此扩展为处理具有特定宽高比的尺寸提供了便捷的实用工具。

功能

宽高比尺寸

缩放

用法

// Access aspect ratio sizes
let size16x9 = CGSize.w16_h9
let sizeScaled = CGSize(width: 10, height: 5).scaled(by: 2.0)

// ... (use other aspect ratios and methods as needed)


DateDecodingStrategy+CustomISO8601

DateDecodingStrategy+CustomISO8601 扩展为解析带有小数秒的 ISO 8601 日期提供了自定义的 DateDecodingStrategy

功能

用法

要使用 DateDecodingStrategy+CustomISO8601 扩展,请按照以下步骤操作

在配置 JSONDecoder 实例以处理带有小数秒的 ISO 8601 日期时,使用 customISO8601 策略。

// Create a JSONDecoder with the custom date decoding strategy
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .customISO8601

// Use the decoder to decode JSON containing ISO 8601 dates with fractional seconds
let jsonData = """
{"date": "2024-02-05T12:34:56.789Z"}
""".data(using: .utf8)!

let decodedObject = try decoder.decode(MyObject.self, from: jsonData)


DispatchQueue+Once

DispatchQueue+Once 扩展提供了一种机制,以确保代码块仅执行一次,无论调用多少次。

功能

用法

  1. 每个令牌执行一次代码:

    使用 once(per:token:action:) 方法可确保代码块对于与对象关联的每个提供的令牌仅执行一次。

    private func requestDefaultPermissions() async {
         DispatchQueue.nz.once(per: self, token: permissionsToken) { [weak self] in
             self?.permissionsManager.requestFirstLaunchStartupPermissions()
         }
     }
  2. 直接每个令牌执行一次代码

    或者,使用 once(for:action:) 方法直接对于每个提供的令牌执行一次代码块。

     DispatchQueue.nz.once(for: "uniqueToken") {
         // Code to be executed once
     }


Encodable+JsonData

Encodable+JsonData 扩展简化了将符合 Encodable 协议的对象转换为 JSON 数据的过程。

功能

用法

struct MyStruct: Encodable {
    let id: Int
    let title: String
}

let myObject = MyStruct(id: 1, title: "Sample Title")

// Get JSON data from the encodable object
if let jsonData = myObject.nz_jsonData {
    // Use jsonData as needed
    print("JSON Data: \(String(data: jsonData, encoding: .utf8) ?? "Unable to convert to string")")
}


Formatter+iso8601

Formatter+iso8601 扩展提供了带有和不带有小数秒的 ISO8601 日期格式化器。

功能

用法

// Format a date with fractional seconds
let currentDateWithFS = Date()
let formattedWithFS = Formatter.iso8601WithFS.string(from: currentDateWithFS)

// Format a date without fractional seconds
let currentDate = Date()
let formattedWithoutFS = Formatter.iso8601.string(from: currentDate)


NZUtilsExtensionData

NZUtilsExtensionDataNZUtilsExtensionCompatible 为创建具有流畅语法的 Swift 扩展奠定了基础,允许您向现有类型添加实用方法。

功能

用法

1. NZUtilsExtensionData

// Example: Creating an NZUtilsExtensionData wrapper
let myInteger = 42
let wrapper = NZUtilsExtensionData(myInteger)

// Access the base value
let baseValue = wrapper.base // This will be 42

2. NZUtilsExtensionCompatible

// Example: Making a type compatible with NZUtils extensions
struct MyStruct:NZUtilsExtensionCompatible {
    var value: String
}

// Use NZUtilsExtensionData for MyStruct
let myInstance = MyStruct(value: "Hello")
let wrappedInstance = myInstance.nz

// Access the base value
let baseValue = wrappedInstance.base // This will be an instance of MyStruct


Locale+CountryList

Locale+CountryList 扩展提供了便捷的方法来检索国家/地区列表并根据当前设备区域设置获取特定国家/地区的详细信息。

功能

用法

// Access country list
let countries [Country] = Locale.current.countryList

// Access details for a specific country (e.g., "US")
if let countryDetails = Locale.current.country(from: "US") {
    print("Country Code: \(countryDetails.code), Country Name: \(countryDetails.name)")
}


NSObject+ClassName

NSObject+ClassName 扩展提供了便捷的方法来检索 NSObject 实例的类名。

功能

用法

  1. 访问类名(静态):

    // Access class name for MyClass
    let className = MyClass.className
  2. 访问类名(实例):

    // Create an instance of MyClass
    let myClass = MyClass()
    
    // Access class name for the instance
    let instanceClassName = myClass.nz.className


String+Attributed

String+Attributed 扩展提供了一种便捷的方法,可以使用指定的属性从 String 创建属性化字符串。

功能

用法

let originalString = "Hello, World!"

let attributes: [NSAttributedString.Key: Any] = [
   .font: UIFont.boldSystemFont(ofSize: 16),
   .foregroundColor: UIColor.blue
]

let attributedString = originalString.nz.attributed(with: attributes)


String+IsWhiteSpaceOrEmpty

String+IsWhiteSpaceOrEmpty 扩展提供了一种便捷的方法来检查字符串是否为空或仅由空格和换行符组成。

功能

用法

let emptyString = ""
let whitespaceString = "     "
let nonEmptyString = "Hello, World!"

let isEmpty = emptyString.nz.isWhiteSpaceOrEmpty // true
let isWhitespace = whitespaceString.nz.isWhiteSpaceOrEmpty // true
let isNonEmpty = nonEmptyString.nz.isWhiteSpaceOrEmpty // false


String+Localization

String+Localization 扩展提供了一种便捷的方法来获取字符串的本地化表示形式,并支持覆盖当前区域设置。

功能

用法

  1. 获取本地化字符串:

    使用 localized 属性获取字符串的本地化表示形式。

    let originalString = "hello_key"
    let localizedString = originalString.nz.localized

    在此示例中,localizedString 将包含键为 "hello_key" 的字符串的本地化表示形式。

  2. 覆盖区域设置:

    (可选)使用 overridenLocale 属性来设置或检索本地化的覆盖区域设置。

    originalString.nz.overridenLocale = "fr" // Set to "fr" for French locale
    
    // Access the localized string with the overridden locale
    let frenchLocalizedString = originalString.nz.localized

    注意:确保覆盖的区域设置是有效的区域设置标识符(例如,“fr”表示法语)。



String+VersionCompare

String+VersionCompare 扩展提供了将字符串版本与目标版本进行比较的方法,从而可以在 Swift 项目中轻松进行版本比较。

功能

用法

// Example: Comparing string versions
let currentVersion = "1.2.3"
let targetVersion = "1.2.0"

let isEqual = currentVersion.nz.isVersion(equalTo: targetVersion) // false
let isGreater = currentVersion.nz.isVersion(greaterThan: targetVersion) // true
let isGreaterOrEqual = currentVersion.nz.isVersion(greaterThanOrEqualTo: targetVersion) // true
let isLess = currentVersion.nz.isVersion(lessThan: targetVersion) // false
let isLessOrEqual = currentVersion.nz.isVersion(lessThanOrEqualTo: targetVersion) // false



扩展 (UIKit)



UIApplication+OpenSettings

UIApplication+OpenSettings 扩展提供了一种便捷的方法来打开 iOS 上应用程序的原生设置。

功能

用法

let application = UIApplication.shared
application.openSettings()


UIApplication+Jailbreak

UIApplication+Jailbreak 扩展提供了一种实用工具方法来检查当前设备是否可能已越狱。

功能

用法

let application = UIApplication.shared
let isJailbroken = application.nz.isJailbroken


UIColor+Hex

UIColor+Hex 扩展提供了一个便捷的初始化器,可以使用十六进制颜色代码创建 UIColor 实例。

功能

用法

let hexColor = "#FF5733"
let alphaValue: CGFloat = 1.0

let color = UIColor(hex: hexColor, alpha: alphaValue)


UIAlertController+Extensions

UIAlertController+Extensions 提供了便捷的扩展,以简化 Swift 中 UIAlertController 实例的创建和呈现。

功能

用法

// Example: Creating and presenting an alert
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)

alertController.nz
   .action(title: "Default Action") {
       // Handle default action
   }
   .destructive(title: "Destructive Action") {
       // Handle destructive action
   }
   .cancel(title: "Cancel Action") {
       // Handle cancel action
   }
   .source(sourceView)
   .show(on: presentingController)


UIButton+Localized

UIButton+Localized 扩展提供了一种便捷的方式来为 UIButton 实例设置本地化文本,尤其是在使用 nib 文件时非常有用。

功能

用法

  1. 以编程方式设置本地化文本:

    let button = UIButton(type: .system)
    button.nz.textLocalization = "buttonTitleKey"
  2. 在 Interface Builder 中设置本地化文本:

    使用 @IBInspectable 属性 nz_textLocalization 直接在 Interface Builder 中设置本地化文本。

    Screenshot 2024-02-16 at 15 50 23



UIColor+Inversed

UIColor+Inversed 扩展提供了一种简单的方法来获取给定 UIColor 的反色。这对于在您的应用程序中创建视觉上对比鲜明的元素非常有用。

功能

用法

  1. 以编程方式计算反色:

    let originalColor = UIColor.red
    let inverseColor = originalColor.nz.inversed
  2. 在 UI 元素中应用反色:

    let originalColor = UIColor.blue
    let inverseColor = originalColor.nz.inversed
    
    let myView = UIView()
    myView.backgroundColor = originalColor // Set the original color
    // ...
    // Apply the inverse color to another UI element
    someOtherElement.backgroundColor = inverseColor


UIControl+ClosureAction

UIControl+ClosureAction 扩展允许您轻松地向 UIControl 添加基于闭包的操作。这提供了一种更简洁和更具表现力的方式来处理控件事件。

功能

用法

  1. 添加基于闭包的操作:

    let myButton = UIButton()
    
    myButton.nz.addAction(for: .touchUpInside) {
        print("Button tapped!")
    }
  2. 使用闭包处理控件事件:

    let mySwitch = UISwitch()
    
    mySwitch.nz.addAction(for: .valueChanged) {
        print("Switch value changed!")
    }


UIImage+BlurHash

UIImage+BlurHash 扩展提供了一种使用 BlurHash 算法轻松初始化 UIImage 的方法。BlurHash 是图像占位符的紧凑表示形式,对于使用占位符效果延迟加载图像非常有用。

功能

用法

let blurHashInfo = BlurHashInfo(
    hash: "LEHV6nWB2yk8pyo0adR*.7kCMdnj", 
    size: CGSize(width: 320, height: 240)
)

if let blurredImage = UIImage(info: blurHashInfo) {
   // Use the blurredImage as a placeholder or background
}


UIImage+Scale

UIImage+Scale 扩展提供了便捷的方法,可以根据宽度、高度或自定义大小要求缩放 UIImage 对象。

功能

用法

  1. 按宽度/高度缩放图像:

    使用 scaled(toWidth:)/scaled(toHeight:) 方法将图像缩放到特定宽度/高度。

    let originalImage: UIImage = // Some image
    let scaledByWidthImage = originalImage.nz.scaled(toWidth: 200)
    let scaledByHeightImage = originalImage.nz.scaled(toHeight: 150)
  2. 缩放到较大边/较小边图像:

    使用 scaled(toBigger:)/scaled(toSmaller:) 方法将图像缩放到较大边/较小边的指定大小。

    let originalImage: UIImage = // Some image
    let scaledToBiggerSideImage = originalImage.nz.scaled(toBigger: 300)
    let scaledToSmallerSideImage = originalImage.nz.scaled(toSmaller: 120)
  3. 缩放到适应大小图像:

    使用 scaled(toFit:) 方法缩放图像以适应目标大小,同时保持宽高比。

    let originalImage: UIImage = // Some image
    let targetSize = CGSize(width: 250, height: 200)
    let scaledImage = originalImage.nz.scaled(toFit: targetSize)
  4. 按因子缩放图像:

    使用 scaled(by:) 方法按提供的因子缩放图像。

    let originalImage: UIImage = // Some image
    let scaledImage = originalImage.nz.scaled(by: 1.5)


UILabel+NibLocalized

UILabel+NibLocalized 扩展提供了一种便捷的方式,可以直接从 .nib 文件为 UILabel 元素设置本地化文本。

功能

用法

  1. UILabel 的本地化文本:

    let localizedLabel: UILabel = // Your UILabel from the Nib file
    localizedLabel.nz.textLocalization = "localized_key"
  2. Nib 文件中的本地化文本:

    在您的 nib 文件中,您可以直接从 Xcode 的属性检查器中设置本地化文本。将 nz_textLocalization 属性设置为本地化键。UILabel 的文本将自动设置为与指定键对应的本地化字符串。

    Screenshot 2024-02-16 at 16 27 10




UIKIt 扩展


UINavigationBar+Translucent

UINavigationBar+Translucent 扩展提供了一种便捷的方式来控制 UINavigationBar 的半透明度。

功能

用法

let navigationBar: UINavigationBar = // Your UINavigationBar instance
navigationBar.nz.makeTranslucent(true)
navigationBar.nz.makeTranslucent(false)


UINavigationController+Completion

NerdzUtils 框架中的 UINavigationController+Completion 扩展通过为各种导航操作提供完成闭包来增强 UINavigationController。

功能

用法

  1. 推送带有完成处理程序的视图控制器:

    let navigationController: UINavigationController = // Your UINavigationController instance
    let viewController: UIViewController = // The view controller to push
    
    navigationController.nz.pushViewController(viewController, animated: true) {
        print("ViewController pushed!")
    }
  2. 弹出到带有完成处理程序的视图控制器:

    let navigationController: UINavigationController = // Your UINavigationController instance
    let viewController: UIViewController = // The view controller to pop to
    
    navigationController.nz.popToViewController(viewController, animated: true) {
        print("Popped to ViewController!")
    }
  3. 弹出带有完成处理程序的视图控制器:

    let navigationController: UINavigationController = // Your UINavigationController instance
    
    navigationController.nz.popViewController(animated: true) {
        print("Popped top ViewController!")
    }
  4. 弹出到带有完成处理程序的根视图控制器:

    let navigationController: UINavigationController = // Your UINavigationController instance
    
    navigationController.nz.popToRootViewController(animated: true) {
        print("Popped to Root ViewController!")
    }


UITextField+Localized

UITextField+Localized 扩展通过提供直接从 Interface Builder 或以编程方式设置本地化文本和占位符的功能来增强 UITextField。

功能

用法

  1. 本地化文本:

    直接从 Interface Builder 或以编程方式设置本地化文本。

    • 从 Interface Builder:

      在 UITextField 的属性检查器中设置 nz_textLocalization 属性。

      Screenshot 2024-02-18 at 15 27 24
    • 以编程方式:

      let textField: UITextField = // Your UITextField instance
      textField.nz_textLocalization = "localized_key"
  2. 本地化占位符:

    直接从 Interface Builder 或以编程方式设置本地化占位符。

    • 从 Interface Builder:

      在 UITextField 的属性检查器中设置 nz_placeholderLocalization 属性。

      Screenshot 2024-02-18 at 15 27 24
    • 以编程方式:

      let textField: UITextField = // Your UITextField instance
      textField.nz_placeholderLocalization = "localized_placeholder_key"


UITextField+PasswordVisibility

UITextField+PasswordVisibility 扩展通过提供密码可见性切换来增强 UITextField。

功能

属性

名称 类型 可访问性 描述
nz_isPasswordVisibilityToggleEnabled Bool read-write IBInspectable 直接从 Interface Builder 或以编程方式启用或禁用密码可见性切换。

用法

启用密码可见性切换

从 Interface Builder

在 UITextField 的属性检查器中设置 nz_isPasswordVisibilityToggleEnabled 属性。

Screenshot 2024-02-18 at 15 35 57

以编程方式

let passwordTextField: UITextField = // Your UITextField instance
passwordTextField.nz_isPasswordVisibilityToggleEnabled = true


UIView+AddDashedBorder

UIView+AddDashedBorder 通过提供一种便捷的方法来向视图添加虚线边框,从而扩展了 UIView 类。

功能

方法

func addDashedBorder(...) -> CAShapeLayer

名称 类型 默认值 描述
strokeColor UIColor - 虚线边框的颜色。
fillColor UIColor UIColor.clear 虚线边框内部的颜色。
position CGPoint .zero 虚线边框的位置。
lineWidth CGFloat 2 虚线边框线的宽度。
lineJoin CAShapeLayerLineJoin .round 虚线边框的线连接样式。
lineDashPattern [NSNumber] [6, 3] 虚线边框的虚线模式。
cornerRadius CGFloat 20 圆角半径

用法

let myView: UIView = // Your UIView instance
let dashedBorderLayer = myView.nz.addDashedBorder(
    with: .blue,
    fillColor: .clear,
    position: CGPoint(x: 10, y: 10),
    lineWidth: 2,
    lineJoin: .round,
    lineDashPattern: [6, 3],
    cornerRadius: 20
)


UIView+ApplyGradient

UIView+ApplyGradient 扩展通过提供一种轻松向视图应用渐变的方法来增强 UIView 类。

功能

参数

名称 类型 默认值 描述
colors [UIColor] - 一个 UIColor 对象数组,用于定义每个渐变停止点的颜色。
locations [NSNumber] - 一个 NSNumber 对象数组,用于定义每个渐变停止点的位置,值范围为 [0,1]。
type CAGradientLayerType .axial 渐变的类型。
startPoint CGPoint {0.5, 0} 渐变的起始点。
endPoint CGPoint {0.5, 1} 渐变的结束点。

用法

let myView: UIView = // Your UIView instance
let gradientLayer = myView.nz.applyGradient(
    colors: [.red, .blue],
    locations: [0, 1],
    type: .axial,
    startPoint: CGPoint(x: 0.5, y: 0),
    endPoint: CGPoint(x: 0.5, y: 1)
)


UIView+ApplyShadow

UIView+ApplyShadow 扩展通过提供一种轻松向视图应用阴影的方法来增强 UIView 类。

功能

参数

名称 类型 默认值 描述
color UIColor - 阴影的颜色。
opacity Float 0.5 阴影的不透明度。
offSet CGSize .zero 阴影的偏移量。
radius CGFloat 1 阴影的半径。

用法

let myView: UIView = // Your UIView instance
myView.nz.applyShadow(
    color: .black,
    opacity: 0.7,
    offSet: CGSize(width: 2, height: 2),
    radius: 3
)


UIView+AsImage

UIView+AsImage 扩展通过提供一种捕获视图屏幕截图的方法来扩展 UIView 类。

功能

用法

let myView: UIView = // Your UIView instance
let screenshotImage = myView.nz.asImage()


UIView+InspectableLayer

UIView+InspectableLayer 扩展为配置 UIView 的图层提供了可检查的属性。

功能

属性

属性 类型 描述
cornerRadius CGFloat 视图圆角半径
maskedCorners CACornerMask 视图蒙版角(从 iOS 11.0 开始可用)
borderWidth CGFloat 视图边框宽度
borderColor UIColor? 视图边框颜色
shadowColor UIColor? 视图阴影颜色
shadowAlpha Float 视图阴影不透明度
shadowOffset CGSize 视图阴影偏移
shadowBlur CGFloat 视图阴影半径

用法



UIView+RoundCorners

UIView+RoundCorners 扩展提供了一种方法,可将圆角应用于 UIView 的特定角,并可以选择添加边框。

方法

用法

let myView: UIView = // Your UIView instance

// Apply round corners to the top-left and top-right corners with a radius of 10
// Also, add a border with a color of red and a width of 2
myView.nz.roundCorners(
    [.layerMinXMinYCorner, .layerMaxXMinYCorner],
    radius: 10,
    borderColor: .red, 
    borderWidth: 2
)


UIViewController+AddChild

UIViewController+AddChild 扩展提供了一种方法,可以轻松添加具有所有必要配置的子视图控制器。

方法

用法

let parentViewController: UIViewController = // Your parent view controller
let childViewController: UIViewController = // Your child view controller

// Add child view controller to the parent view controller's view with default configuration
parentViewController.nz.easilyAddChild(childViewController)

// Add child view controller to a custom container view with custom configuration
let customContainerView: UIView = // Your custom container view
parentViewController.nz.easilyAddChild(childViewController, on: customContainerView) { childView, parentView in
    // Your custom configuration code for constraints
}


UIViewController+Overlay

UIViewController+Overlay 扩展提供了将当前视图控制器作为覆盖层呈现和解除的方法。

方法

用法

let viewController: UIViewController = // Your view controller

// Present the view controller as an overlay
viewController.nz.presentAsOverlay()

// Dismiss the overlay if it was presented
do {
    try viewController.nz.dismissOverlay()
}
catch {
    print(error.localizedDescription)
}


UIViewController+Top

UIViewController+Top 扩展提供了一个属性,用于获取顶部呈现或推送的视图控制器。

属性

用法

let viewController: UIViewController = // Your view controller
let topController = viewController.nz.topController



UI 组件


LoadableButton

LoadableButton 是一个扩展 UIButton 的类,提供带有活动指示器的加载功能。

属性

名称 类型 默认值 描述
onStartLoading LoadableButtonEmptyAction - 加载开始时要执行的闭包。
onFinishLoading LoadableButtonEmptyAction - 加载完成时要执行的闭包。
topBottomIndicatorPadding CGFloat 10 活动指示器与按钮顶部和底部的间距。
isLoading Bool false 一个布尔值,指示按钮是否处于加载状态。
activityIndicatorView UIView - 表示加载指示器的视图。

用法

  1. 设置加载状态:

    let loadableButton: LoadableButton = // Your LoadableButton instance
    
    // Set the loading state
    loadableButton.isLoading = true
  2. 自定义加载按钮:

    let loadableButton: LoadableButton = // Your LoadableButton instance
    
    // Customize the loading button
    loadableButton.topBottomIndicatorPadding = 15
    loadableButton.activityIndicatorView = customActivityIndicatorView
  3. 处理加载事件:

    let loadableButton: LoadableButton = // Your LoadableButton instance
    
    loadableButton.onStartLoading = {
        // Code to execute when loading starts
    }
    
    loadableButton.onFinishLoading = {
        // Code to execute when loading finishes
    }


LoadableImageView (ImageStoringPolicy 枚举)

表示 LoadableImageView 类存储加载图像的方式

有关更多信息,请参阅 LoadableImageView 的文档


案例

.none

无需存储


.cache(timeout: TimeInterval? = nil)

加载的图像需要缓存

如果未提供超时时间,则图像将在目标存在期间被缓存。

名称 类型 默认值 描述
timeout TimeInterval? nil 缓存图像需要重新加载的持续时间


SpinnerLoader

方法

用法

  1. 开始使用旋转器加载:

    yourView.startSpinnerLoading(with: .white, size: 15.0)
  2. 停止加载:

    yourView.stopSpinnerLoading()



Utils



属性包装器:


@DefaultsProperty

一个属性包装器,简化了属性与 UserDefaults 的同步,提供自动初始化和值检索。

初始化器

属性

用法

  1. 基本用法:

    @DefaultsProperty("userLoggedIn", initial: false)
    var isUserLoggedIn: Bool
  2. 自定义 UserDefaults:

    let customUserDefaults = UserDefaults(suiteName: "com.example.app")
    
    @DefaultsProperty("darkModeEnabled", initial: false, defaults: customUserDefaults)
    var isDarkModeEnabled: Bool


@KeychainProperty

一个属性包装器,方便属性与 Keychain 的自动同步,提供无缝的初始化和值检索。

初始化器

属性

用法

  1. 基本用法:

    @KeychainProperty("userAuthToken", initial: "")
    var userAuthToken: String
  2. 自定义 UserDefaults:

    let customKeychain = Keychain(service: "com.example.app.keychain")
    
    @KeychainProperty("userPassword", initial: "", keychain: customKeychain)
    var userPassword: String


AtomicAsyncOperation

AtomicAsyncOperation 类封装了每次执行单个操作的逻辑,确保操作不会被多个请求并发启动。如果操作已经在进行中,则会将其他请求添加到完成列表,并在初始操作完成后调用其闭包。这种方法最大限度地减少了冗余执行,并为服务延迟初始化或优化请求执行等场景提供了解决方案。

注意此类在内部使用后台队列,因此请确保所有 UI 操作都包装在主队列中。

初始化

属性

方法

用法

let asyncOperation = AtomicAsyncOperation { completion in
    // Perform your asynchronous operation logic here
    // For example, fetching data from a network API
    fetchDataFromAPI { result in
        // Process the result
        // ...

        // Notify completion when finished
        completion()
    }
}

// Trigger the asynchronous operation
asyncOperation.perform {
    // Closure to be executed when the operation completes
    // This can be used to update the UI or perform additional tasks
}


DelayedAction

DelayedAction 类提供了一种延迟执行闭包的机制,并允许在需要时取消或重新安排。

方法

用法

  1. 延迟执行:

    let delayedAction = DelayedAction()
    
    // Schedule an action to be executed after a delay
    delayedAction.perform(after: 2.0) {
        print("Delayed action executed!")
    }
    
    // Cancelling the pending execution (if needed)
    delayedAction.cancel()
  2. 重新安排操作:

    let delayedAction = DelayedAction()
    
    delayedAction.perform(after: 3.0) {
        print("Initial action executed!")
    }
    
    // Rescheduling the action to be executed sooner
    delayedAction.perform(after: 1.0) {
        print("Rescheduled action executed!")
    }


IdType

IdType 协议定义了表示唯一标识符的类型的要求。当您有各种类型的实体(例如,用户、产品等)需要标准化的方式来表示其身份时,通常会使用它。它确保唯一性并方便诸如相等比较 (==) 和哈希之类的操作。

协议概述

子协议

默认实现

运算符重载

用法

// Example conforming type
struct UserID: IntIdType {
    let id: Int
}

// Example usage
let user1 = UserID(id: 42)
let user2 = UserID(id: 42)

// Equality comparison
let areEqual = (user1 == user2) // true

// Hashing
var hasher = Hasher()
user1.hash(into: &hasher)
let hashValue1 = hasher.finalize()

print("Hash Value for User 1: \(hashValue1)")


SyncPropertyActor

SyncPropertyActor 是一个基于 Actor 的容器,旨在为给定类型的属性提供线程安全的访问。

初始化

方法

用法

  1. 设置新值:

    private let nextProductsPageLink = SyncPropertyActor<URL?>(nil)
    
    Task {
        // Use the setNewValue method to set the property to a new URL.
        await nextProductsPageLink.setNewValue(URL(string: "https://example.com/nextpage"))
    }
  2. 修改现有值:

    // Example of modifying the property within a task
    Task {
        nextProductsPageLink.modify { currentURL in
            // Modify the current URL, for example, appending a query parameter
            currentURL?.appendPathComponent("additionalPath")
        }
    }


@ Weak<T>

类型: class

添加在强包装器中拥有弱引用的可能性。在您需要在 ArrayDictionary 中使用对象的弱引用的情况下很有用。


使用示例

class SomeClass {
    // All objects stored in this array will be stored with weak reference
    private let weekArray = Array<Weak<AnotherClass>>()
}

属性

名称 类型 可访问性 描述
对象 T? 读写 包装的对象

方法

init(_ object: T?)

使用包装的对象来初始化包装器

名称 类型 默认值 描述
对象 T? 包装的对象