Skip to content

Commit

Permalink
[gardening] Use optional binding
Browse files Browse the repository at this point in the history
  • Loading branch information
ikesyo committed Dec 8, 2017
1 parent fdf6bb4 commit 30efb6f
Show file tree
Hide file tree
Showing 12 changed files with 53 additions and 65 deletions.
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
28 changes: 12 additions & 16 deletions TestFoundation/TestStream.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,8 @@ class TestStream : XCTestCase {
let message: NSString = "Hello, playground"
let messageData: Data = message.data(using: String.Encoding.utf8.rawValue)!
//Initialiser with url
let testFile = createTestFile("testFile_in.txt", _contents: messageData)
if testFile != nil {
let url = URL(fileURLWithPath: testFile!)
if let testFile = createTestFile("testFile_in.txt", _contents: messageData) {
let url = URL(fileURLWithPath: testFile)
let urlStream: InputStream = InputStream(url: url)!
XCTAssertEqual(Stream.Status.notOpen, urlStream.streamStatus)
urlStream.open()
Expand All @@ -73,7 +72,7 @@ class TestStream : XCTestCase {
XCTAssertEqual(message, output!)
}
}
removeTestFile(testFile!)
removeTestFile(testFile)
} else {
XCTFail("Unable to create temp file")
}
Expand All @@ -83,9 +82,8 @@ class TestStream : XCTestCase {
let message: NSString = "Hello, playground"
let messageData: Data = message.data(using: String.Encoding.utf8.rawValue)!
//Initialiser with file
let testFile = createTestFile("testFile_in.txt", _contents: messageData)
if testFile != nil {
let fileStream: InputStream = InputStream(fileAtPath: testFile!)!
if let testFile = createTestFile("testFile_in.txt", _contents: messageData) {
let fileStream: InputStream = InputStream(fileAtPath: testFile)!
XCTAssertEqual(Stream.Status.notOpen, fileStream.streamStatus)
fileStream.open()
XCTAssertEqual(Stream.Status.open, fileStream.streamStatus)
Expand All @@ -100,7 +98,7 @@ class TestStream : XCTestCase {
XCTAssertEqual(message, output!)
}
}
removeTestFile(testFile!)
removeTestFile(testFile)
} else {
XCTFail("Unable to create temp file")
}
Expand All @@ -125,9 +123,8 @@ 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)
if let filePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 256)) {
let outputStream = OutputStream(toFileAtPath: filePath, append: true)
XCTAssertEqual(Stream.Status.notOpen, outputStream!.streamStatus)
var myString = "Hello world!"
let encodedData = [UInt8](myString.utf8)
Expand All @@ -137,7 +134,7 @@ class TestStream : XCTestCase {
outputStream?.close()
XCTAssertEqual(myString.count, result)
XCTAssertEqual(Stream.Status.closed, outputStream!.streamStatus)
removeTestFile(filePath!)
removeTestFile(filePath)
} else {
XCTFail("Unable to create temp file");
}
Expand All @@ -159,9 +156,8 @@ 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)
if let filePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 256)) {
let outputStream = OutputStream(url: URL(fileURLWithPath: filePath), append: true)
XCTAssertEqual(Stream.Status.notOpen, outputStream!.streamStatus)
var myString = "Hello world!"
let encodedData = [UInt8](myString.utf8)
Expand All @@ -171,7 +167,7 @@ class TestStream : XCTestCase {
outputStream?.close()
XCTAssertEqual(myString.count, result)
XCTAssertEqual(Stream.Status.closed, outputStream!.streamStatus)
removeTestFile(filePath!)
removeTestFile(filePath)
} else {
XCTFail("Unable to create temp file");
}
Expand Down
10 changes: 4 additions & 6 deletions TestFoundation/XDGTestHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,14 @@ class XDGCheck {
.path: "/",
.domain: "example.com",
]
let simpleCookie = HTTPCookie(properties: properties)
guard simpleCookie != nil else {
guard let simpleCookie = HTTPCookie(properties: properties) else {
exit(HelperCheckStatus.cookieStorageNil.rawValue)
}
let rawValue = getenv("XDG_DATA_HOME")
guard rawValue != nil else {
guard let rawValue = getenv("XDG_DATA_HOME") else {
exit(HelperCheckStatus.fail.rawValue)
}
let xdg_data_home = String(utf8String: rawValue!)
storage.setCookie(simpleCookie!)
let xdg_data_home = String(utf8String: rawValue)
storage.setCookie(simpleCookie)
let fm = FileManager.default
let destPath = xdg_data_home! + "/xdgTestHelper/.cookies.shared"
var isDir: ObjCBool = false
Expand Down

0 comments on commit 30efb6f

Please sign in to comment.