Skip to content

Commit 392baef

Browse files
LucianoPAlmeidaCodaFi
authored andcommitted
[stdlib][Qol] SR-11295 Removing stdlib unnecessary coercions (#27165)
* Removing unnecessary casts from stdlib * Minor adjustments * [stdlib][qol] Clean up error variable assign NSError * Removing unnecessary coercions after removing DeclRefExpr restriction.
1 parent 975aa53 commit 392baef

23 files changed

+36
-41
lines changed

benchmark/single-source/ArrayOfGenericRef.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ class ConstructibleArray<T:Constructible> {
3434
array = [T]()
3535
array.reserveCapacity(1_000)
3636
for _ in 0...1_000 {
37-
array.append(T(e:e) as T)
37+
array.append(T(e:e))
3838
}
3939
}
4040
}

benchmark/single-source/ArrayOfRef.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ class ConstructibleArray<T:Constructible> {
3535
array = [T]()
3636
array.reserveCapacity(1_000)
3737
for _ in 0...1_000 {
38-
array.append(T(e:e) as T)
38+
array.append(T(e:e))
3939
}
4040
}
4141
}

benchmark/single-source/StringWalk.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ import TestsUtils
6666
let ascii =
6767
"siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig"
6868
let emoji = "👍👩‍👩‍👧‍👧👨‍👨‍👦‍👦🇺🇸🇨🇦🇲🇽👍🏻👍🏼👍🏽👍🏾👍🏿"
69-
let utf16 = emoji + "the quick brown fox" + String(emoji.reversed() as Array<Character>)
69+
let utf16 = emoji + "the quick brown fox" + String(emoji.reversed())
7070

7171
let japanese = "今回のアップデートでSwiftに大幅な改良が施され、安定していてしかも直感的に使うことができるAppleプラットフォーム向けプログラミング言語になりました。"
7272
let chinese = "Swift 是面向 Apple 平台的编程语言,功能强大且直观易用,而本次更新对其进行了全面优化。"

benchmark/single-source/StringWalk.swift.gyb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ import TestsUtils
6767
let ascii =
6868
"siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig"
6969
let emoji = "👍👩‍👩‍👧‍👧👨‍👨‍👦‍👦🇺🇸🇨🇦🇲🇽👍🏻👍🏼👍🏽👍🏾👍🏿"
70-
let utf16 = emoji + "the quick brown fox" + String(emoji.reversed() as Array<Character>)
70+
let utf16 = emoji + "the quick brown fox" + String(emoji.reversed())
7171

7272
let japanese = "今回のアップデートでSwiftに大幅な改良が施され、安定していてしかも直感的に使うことができるAppleプラットフォーム向けプログラミング言語になりました。"
7373
let chinese = "Swift 是面向 Apple 平台的编程语言,功能强大且直观易用,而本次更新对其进行了全面优化。"

stdlib/public/Darwin/CloudKit/CKRecord.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,17 +58,17 @@ extension CKRecord {
5858

5959
@available(swift 4.2)
6060
public enum SystemType {
61-
public static let userRecord: CKRecord.RecordType = __CKRecordTypeUserRecord as CKRecord.RecordType
61+
public static let userRecord: CKRecord.RecordType = __CKRecordTypeUserRecord
6262
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
63-
public static let share: CKRecord.RecordType = __CKRecordTypeShare as CKRecord.RecordType
63+
public static let share: CKRecord.RecordType = __CKRecordTypeShare
6464
}
6565

6666
@available(swift 4.2)
6767
public enum SystemFieldKey {
6868
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
69-
public static let parent: CKRecord.FieldKey = __CKRecordParentKey as CKRecord.RecordType
69+
public static let parent: CKRecord.FieldKey = __CKRecordParentKey
7070
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
71-
public static let share: CKRecord.FieldKey = __CKRecordShareKey as CKRecord.RecordType
71+
public static let share: CKRecord.FieldKey = __CKRecordShareKey
7272
}
7373
}
7474

