我正在尝试将这个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循环的结果?提前感谢您的答案。
答案 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
}
}