ios - 将 Swift String 转换为 UTF-8 并使用 char 的 ASCII 值进行算术运算

标签 ios objective-c string swift utf-8

我正在尝试将遗留的 Objective-C 函数转换为 Swift,但遇到了一些障碍。这是 Objective-C 函数 -

- (SHCardType)cardType:(NSString *)cardNum {
    if (cardNum.length <= 0) {
        return SHCTUnknown;
    }
    const char *s = [cardNum UTF8String];

    if (sizeof(cardTypes[0]) == 0) {
        return SHCTUnknown;
    }
    int cardsCount = sizeof(cardTypes) / sizeof(cardTypes[0]);
    for (int i = 0; i < cardsCount; i++) {
        int dig = log10(cardTypes[i].max) + 1;
        int n = 0;

        for (int j = 0; j < dig; j++) {
            n = n * 10 + (s[j] - '0');
        }

        if ((cardTypes[i].min <= n) && (n <= cardTypes[i].max)) {
            SHCardType cardType = cardTypes[i].cardType;
            int numLength = 16;
            if (cardType == SHCTAmericanExpress) {
                // Length is 15. Should confirm its type before all card number is entered.
                return cardType;
            } else if (cardType == SHCTDinersClubCarteBlanche || cardType == SHCTDinersClubenRoute || cardType == SHCTDinersClubInternational || cardType == SHCTDinersClubUnitedStatesCanada) {
                numLength = 14;
            }

            // For DinersClubCarteBlanche card, the length may be 16.
            if (numLength == cardNum.length || cardType == SHCTDinersClubCarteBlanche || cardType == SHCTDinersClubInternational) {
                return cardType;
            }
        }
    }

    return SHCTUnknown;
}

有几行我无法找到 Swift 的等价物 for is

const char *s = [cardNum UTF8String];

有没有我可以用来将字符串转换为 UTF-8 的 Swift 函数

n = n * 10 + (s[j] - '0');

我如何在 swift 中表示字符“0”。我可以使用“-”操作数吗?

如有任何指点,我们将不胜感激。

最佳答案

试试这个:

let s = cardNum.cStringUsingEncoding(NSUTF8StringEncoding)! // s is an Array<Int8>
...
let CHAR_ZERO : Int8 = 48
n = n * 10 + (s[j] - CHAR_ZERO);

在 Swift 的 ASCII 表中将一个字符转换成它的整数值是很麻烦的。因此,您不妨将其定义为整数常量。

编辑:如果您想要一种更安全的解包方式:

let s : Array<Int8>
if cardNum.canBeConvertedToEncoding(NSUTF8StringEncoding) {
    s = cardNum.cStringUsingEncoding(NSUTF8StringEncoding)!
} else {
    s = []
    // Handle error
}

关于ios - 将 Swift String 转换为 UTF-8 并使用 char 的 ASCII 值进行算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32849592/

相关文章:

iphone - 当应用程序处于后台时,UILocalNotification 未显示在通知中心

objective-c - 无法弄清楚这个动态类型的事情

string - 批处理文件: Find if substring is in string (not in a file) Part 2 - Using Variables

php - Mysql中如何处理带有内嵌变量的字符串

java - 检查一个字符串是否可以在没有 try-catch 的情况下解析为 Long?

ios - 捕获 swift 和 core 图形的要点

ios - 在 navigationController 中呈现 modalviewController 后,推送和弹出动画会损坏

ios - 释放 CGMutablePathRef 对象的正确方法

ios - 如何为iOS正确构建Swift框架

ios - 二进制表达式 ('int' 和 'NSString' 的无效操作数)