stdlib/public/Darwin/CloudKit/CKShare.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@
1717
extension CKShare {
1818
@available(swift 4.2)
1919
public enum SystemFieldKey {
20-
public static let title: CKRecord.FieldKey = __CKShareTitleKey as CKRecord.FieldKey
21-
public static let thumbnailImageData: CKRecord.FieldKey = __CKShareThumbnailImageDataKey as CKRecord.FieldKey
22-
public static let shareType: CKRecord.FieldKey = __CKShareTypeKey as CKRecord.FieldKey
20+
public static let title: CKRecord.FieldKey = __CKShareTitleKey
21+
public static let thumbnailImageData: CKRecord.FieldKey = __CKShareThumbnailImageDataKey
22+
public static let shareType: CKRecord.FieldKey = __CKShareTypeKey
2323
}
2424
}
2525

stdlib/public/Darwin/CloudKit/TypealiasStrings.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ extension CKOperation {
4343
*/
4444
@available(swift 4.2)
4545
public var operationID: CKOperation.ID {
46-
get { return self.__operationID as CKOperation.ID }
46+
get { return self.__operationID }
4747
}
4848
}
4949

stdlib/public/Darwin/CoreMedia/CMTime.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ extension CMTime {
6262
}
6363

6464
public var seconds: Double {
65-
return CMTimeGetSeconds(self) as Double
65+
return CMTimeGetSeconds(self)
6666
}
6767

6868
public func convertScale(_ newTimescale: Int32, method: CMTimeRoundingMethod)

stdlib/public/Darwin/Foundation/DateComponents.swift

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -204,11 +204,7 @@ public struct DateComponents : ReferenceConvertible, Hashable, Equatable, _Mutab
204204

205205
/// Returns a `Date` calculated from the current components using the `calendar` property.
206206
public var date: Date? {
207-
if let d = _handle.map({$0.date}) {
208-
return d as Date
209-
} else {
210-
return nil
211-
}
207+
return _handle.map { $0.date }
212208
}
213209

214210
// MARK: - Generic Setter/Getters

stdlib/public/Darwin/Foundation/FileManager.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ extension FileManager {
4848
return __NSFileManagerEnumeratorAtURL(self, url, keys, mask, { (url, error) in
4949
var errorResult = true
5050
if let h = handler {
51-
errorResult = h(url as URL, error)
51+
errorResult = h(url, error)
5252
}
5353
return errorResult
5454
})

stdlib/public/Darwin/Foundation/IndexSet.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -600,7 +600,7 @@ public struct IndexSet : ReferenceConvertible, Equatable, BidirectionalCollectio
600600
stop.pointee = true
601601
return false
602602
}
603-
}) as IndexSet
603+
})
604604
if let e = error {
605605
throw e
606606
} else {

stdlib/public/Darwin/Foundation/NSCoder.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ extension NSCoder {
5353
if let theClasses = classes {
5454
classesAsNSObjects = NSSet(array: theClasses.map { $0 as AnyObject })
5555
}
56-
return __NSCoderDecodeObjectOfClassesForKey(self, classesAsNSObjects, key, nil).map { $0 as Any }
56+
return __NSCoderDecodeObjectOfClassesForKey(self, classesAsNSObjects, key, nil).map { $0 }
5757
}
5858

5959
@nonobjc
@@ -62,7 +62,7 @@ extension NSCoder {
6262
var error: NSError?
6363
let result = __NSCoderDecodeObject(self, &error)
6464
try resolveError(error)
65-
return result.map { $0 as Any }
65+
return result.map { $0 }
6666
}
6767

6868
@available(*, unavailable, renamed: "decodeTopLevelObject(forKey:)")
@@ -125,7 +125,7 @@ extension NSCoder {
125125
}
126126
let result = __NSCoderDecodeObjectOfClassesForKey(self, classesAsNSObjects, key, &error)
127127
try resolveError(error)
128-
return result.map { $0 as Any }
128+
return result.map { $0 }
129129
}
130130
}
131131

