Swift学习笔记 - 字符串
1. 不可变字符串
Objective-C:
NSString *string1 = @"Hello World!";
Swift:
let string1 = "Hello world!"
2. 可变字符串
Objective-C:
NSMutableString *string2 = [NSMutableString new]; NSMutableString *string3 = [@"" mutableCopy];
Swift:
var string2 = String() var string3 = ""
3. 输出
Objective-C:
NSLog(@"%lu", (unsigned long)string1.length); // Prints "12" NSLog(@"%i", !string2.length); // Prints "1" NSLog(@"%i", [string1 hasPrefix:@"Hello"]); // Prints "1" NSLog(@"%i", [string1 hasSuffix:@"earth!"]);// Prints "0"
Swift:
println(string1.utf16Count) // Prints "12" println(countElements(string1)) // Prints "12" println(string2.isEmpty) // Prints "true" println(string1.hasPrefix("Hello")) // Prints true println(string1.hasSuffix("earth!")) // Prints false
4. 比较
Objective-C:
// Prints "string2 equals string3" if ([string2 isEqualToString:string3]) { NSLog(@"string2 equals string3"); }
Swift:
// Prints "string2 equals string3" if string2 == string3 { println("string2 equals string3") }
5. 转换
Objective-C:
NSString *fiveString = [@5 stringValue]; // "5" NSInteger five = [fiveString integerValue];
Swift:
let fiveString = "\(5)" // "5" let five = fiveString.toInt()! let pi = Double((π as NSString).doubleValue) // 3.14
6. Copy and Mutable Copy
Objective-C:
NSMutableString *string4 = [string1 mutableCopy]; [string4 appendFormat:@"Am I alone?"]; NSLog(@"%@", string1); // Prints "Hello world!" NSLog(@"%@", string4); // Prints "Hello world! Am I alone?" NSMutableString *string5 = string4; [string5 replaceCharactersInRange:NSMakeRange(13, 10) withString:@"How do you like me now"]; // Prints "Hello world! How do you like me now?" if ([string4 isEqualToString:string5]) { NSLog(@"%@", string5); } NSMutableString *tempHigh = [@"85" mutableCopy]; NSMutableString *tempLow = [@"70" mutableCopy]; NSString *degreeF = @"\u2109"; [tempHigh appendString:degreeF]; [tempLow appendString:degreeF]; // Prints "High/Low: 85°F/70°F" NSLog(@"High/Low: %@/%@", tempHigh, tempLow);
Swift:
var string4 = string1 string4 += " Am I alone?" println(string1) // Prints "Hello world!" println(string4) // Prints "Hello world! Am I alone?" var string5 = string4 let startIndex = advance(string5.startIndex, 13) string5.replaceRange(startIndex..<string5.endIndex, with: "How do you like me now?") // Prints "Hello world! How do you like me now?" if string4 != string5 { println(string5) } var tempHigh = "85" var tempLow = "70" let degreeF: Character = "\u{2109}" tempHigh.append(degreeF) tempLow.append("\u{2109}" as Character) // Prints "High/Low: 85°F/70°F" println("High/Low: \(tempHigh)/\(tempLow)")
技术改变世界