Skip to content

[gardening] Use optional binding #1358

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 12, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions Foundation/Data.swift
Original file line number Diff line number Diff line change
Expand Up @@ -343,8 +343,8 @@ public final class _DataStorage {
let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4)
if allocateCleared && tryCalloc {
newBytes = _DataStorage.allocate(newCapacity, true)
if newBytes != nil {
_DataStorage.move(newBytes!, _bytes!, origLength)
if let newBytes = newBytes {
_DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
Expand All @@ -353,8 +353,8 @@ public final class _DataStorage {
allocateCleared = false
if _deallocator != nil {
newBytes = _DataStorage.allocate(newCapacity, true)
if newBytes != nil {
_DataStorage.move(newBytes!, _bytes!, origLength)
if let newBytes = newBytes {
_DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
_deallocator = nil
}
Expand All @@ -369,8 +369,8 @@ public final class _DataStorage {
allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity)
if allocateCleared && tryCalloc {
newBytes = _DataStorage.allocate(newCapacity, true)
if newBytes != nil {
_DataStorage.move(newBytes!, _bytes!, origLength)
if let newBytes = newBytes {
_DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
Expand Down Expand Up @@ -619,8 +619,8 @@ public final class _DataStorage {
memmove(mutableBytes! + start + replacementLength, mutableBytes! + start + length, currentLength - start - length)
}
if replacementLength != 0 {
if replacementBytes != nil {
memmove(mutableBytes! + start, replacementBytes!, replacementLength)
if let replacementBytes = replacementBytes {
memmove(mutableBytes! + start, replacementBytes, replacementLength)
} else {
memset(mutableBytes! + start, 0, replacementLength)
}
Expand Down
10 changes: 4 additions & 6 deletions Foundation/FileManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -296,15 +296,13 @@ open class FileManager : NSObject {
result[.systemNumber] = NSNumber(value: UInt64(s.st_dev))
result[.systemFileNumber] = NSNumber(value: UInt64(s.st_ino))

let pwd = getpwuid(s.st_uid)
if pwd != nil && pwd!.pointee.pw_name != nil {
let name = String(cString: pwd!.pointee.pw_name)
if let pwd = getpwuid(s.st_uid), pwd.pointee.pw_name != nil {
let name = String(cString: pwd.pointee.pw_name)
result[.ownerAccountName] = name
}

let grd = getgrgid(s.st_gid)
if grd != nil && grd!.pointee.gr_name != nil {
let name = String(cString: grd!.pointee.gr_name)
if let grd = getgrgid(s.st_gid), grd.pointee.gr_name != nil {
let name = String(cString: grd.pointee.gr_name)
result[.groupOwnerAccountName] = name
}

Expand Down
4 changes: 2 additions & 2 deletions Foundation/NSCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ open class NSCache<KeyType : AnyObject, ObjectType : AnyObject> : NSObject {
return
}

while currentElement.nextByCost != nil && currentElement.nextByCost!.cost < entry.cost {
currentElement = currentElement.nextByCost!
while let nextByCost = currentElement.nextByCost, nextByCost.cost < entry.cost {
currentElement = nextByCost
}

// Insert entry between currentElement and nextElement
Expand Down
4 changes: 2 additions & 2 deletions Foundation/NSPathUtilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -475,8 +475,8 @@ public extension NSString {
break loop
}

if char != nil {
let lhs = caseSensitive ? char : String(char!).lowercased().first!
if let char = char {
let lhs = caseSensitive ? char : String(char).lowercased().first!
let rhs = caseSensitive ? c : String(c).lowercased().first!
if lhs != rhs {
break loop
Expand Down
4 changes: 2 additions & 2 deletions Foundation/NSString.swift
Original file line number Diff line number Diff line change
Expand Up @@ -699,7 +699,7 @@ extension NSString {
return
}
/* Find the starting point first */
if startPtr != nil {
if let startPtr = startPtr {
var start: Int = 0
if range.location == 0 {
start = 0
Expand All @@ -723,7 +723,7 @@ extension NSString {
buf.rewind()
}
}
startPtr!.pointee = start
startPtr.pointee = start
}
}

Expand Down
4 changes: 2 additions & 2 deletions Foundation/NSStringAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1471,8 +1471,8 @@ extension StringProtocol where Index == String.Index {
tokenRanges: $0) as NSArray
}

if nsTokenRanges != nil {
tokenRanges?.pointee = (nsTokenRanges! as [AnyObject]).map {
if let nsTokenRanges = nsTokenRanges {
tokenRanges?.pointee = (nsTokenRanges as [AnyObject]).map {
self._range($0.rangeValue)
}
}
Expand Down
4 changes: 2 additions & 2 deletions Foundation/Process.swift
Original file line number Diff line number Diff line change
Expand Up @@ -308,9 +308,9 @@ open class Process: NSObject {

// If a termination handler has been set, invoke it on a background thread

if process.terminationHandler != nil {
if let terminationHandler = process.terminationHandler {
let thread = Thread {
process.terminationHandler!(process)
terminationHandler(process)
}
thread.start()
}
Expand Down
5 changes: 2 additions & 3 deletions Foundation/String.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,8 @@ extension String : _ObjectTypeBridgeable {
result = source._storage
} else if type(of: source) == _NSCFString.self {
let cf = unsafeBitCast(source, to: CFString.self)
let str = CFStringGetCStringPtr(cf, CFStringEncoding(kCFStringEncodingUTF8))
if str != nil {
result = String(cString: str!)
if let str = CFStringGetCStringPtr(cf, CFStringEncoding(kCFStringEncodingUTF8)) {
result = String(cString: str)
} else {
let length = CFStringGetLength(cf)
let buffer = UnsafeMutablePointer<UniChar>.allocate(capacity: length)
Expand Down
6 changes: 3 additions & 3 deletions Foundation/XMLParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -291,10 +291,10 @@ internal func _NSXMLParserStartElementNs(_ ctx: _CFXMLInterface, localname: Unsa
// idx+3 = value, i+4 = endvalue
// By using XML_PARSE_NOENT the attribute value string will already have entities resolved
var attributeValue = ""
if attributes[idx + 3] != nil && attributes[idx + 4] != nil {
let numBytesWithoutTerminator = attributes[idx + 4]! - attributes[idx + 3]!
if let value = attributes[idx + 3], let endvalue = attributes[idx + 4] {
let numBytesWithoutTerminator = endvalue - value
if numBytesWithoutTerminator > 0 {
let buffer = UnsafeBufferPointer(start: attributes[idx + 3]!,
let buffer = UnsafeBufferPointer(start: value,
count: numBytesWithoutTerminator)
attributeValue = String._fromCodeUnitSequence(UTF8.self,
input: buffer)!
Expand Down
23 changes: 10 additions & 13 deletions TestFoundation/TestJSONSerialization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -757,15 +757,14 @@ extension TestJSONSerialization {
XCTFail("Unable to convert string to data")
return
}
let filePath = createTestFile("TestJSON.txt",_contents: data)
if filePath != nil {
let fileStream: InputStream = InputStream(fileAtPath: filePath!)!
if let filePath = createTestFile("TestJSON.txt",_contents: data) {
let fileStream: InputStream = InputStream(fileAtPath: filePath)!
fileStream.open()
let resultRead = try JSONSerialization.jsonObject(with: fileStream, options: [])
let result = resultRead as? [String: Any]
XCTAssertEqual(result?.count, 0)
fileStream.close()
removeTestFile(filePath!)
removeTestFile(filePath)
}
} catch {
XCTFail("Error thrown: \(error)")
Expand All @@ -780,14 +779,13 @@ extension TestJSONSerialization {
XCTFail("Unable to convert string to data")
return
}
let filePath = createTestFile("TestJSON.txt",_contents: data)
if filePath != nil {
let url = URL(fileURLWithPath: filePath!)
if let filePath = createTestFile("TestJSON.txt",_contents: data) {
let url = URL(fileURLWithPath: filePath)
let inputStream: InputStream = InputStream(url: url)!
inputStream.open()
let result = try JSONSerialization.jsonObject(with: inputStream, options: []) as? [Any]
inputStream.close()
removeTestFile(filePath!)
removeTestFile(filePath)
XCTAssertEqual(result?[0] as? Bool, true)
XCTAssertEqual(result?[1] as? Bool, false)
XCTAssertEqual(result?[2] as? String, "hello")
Expand Down Expand Up @@ -1387,14 +1385,13 @@ extension TestJSONSerialization {
func test_jsonObjectToOutputStreamFile() {
let dict = ["a":["b":1]]
do {
let filePath = createTestFile("TestFileOut.txt",_contents: Data(capacity: 128))
if filePath != nil {
let outputStream = OutputStream(toFileAtPath: filePath!, append: true)
if let filePath = createTestFile("TestFileOut.txt",_contents: Data(capacity: 128)) {
let outputStream = OutputStream(toFileAtPath: filePath, append: true)
outputStream?.open()
let result = try JSONSerialization.writeJSONObject(dict, toStream: outputStream!, options: [])
outputStream?.close()
if(result > -1) {
let fileStream: InputStream = InputStream(fileAtPath: filePath!)!
let fileStream: InputStream = InputStream(fileAtPath: filePath)!
var buffer = [UInt8](repeating: 0, count: 20)
fileStream.open()
if fileStream.hasBytesAvailable {
Expand All @@ -1404,7 +1401,7 @@ extension TestJSONSerialization {
XCTAssertEqual(NSString(bytes: buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue), "{\"a\":{\"b\":1}}")
}
}
removeTestFile(filePath!)
removeTestFile(filePath)
} else {
XCTFail("Unable to create temp file")
}
Expand Down
134 changes: 67 additions & 67 deletions TestFoundation/TestStream.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,56 +54,56 @@ class TestStream : XCTestCase {
func test_InputStreamWithUrl() {
let message: NSString = "Hello, playground"
let messageData: Data = message.data(using: String.Encoding.utf8.rawValue)!
guard let testFile = createTestFile("testFile_in.txt", _contents: messageData) else {
XCTFail("Unable to create temp file")
return
}

//Initialiser with url
let testFile = createTestFile("testFile_in.txt", _contents: messageData)
if testFile != nil {
let url = URL(fileURLWithPath: testFile!)
let urlStream: InputStream = InputStream(url: url)!
XCTAssertEqual(Stream.Status.notOpen, urlStream.streamStatus)
urlStream.open()
XCTAssertEqual(Stream.Status.open, urlStream.streamStatus)
var buffer = [UInt8](repeating: 0, count: 20)
if urlStream.hasBytesAvailable {
let result :Int = urlStream.read(&buffer, maxLength: buffer.count)
urlStream.close()
XCTAssertEqual(Stream.Status.closed, urlStream.streamStatus)
XCTAssertEqual(messageData.count, result)
if(result > 0) {
let output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
XCTAssertEqual(message, output!)
}
let url = URL(fileURLWithPath: testFile)
let urlStream: InputStream = InputStream(url: url)!
XCTAssertEqual(Stream.Status.notOpen, urlStream.streamStatus)
urlStream.open()
XCTAssertEqual(Stream.Status.open, urlStream.streamStatus)
var buffer = [UInt8](repeating: 0, count: 20)
if urlStream.hasBytesAvailable {
let result :Int = urlStream.read(&buffer, maxLength: buffer.count)
urlStream.close()
XCTAssertEqual(Stream.Status.closed, urlStream.streamStatus)
XCTAssertEqual(messageData.count, result)
if(result > 0) {
let output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
XCTAssertEqual(message, output!)
}
removeTestFile(testFile!)
} else {
XCTFail("Unable to create temp file")
}
removeTestFile(testFile)
}

func test_InputStreamWithFile() {
let message: NSString = "Hello, playground"
let messageData: Data = message.data(using: String.Encoding.utf8.rawValue)!
guard let testFile = createTestFile("testFile_in.txt", _contents: messageData) else {
XCTFail("Unable to create temp file")
return
}

//Initialiser with file
let testFile = createTestFile("testFile_in.txt", _contents: messageData)
if testFile != nil {
let fileStream: InputStream = InputStream(fileAtPath: testFile!)!
XCTAssertEqual(Stream.Status.notOpen, fileStream.streamStatus)
fileStream.open()
XCTAssertEqual(Stream.Status.open, fileStream.streamStatus)
var buffer = [UInt8](repeating: 0, count: 20)
if fileStream.hasBytesAvailable {
let result: Int = fileStream.read(&buffer, maxLength: buffer.count)
fileStream.close()
XCTAssertEqual(Stream.Status.closed, fileStream.streamStatus)
XCTAssertEqual(messageData.count, result)
if(result > 0){
let output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
XCTAssertEqual(message, output!)
}
let fileStream: InputStream = InputStream(fileAtPath: testFile)!
XCTAssertEqual(Stream.Status.notOpen, fileStream.streamStatus)
fileStream.open()
XCTAssertEqual(Stream.Status.open, fileStream.streamStatus)
var buffer = [UInt8](repeating: 0, count: 20)
if fileStream.hasBytesAvailable {
let result: Int = fileStream.read(&buffer, maxLength: buffer.count)
fileStream.close()
XCTAssertEqual(Stream.Status.closed, fileStream.streamStatus)
XCTAssertEqual(messageData.count, result)
if(result > 0){
let output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
XCTAssertEqual(message, output!)
}
removeTestFile(testFile!)
} else {
XCTFail("Unable to create temp file")
}
removeTestFile(testFile)
}

func test_InputStreamHasBytesAvailable() {
Expand All @@ -125,22 +125,22 @@ class TestStream : XCTestCase {
}

func test_outputStreamCreationToFile() {
let filePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 256))
if filePath != nil {
let outputStream = OutputStream(toFileAtPath: filePath!, append: true)
XCTAssertEqual(Stream.Status.notOpen, outputStream!.streamStatus)
var myString = "Hello world!"
let encodedData = [UInt8](myString.utf8)
outputStream?.open()
XCTAssertEqual(Stream.Status.open, outputStream!.streamStatus)
let result: Int? = outputStream?.write(encodedData, maxLength: encodedData.count)
outputStream?.close()
XCTAssertEqual(myString.count, result)
XCTAssertEqual(Stream.Status.closed, outputStream!.streamStatus)
removeTestFile(filePath!)
} else {
guard let filePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 256)) else {
XCTFail("Unable to create temp file");
return
}

let outputStream = OutputStream(toFileAtPath: filePath, append: true)
XCTAssertEqual(Stream.Status.notOpen, outputStream!.streamStatus)
var myString = "Hello world!"
let encodedData = [UInt8](myString.utf8)
outputStream?.open()
XCTAssertEqual(Stream.Status.open, outputStream!.streamStatus)
let result: Int? = outputStream?.write(encodedData, maxLength: encodedData.count)
outputStream?.close()
XCTAssertEqual(myString.count, result)
XCTAssertEqual(Stream.Status.closed, outputStream!.streamStatus)
removeTestFile(filePath)
}

func test_outputStreamCreationToBuffer() {
Expand All @@ -159,22 +159,22 @@ class TestStream : XCTestCase {
}

func test_outputStreamCreationWithUrl() {
let filePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 256))
if filePath != nil {
let outputStream = OutputStream(url: URL(fileURLWithPath: filePath!), append: true)
XCTAssertEqual(Stream.Status.notOpen, outputStream!.streamStatus)
var myString = "Hello world!"
let encodedData = [UInt8](myString.utf8)
outputStream!.open()
XCTAssertEqual(Stream.Status.open, outputStream!.streamStatus)
let result: Int? = outputStream?.write(encodedData, maxLength: encodedData.count)
outputStream?.close()
XCTAssertEqual(myString.count, result)
XCTAssertEqual(Stream.Status.closed, outputStream!.streamStatus)
removeTestFile(filePath!)
} else {
guard let filePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 256)) else {
XCTFail("Unable to create temp file");
return
}

let outputStream = OutputStream(url: URL(fileURLWithPath: filePath), append: true)
XCTAssertEqual(Stream.Status.notOpen, outputStream!.streamStatus)
var myString = "Hello world!"
let encodedData = [UInt8](myString.utf8)
outputStream!.open()
XCTAssertEqual(Stream.Status.open, outputStream!.streamStatus)
let result: Int? = outputStream?.write(encodedData, maxLength: encodedData.count)
outputStream?.close()
XCTAssertEqual(myString.count, result)
XCTAssertEqual(Stream.Status.closed, outputStream!.streamStatus)
removeTestFile(filePath)
}

func test_outputStreamCreationToMemory(){
Expand Down
Loading