You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Swift中实现C#的Right方法,正确编写空值判断语句?

Equivalent Swift Implementation for the C# Right Method

Let’s break down how to replicate your C# logic efficiently in Swift, focusing on clean null/empty checks that fit Swift’s idioms.

Option 1: Standalone Function (Handles Optional Input)

This function mirrors your original C# method’s behavior directly, handling both nil and empty strings seamlessly:

func right(_ value: String?, length: Int) -> String {
    // Combine nil check and empty check in one concise guard statement
    guard let nonNilValue = value, !nonNilValue.isEmpty else {
        return ""
    }
    
    // Return the full string if it's shorter than the requested length
    guard nonNilValue.count > length else {
        return nonNilValue
    }
    
    // Calculate the starting index for the substring (Swift uses Unicode-aware indices)
    let startIndex = nonNilValue.index(nonNilValue.endIndex, offsetBy: -length)
    return String(nonNilValue[startIndex...])
}

Option 2: String Extension (More Swift-Like Approach)

If you prefer extending the String type directly (a common Swift pattern), here’s an extension plus a helper for optional strings:

extension String {
    func right(_ length: Int) -> String {
        guard count > length else {
            return self
        }
        let startIndex = index(endIndex, offsetBy: -length)
        return String(self[startIndex...])
    }
}

// Helper to handle optional strings
extension Optional where Wrapped == String {
    func right(_ length: Int) -> String {
        guard let self = self, !self.isEmpty else {
            return ""
        }
        return self.right(length)
    }
}

Key Details on the Null/Empty Check

  • In Swift, guard let lets us safely unwrap optional values and add additional conditions (like checking for empty) in a single line—this is the efficient alternative to your C# null/empty check.
  • Swift strings are Unicode-aware, so we use index(_:offsetBy:) instead of integer indices to avoid errors with multi-byte characters.

Example Usage

// Standalone function
print(right("Hello World", length: 5)) // Output: "World"
print(right("", length: 3)) // Output: ""
print(right(nil, length: 2)) // Output: ""
print(right("Hi", length: 5)) // Output: "Hi"

// Extension approach
print("Hello World".right(5)) // Output: "World"
print((nil as String?).right(2)) // Output: ""
print("Hi".right(5)) // Output: "Hi"

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:46:42