初始化变量并在for循环中更改其值后访问它

时间:2014-08-30 05:59:54

标签: objective-c swift

我正在尝试将这个Objective-C代码翻译成Swift:

- (void) performActivity{
NSMutableString *reversedStrings = [[NSMutableString alloc] init];
for (NSString *string in self.activityItems){
    [reversedStrings appendString:[self reverseOfString:string]];
    [reversedStrings appendString:@"\n"];
}
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Reversed"
                                                    message:reversedStrings
                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
[alertView show];

}

我的Swift代码是:

override func performActivity() {

    var reversedStrings = String()

    for string in activityItems{

        reversedStrings += reverseOfString(string)
        reversedStrings += "\n"
    }

    var alert = UIAlertView(title: "Reversed",
        message: reversedStrings,
        delegate: self,
        cancelButtonTitle: "Cancel",
        otherButtonTitles: "Ok")

    alert.show()
}

但是我的警报中的消息仍然是空字符串。如何访问reversStrings,这是for循环的结果?提前感谢您的答案。

1 个答案:

答案 0 :(得分:2)

reverseOfString()的实施很可能无法正常运作。这是一个有效的解决方案:

var reversedStrings = String()

for string in activityItems{

    reversedStrings += string.reverse()
    reversedStrings += "\n"
}

使用实现String方法的reverse扩展程序:

extension String {
    func reverse() -> String {
        var result = ""

        for character in self {
            result = "\(character)" + result
        }

        return result
    }
}