Skip to content

Use new shorthand syntax for unwrapping optionals #6329

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
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
2 changes: 1 addition & 1 deletion Sources/Basics/AuthorizationProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public class NetrcAuthorizationProvider: AuthorizationProvider, AuthorizationWri
let contents = try? self.fileSystem.readFileContents(self.path).contents
try self.fileSystem.writeFileContents(self.path) { stream in
// Write existing contents
if let contents = contents, !contents.isEmpty {
if let contents, !contents.isEmpty {
stream.write(contents)
stream.write("\n")
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/Basics/Concurrency/SendableBox.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ public actor SendableBox<Value: Sendable> {

extension SendableBox where Value == Int {
func increment() {
if let value = self.value {
if let value {
self.value = value + 1
}
}

func decrement() {
if let value = self.value {
if let value {
self.value = value - 1
}
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/Basics/FileSystem/VirtualFileSystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ public class VirtualFileSystem: FileSystem {
switch node {
case .directory(_, _, _): throw Errors.notAFile(path: path)
case .file(_, _, _, let contents):
if let contents = contents {
if let contents {
return ByteString(contents)
} else {
return ""
Expand Down
4 changes: 2 additions & 2 deletions Sources/Basics/HTTPClient/URLSessionHTTPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ private class DataTaskManager: NSObject, URLSessionDataDelegate {
guard let task = self.tasks.removeValue(forKey: task.taskIdentifier) else {
return
}
if let error = error {
if let error {
task.completionHandler(.failure(error))
} else if let response = task.response {
task.completionHandler(.success(response.response(body: task.buffer)))
Expand Down Expand Up @@ -294,7 +294,7 @@ private class DownloadTaskManager: NSObject, URLSessionDownloadDelegate {
}

do {
if let error = error {
if let error {
throw HTTPClientError.downloadError("\(error)")
} else if let error = task.moveFileError {
throw error
Expand Down
8 changes: 4 additions & 4 deletions Sources/Basics/SQLite.swift
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public final class SQLite {

sqlite3_free(query)

if let err = err {
if let err {
let errorString = String(cString: err)
sqlite3_free(err)
throw StringError(errorString)
Expand Down Expand Up @@ -286,7 +286,7 @@ public final class SQLite {
case "database or disk is full":
throw Errors.databaseFull
default:
if let prefix = prefix {
if let prefix {
description = "\(prefix): \(description)"
}
throw StringError(description)
Expand All @@ -309,8 +309,8 @@ private func sqlite_callback(
_ columns: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?,
_ columnNames: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?
) -> Int32 {
guard let ctx = ctx else { return 0 }
guard let columnNames = columnNames, let columns = columns else { return 0 }
guard let ctx else { return 0 }
guard let columnNames, let columns else { return 0 }
let numColumns = Int(numColumns)
var result: [SQLite.Column] = []

Expand Down
2 changes: 1 addition & 1 deletion Sources/Basics/SwiftVersion.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public struct SwiftVersion {
if self.isDevelopment {
result += "-dev"
}
if let buildIdentifier = self.buildIdentifier {
if let buildIdentifier {
result += " (" + buildIdentifier + ")"
}
return result
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ public final class ClangTargetBuildDescription {
// Include the path to the resource header unless the arguments are
// being evaluated for a C file. A C file cannot depend on the resource
// accessor header due to it exporting a Foundation type (`NSBundle`).
if let resourceAccessorHeaderFile = self.resourceAccessorHeaderFile, !isC {
if let resourceAccessorHeaderFile, !isC {
args += ["-include", resourceAccessorHeaderFile.pathString]
}

Expand Down Expand Up @@ -304,7 +304,7 @@ public final class ClangTargetBuildDescription {
/// Generate the resource bundle accessor, if appropriate.
private func generateResourceAccessor() throws {
// Only generate access when we have a bundle and ObjC files.
guard let bundlePath = self.bundlePath, clangTarget.sources.containsObjcFiles else { return }
guard let bundlePath, clangTarget.sources.containsObjcFiles else { return }

// Compute the basename of the bundle.
let bundleBasename = bundlePath.basename
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ public final class SwiftTargetBuildDescription {
self.toolsVersion = toolsVersion
self.buildParameters = buildParameters
// Unless mentioned explicitly, use the target type to determine if this is a test target.
if let testTargetRole = testTargetRole {
if let testTargetRole {
self.testTargetRole = testTargetRole
} else if target.type == .test {
self.testTargetRole = .default
Expand Down Expand Up @@ -336,7 +336,7 @@ public final class SwiftTargetBuildDescription {
/// Generate the resource bundle accessor, if appropriate.
private func generateResourceAccessor() throws {
// Do nothing if we're not generating a bundle.
guard let bundlePath = self.bundlePath else { return }
guard let bundlePath else { return }

let mainPathSubstitution: String
if self.buildParameters.triple.isWASI() {
Expand Down
4 changes: 2 additions & 2 deletions Sources/Build/BuildOperation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ public final class BuildOperation: PackageStructureDelegate, SPMBuildCore.BuildS
// Compiles a single plugin, emitting its output and throwing an error if it
// fails.
func compilePlugin(_ plugin: PluginDescription) throws {
guard let pluginConfiguration = self.pluginConfiguration else {
guard let pluginConfiguration else {
throw InternalError("unknown plugin script runner")
}
// Compile the plugin, getting back a PluginCompilationResult.
Expand Down Expand Up @@ -408,7 +408,7 @@ public final class BuildOperation: PackageStructureDelegate, SPMBuildCore.BuildS
let buildToolPluginInvocationResults: [ResolvedTarget: [BuildToolPluginInvocationResult]]
let prebuildCommandResults: [ResolvedTarget: [PrebuildCommandResult]]
// Invoke any build tool plugins in the graph to generate prebuild commands and build commands.
if let pluginConfiguration = self.pluginConfiguration {
if let pluginConfiguration {
let buildOperationForPluginDependencies = try BuildOperation(buildParameters: self.buildParameters.withDestination(self.buildParameters.hostTriple), cacheBuildManifest: false, packageGraphLoader: { return graph }, additionalFileRules: self.additionalFileRules, pkgConfigDirectories: self.pkgConfigDirectories, outputStream: self.outputStream, logLevel: self.logLevel, fileSystem: self.fileSystem, observabilityScope: self.observabilityScope)
buildToolPluginInvocationResults = try graph.invokeBuildToolPlugins(
outputDir: pluginConfiguration.workDirectory.appending("outputs"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -916,7 +916,7 @@ private struct CommandTaskTracker {
let fileNameStartIndex = command.description.index(after: lastDirectorySeparatorIndex)
let fileName = command.description[fileNameStartIndex...]

if let targetName = targetName {
if let targetName {
return "\(action) \(targetName) \(fileName)"
} else {
return "\(action) \(fileName)"
Expand Down
12 changes: 6 additions & 6 deletions Sources/Build/LLBuildManifestBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -292,10 +292,10 @@ extension LLBuildManifestBuilder {

// Check if an explicit pre-build dependency job has already been
// added as a part of this build.
if let uniqueDependencyTracker = uniqueExplicitDependencyTracker,
if let uniqueExplicitDependencyTracker,
job.isExplicitDependencyPreBuildJob
{
if try !uniqueDependencyTracker.registerExplicitDependencyBuildJob(job) {
if try !uniqueExplicitDependencyTracker.registerExplicitDependencyBuildJob(job) {
// This is a duplicate of a previously-seen identical job.
// Skip adding it to the manifest
continue
Expand Down Expand Up @@ -619,10 +619,10 @@ extension LLBuildManifestBuilder {
// Depend on the binary for executable targets.
if target.type == .executable {
// FIXME: Optimize.
let _product = try plan.graph.allProducts.first {
let product = try plan.graph.allProducts.first {
try $0.type == .executable && $0.executableTarget == target
}
if let product = _product {
if let product {
guard let planProduct = plan.productMap[product] else {
throw InternalError("unknown product \(product)")
}
Expand Down Expand Up @@ -855,8 +855,8 @@ extension LLBuildManifestBuilder {
// Add language standard flag if needed.
if let ext = path.source.extension {
for (standard, validExtensions) in standards {
if let languageStandard = standard, validExtensions.contains(ext) {
args += ["-std=\(languageStandard)"]
if let standard, validExtensions.contains(ext) {
args += ["-std=\(standard)"]
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/Commands/PackageTools/ArchiveSource.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ extension SwiftPackageTool {
let packageDirectory = try globalOptions.locations.packageDirectory ?? swiftTool.getPackageRoot()

let archivePath: AbsolutePath
if let output = output {
if let output {
archivePath = output
} else {
let graph = try swiftTool.loadPackageGraph()
Expand Down
2 changes: 1 addition & 1 deletion Sources/Commands/PackageTools/Learn.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ extension SwiftPackageTool {
.map { try AbsolutePath(validating: $0, relativeTo: directory) }
.filter { fileSystem.isFile($0) }

guard let fileExtension = fileExtension else {
guard let fileExtension else {
return files
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/Commands/PackageTools/ToolsVersionCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ struct ToolsVersionCommand: SwiftCommand {

var toolsVersionMode: ToolsVersionMode {
// TODO: enforce exclusivity
if let set = set {
if let set {
return .set(set)
} else if setCurrent {
return .setCurrent
Expand Down
4 changes: 2 additions & 2 deletions Sources/Commands/Snippets/CardStack.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ struct CardStack {
}

func askForLineInput(prompt: String?) -> String? {
if let prompt = prompt {
if let prompt {
print(brightBlack { prompt }.terminalString())
}
terminal.write(">>> ", inColor: .green, bold: true)
Expand Down Expand Up @@ -99,7 +99,7 @@ struct CardStack {
break askForLine
case let .pop(error):
cards.removeLast()
if let error = error {
if let error {
self.swiftTool.observabilityScope.emit(error)
needsToClearScreen = false
} else {
Expand Down
8 changes: 4 additions & 4 deletions Sources/Commands/SwiftBuildTool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@ struct BuildToolOptions: ParsableArguments {
func buildSubset(observabilityScope: ObservabilityScope) -> BuildSubset? {
var allSubsets: [BuildSubset] = []

if let productName = product {
allSubsets.append(.product(productName))
if let product {
allSubsets.append(.product(product))
}

if let targetName = target {
allSubsets.append(.target(targetName))
if let target {
allSubsets.append(.target(target))
}

if buildTests {
Expand Down
4 changes: 2 additions & 2 deletions Sources/Commands/SwiftTestTool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -668,13 +668,13 @@ final class TestRunner {
throw TestError.xctestNotAvailable
}
args = [xctestPath.pathString]
if let xctestArg = xctestArg {
if let xctestArg {
args += ["-XCTest", xctestArg]
}
args += [testPath.pathString]
#else
args += [testPath.description]
if let xctestArg = xctestArg {
if let xctestArg {
args += [xctestArg]
}
#endif
Expand Down
2 changes: 1 addition & 1 deletion Sources/Commands/Utilities/APIDigester.swift
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ public struct SwiftAPIDigester {
"-module", module
]
args.append(contentsOf: try buildPlan.createAPIToolCommonArgs(includeLibrarySearchPaths: false))
if let breakageAllowlistPath = breakageAllowlistPath {
if let breakageAllowlistPath {
args.append(contentsOf: ["-breakage-allowlist-path", breakageAllowlistPath.pathString])
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/Commands/Utilities/DescribedPackage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ public struct PlainTextEncoder {
private mutating func emit(_ key: CodingKey, _ value: String?) {
outputStream <<< String(repeating: " ", count: codingPath.count)
outputStream <<< displayName(for: key) <<< ":"
if let value = value { outputStream <<< " " <<< value }
if let value { outputStream <<< " " <<< value }
outputStream <<< "\n"
}
mutating func encodeNil(forKey key: Key) throws { emit(key, "nil") }
Expand Down
10 changes: 5 additions & 5 deletions Sources/CoreCommands/SwiftTool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,8 @@ extension SwiftCommand {
// wait for all observability items to process
swiftTool.waitForObservabilityEvents(timeout: .now() + 5)

if let error = toolError {
throw error
if let toolError {
throw toolError
}
}
}
Expand Down Expand Up @@ -150,8 +150,8 @@ extension AsyncSwiftCommand {
// wait for all observability items to process
swiftTool.waitForObservabilityEvents(timeout: .now() + 5)

if let error = toolError {
throw error
if let toolError {
throw toolError
}
}
}
Expand Down Expand Up @@ -690,7 +690,7 @@ public final class SwiftTool {
customLogLevel: Basics.Diagnostic.Severity? = .none,
customObservabilityScope: ObservabilityScope? = .none
) throws -> BuildSystem {
guard let buildSystemProvider = buildSystemProvider else {
guard let buildSystemProvider else {
fatalError("build system provider not initialized")
}

Expand Down
6 changes: 3 additions & 3 deletions Sources/CoreCommands/SwiftToolObservabilityHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ private struct InteractiveWriter {

/// Write the string to the contained terminal or stream.
func write(_ string: String, inColor color: TerminalController.Color = .noColor, bold: Bool = false) {
if let term = self.term {
if let term {
term.write(string, inColor: color, bold: bold)
} else {
string.write(to: stream)
Expand All @@ -190,7 +190,7 @@ private struct InteractiveWriter {
}

func format(_ string: String, inColor color: TerminalController.Color = .noColor, bold: Bool = false) -> String {
if let term = self.term {
if let term {
return term.wrap(string, inColor: color, bold: bold)
} else {
return string
Expand All @@ -202,7 +202,7 @@ private struct InteractiveWriter {
// we should remove this as we make use of the new scope and metadata to provide better contextual information
extension ObservabilityMetadata {
fileprivate var diagnosticPrefix: String? {
if let packageIdentity = self.packageIdentity {
if let packageIdentity {
return "'\(packageIdentity)'"
} else {
return .none
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,18 +87,18 @@ struct SetConfiguration: ConfigurationCommand {

let currentWorkingDirectory = fileSystem.currentWorkingDirectory

if let sdkRootPath = sdkRootPath {
if let sdkRootPath {
configuration.sdkRootPath = try AbsolutePath(validating: sdkRootPath, relativeTo: currentWorkingDirectory)
updatedProperties.append(CodingKeys.sdkRootPath.stringValue)
}

if let swiftResourcesPath = swiftResourcesPath {
if let swiftResourcesPath {
configuration.swiftResourcesPath =
try AbsolutePath(validating: swiftResourcesPath, relativeTo: currentWorkingDirectory)
updatedProperties.append(CodingKeys.swiftResourcesPath.stringValue)
}

if let swiftStaticResourcesPath = swiftStaticResourcesPath {
if let swiftStaticResourcesPath {
configuration.swiftResourcesPath =
try AbsolutePath(validating: swiftStaticResourcesPath, relativeTo: currentWorkingDirectory)
updatedProperties.append(CodingKeys.swiftStaticResourcesPath.stringValue)
Expand Down Expand Up @@ -147,7 +147,7 @@ struct SetConfiguration: ConfigurationCommand {

extension AbsolutePath {
fileprivate init(validating string: String, relativeTo basePath: AbsolutePath?) throws {
if let basePath = basePath {
if let basePath {
try self.init(validating: string, relativeTo: basePath)
} else {
try self.init(validating: string)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ extension DestinationCommand {
// wait for all observability items to process
observabilityHandler.wait(timeout: .now() + 5)

if let error = commandError {
throw error
if let commandError {
throw commandError
}
}
}
Loading