stdlib/public/Darwin/Foundation/NSDictionary.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ extension Dictionary {
6464
extension Dictionary : _ObjectiveCBridgeable {
6565
@_semantics("convertToObjectiveC")
6666
public func _bridgeToObjectiveC() -> NSDictionary {
67-
return unsafeBitCast(_bridgeToObjectiveCImpl() as AnyObject,
67+
return unsafeBitCast(_bridgeToObjectiveCImpl(),
6868
to: NSDictionary.self)
6969
}
7070

stdlib/public/Darwin/Foundation/NSError.swift

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -234,8 +234,7 @@ public func _getErrorDefaultUserInfo<T: Error>(_ error: T)
234234
if domain != NSCocoaErrorDomain {
235235
_errorDomainUserInfoProviderQueue.sync {
236236
if NSError.userInfoValueProvider(forDomain: domain) != nil { return }
237-
NSError.setUserInfoValueProvider(forDomain: domain) { (nsError, key) in
238-
let error = nsError as Error
237+
NSError.setUserInfoValueProvider(forDomain: domain) { (error, key) in
239238

240239
switch key {
241240
case NSLocalizedDescriptionKey:

stdlib/public/Darwin/Foundation/NSSet.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ extension NSOrderedSet : Sequence {
5555
extension Set : _ObjectiveCBridgeable {
5656
@_semantics("convertToObjectiveC")
5757
public func _bridgeToObjectiveC() -> NSSet {
58-
return unsafeBitCast(_bridgeToObjectiveCImpl() as AnyObject, to: NSSet.self)
58+
return unsafeBitCast(_bridgeToObjectiveCImpl(), to: NSSet.self)
5959
}
6060

6161
public static func _forceBridgeFromObjectiveC(_ s: NSSet, result: inout Set?) {

stdlib/public/Darwin/Foundation/NSStringAPI.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,7 @@ extension String {
353353
usedEncoding: inout Encoding
354354
) throws {
355355
var enc: UInt = 0
356-
let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc)
356+
let ns = try NSString(contentsOf: url, usedEncoding: &enc)
357357
usedEncoding = Encoding(rawValue: enc)
358358
self = String._unconditionallyBridgeFromObjectiveC(ns)
359359
}
@@ -566,7 +566,7 @@ extension StringProtocol where Index == String.Index {
566566
/// Case transformations aren’t guaranteed to be symmetrical or to produce
567567
/// strings of the same lengths as the originals.
568568
public var capitalized: String {
569-
return _ns.capitalized as String
569+
return _ns.capitalized
570570
}
571571

572572
// @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0);
@@ -583,7 +583,7 @@ extension StringProtocol where Index == String.Index {
583583
/// Returns a capitalized representation of the string
584584
/// using the specified locale.
585585
public func capitalized(with locale: Locale?) -> String {
586-
return _ns.capitalized(with: locale) as String
586+
return _ns.capitalized(with: locale)
587587
}
588588

589589
// - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
@@ -1166,7 +1166,7 @@ extension StringProtocol where Index == String.Index {
11661166
/// locale.
11671167
@available(macOS 10.11, iOS 9.0, *)
11681168
public var localizedUppercase: String {
1169-
return _ns.localizedUppercase as String
1169+
return _ns.localizedUppercase
11701170
}
11711171

11721172
// - (NSString *)uppercaseStringWithLocale:(Locale *)locale

stdlib/public/Darwin/Foundation/Progress.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ extension Progress {
1717
public var estimatedTimeRemaining: TimeInterval? {
1818
get {
1919
guard let v = self.__estimatedTimeRemaining else { return nil }
20-
return v.doubleValue as TimeInterval
20+
return v.doubleValue
2121
}
2222
set {
2323
guard let nv = newValue else {

stdlib/public/Darwin/Foundation/String.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ extension String : _ObjectiveCBridgeable {
3232
// This method should not do anything extra except calling into the
3333
// implementation inside core. (These two entry points should be
3434
// equivalent.)
35-
return unsafeBitCast(_bridgeToObjectiveCImpl() as AnyObject, to: NSString.self)
35+
return unsafeBitCast(_bridgeToObjectiveCImpl(), to: NSString.self)
3636
}
3737

3838
public static func _forceBridgeFromObjectiveC(

stdlib/public/Darwin/Foundation/URL.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1090,7 +1090,7 @@ public struct URL : ReferenceConvertible, Equatable {
10901090
/// Returns bookmark data for the URL, created with specified options and resource values.
10911091
public func bookmarkData(options: BookmarkCreationOptions = [], includingResourceValuesForKeys keys: Set<URLResourceKey>? = nil, relativeTo url: URL? = nil) throws -> Data {
10921092
let result = try _url.bookmarkData(options: options, includingResourceValuesForKeys: keys.flatMap { Array($0) }, relativeTo: url)
1093-
return result as Data
1093+
return result
10941094
}
10951095

10961096
/// Returns the resource values for properties identified by a specified array of keys contained in specified bookmark data. If the result dictionary does not contain a resource value for one or more of the requested resource keys, it means those resource properties are not available in the bookmark data.
@@ -1107,7 +1107,7 @@ public struct URL : ReferenceConvertible, Equatable {
11071107
/// Initializes and returns bookmark data derived from an alias file pointed to by a specified URL. If bookmarkFileURL refers to an alias file created prior to OS X v10.6 that contains Alias Manager information but no bookmark data, this method synthesizes bookmark data for the file.
11081108
public static func bookmarkData(withContentsOf url: URL) throws -> Data {
11091109
let result = try NSURL.bookmarkData(withContentsOf: url)
1110-
return result as Data
1110+
return result
11111111
}
11121112

11131113
/// Given an NSURL created by resolving a bookmark data created with security scope, make the resource referenced by the url accessible to the process. When access to this resource is no longer needed the client must call stopAccessingSecurityScopedResource. Each call to startAccessingSecurityScopedResource must be balanced with a call to stopAccessingSecurityScopedResource (Note: this is not reference counted).

stdlib/public/Darwin/Network/NWConnection.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -479,7 +479,7 @@ public final class NWConnection : CustomDebugStringConvertible {
479479
_ isComplete: Bool, _ error: NWError?) -> Void) {
480480
nw_connection_receive(self.nw, UInt32(minimumIncompleteLength), UInt32(maximumLength)) {
481481
(content, context, complete, nwError) in
482-
completion(NWCreateNSDataFromDispatchData(content) as Data?, ContentContext(context), complete, NWError(nwError));
482+
completion(NWCreateNSDataFromDispatchData(content), ContentContext(context), complete, NWError(nwError));
483483
}
484484
}
485485

@@ -491,7 +491,7 @@ public final class NWConnection : CustomDebugStringConvertible {
491491
_ contentContext: NWConnection.ContentContext?,
492492
_ isComplete: Bool, _ error: NWError?) -> Void) {
493493
nw_connection_receive_message(self.nw) { (content, context, complete, nwError) in
494-
completion(NWCreateNSDataFromDispatchData(content) as Data?, ContentContext(context), complete, NWError(nwError))
494+
completion(NWCreateNSDataFromDispatchData(content), ContentContext(context), complete, NWError(nwError))
495495
}
496496
}
497497

stdlib/public/core/ErrorType.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ internal func _getErrorCode<T: Error>(_ x: UnsafePointer<T>) -> Int {
148148
@_silgen_name("")
149149
internal func _getErrorUserInfoNSDictionary<T: Error>(_ x: UnsafePointer<T>)
150150
-> AnyObject? {
151-
return x.pointee._userInfo.map { $0 as AnyObject }
151+
return x.pointee._userInfo.map { $0 }
152152
}
153153

154154
// Called by the casting machinery to extract an NSError from an Error value.

stdlib/public/core/Integers.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2746,7 +2746,7 @@ extension FixedWidthInteger {
27462746
// If we used &+ instead, the result would be zero, which isn't helpful,
27472747
// so we actually need to handle this case separately.
27482748
if delta == Magnitude.max {
2749-
return Self(truncatingIfNeeded: generator.next() as Magnitude)
2749+
return Self(truncatingIfNeeded: generator.next())
27502750
}
27512751
// Need to widen delta to account for the right-endpoint of a closed range.
27522752
delta += 1
@@ -3366,7 +3366,7 @@ extension FixedWidthInteger {
33663366
using generator: inout R
33673367
) -> Self {
33683368
if bitWidth <= UInt64.bitWidth {
3369-
return Self(truncatingIfNeeded: generator.next() as UInt64)
3369+
return Self(truncatingIfNeeded: generator.next())
33703370
}
33713371

33723372
let (quotient, remainder) = bitWidth.quotientAndRemainder(

stdlib/public/core/StringBridge.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@ internal func _bridgeCocoaString(_ cocoaString: _CocoaString) -> _StringGuts {
383383
// happen; might as well eagerly bridge it in.
384384
// 3) If it's mutable with associated information, must make the call
385385
let immutableCopy
386-
= _stdlib_binary_CFStringCreateCopy(cocoaString) as AnyObject
386+
= _stdlib_binary_CFStringCreateCopy(cocoaString)
387387

388388
#if !(arch(i386) || arch(arm))
389389
if _isObjCTaggedPointer(immutableCopy) {

0 commit comments

Comments
 (0)