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

时间:2021-04-07 20:26:16

I am trying to translate this Objective-C code into 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];

}

}

My Swift code is:

我的代码是:

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()
}

but the message in my alert is still the empty string. How can I access the reversedStrings, which is the result of the for loop? Thanks in advance for the answers.

但我的警告中的消息仍然是空字符串。如何访问反向字符串,这是for循环的结果?谢谢你的回答。

1 个解决方案

#1


2  

Most likely your implementation of reverseOfString() doesn't work correctly. Here is a working solution:

很可能您的reverseOfString()实现不正确。这里有一个可行的解决方案:

var reversedStrings = String()

for string in activityItems{

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

which uses a String extension implementing a reverse method:

使用字符串扩展实现反向方法:

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

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

        return result
    }
}

#1


2  

Most likely your implementation of reverseOfString() doesn't work correctly. Here is a working solution:

很可能您的reverseOfString()实现不正确。这里有一个可行的解决方案:

var reversedStrings = String()

for string in activityItems{

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

which uses a String extension implementing a reverse method:

使用字符串扩展实现反向方法:

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

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

        return result
    }
}