Skip to content

Commit 9326a69

Browse files
sashabelonogovparkera
authored andcommitted
[SR-6139] Implement NSString.copy() method (#1291)
1 parent b21a90f commit 9326a69

File tree

3 files changed

+23
-7
lines changed

3 files changed

+23
-7
lines changed

Foundation/NSString.swift

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,15 @@ open class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSC
231231
}
232232

233233
open func copy(with zone: NSZone? = nil) -> Any {
234-
return self
234+
if type(of: self) === NSString.self {
235+
return self
236+
}
237+
let characters = UnsafeMutablePointer<unichar>.allocate(capacity: length)
238+
getCharacters(characters, range: NSMakeRange(0, length))
239+
let result = NSString(characters: characters, length: length)
240+
characters.deinitialize()
241+
characters.deallocate(capacity: length)
242+
return result
235243
}
236244

237245
open override func mutableCopy() -> Any {

TestFoundation/TestNSArray.swift

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -93,12 +93,9 @@ class TestNSArray : XCTestCase {
9393

9494
XCTAssertEqual(array1[0] as! String, "foo")
9595
XCTAssertEqual(array2[0] as! String, "foo")
96-
97-
// Disable this test for now as it fails, althought it works against Darwin Foundation.
98-
// The test may not acutally be correct anyway.
99-
//foo.append("1")
100-
//XCTAssertEqual(array1[0] as! String, "foo1")
101-
//XCTAssertEqual(array2[0] as! String, "foo")
96+
foo.append("1")
97+
XCTAssertEqual(array1[0] as! String, "foo1")
98+
XCTAssertEqual(array2[0] as! String, "foo")
10299
}
103100

104101
func test_enumeration() {

TestFoundation/TestNSString.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ class TestNSString : XCTestCase {
100100
("test_replacingOccurrences", test_replacingOccurrences),
101101
("test_getLineStart", test_getLineStart),
102102
("test_substringWithRange", test_substringWithRange),
103+
("test_createCopy", test_createCopy),
103104
]
104105
}
105106

@@ -1196,6 +1197,16 @@ class TestNSString : XCTestCase {
11961197
let s6 = NSString(string: "Beyonce\u{301} and Tay")
11971198
XCTAssertEqual(s6.substring(with: NSMakeRange(7, 9)), "\u{301} and Tay")
11981199
}
1200+
1201+
func test_createCopy() {
1202+
let string: NSMutableString = "foo"
1203+
let stringCopy = string.copy() as! NSString
1204+
XCTAssertEqual(string, stringCopy)
1205+
string.append("bar")
1206+
XCTAssertNotEqual(string, stringCopy)
1207+
XCTAssertEqual(string, "foobar")
1208+
XCTAssertEqual(stringCopy, "foo")
1209+
}
11991210
}
12001211

12011212
struct ComparisonTest {

0 commit comments

Comments
 (0)