-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
TypePathConvertible: add a simple type path extension (#46)
- Loading branch information
Showing
2 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
24 changes: 24 additions & 0 deletions
24
Sources/FoundationExtensions/Utils/TypePathConvertible.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
// Copyright © 2023 Lautsprecher Teufel GmbH. All rights reserved. | ||
|
||
import Foundation | ||
|
||
/// Allows to turn the Type-hierarchy into a string, i.e. "`Superclass.Subclass`". | ||
public protocol TypePathConvertible { | ||
var typePath: String { get } | ||
} | ||
|
||
extension TypePathConvertible { | ||
public var typePath: String { | ||
let reflectionString = String(reflecting: self) | ||
|
||
// Regex: "\.\([^\)]*\)" matches .("anything but a closing brace") | ||
guard let regex = try? NSRegularExpression(pattern: "\\.\\([^\\)]*\\)", options: NSRegularExpression.Options.caseInsensitive) else { | ||
return String(describing: self) | ||
} | ||
// Remove anonymous types that appear in unit testing, i.e. "A.B.C.(unknown context at $1071608c4).(unknown context at $107160918).yak" | ||
return regex.stringByReplacingMatches(in: reflectionString, | ||
options: [], | ||
range: NSMakeRange(0, reflectionString.count), | ||
withTemplate: "") | ||
} | ||
} |
30 changes: 30 additions & 0 deletions
30
Tests/FoundationExtensionsTests/TypePathConvertibleTests.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
// Copyright © 2023 Lautsprecher Teufel GmbH. All rights reserved. | ||
|
||
import Foundation | ||
import FoundationExtensions | ||
import XCTest | ||
|
||
class TypePathConvertibleTests: XCTestCase { | ||
|
||
func testTypePath() { | ||
// given | ||
enum A: TypePathConvertible { | ||
enum B: TypePathConvertible { | ||
case foo | ||
case bar | ||
|
||
enum C: TypePathConvertible { | ||
case yik | ||
case yak | ||
} | ||
} | ||
} | ||
let sut = A.B.C.yak | ||
|
||
// when | ||
let result = sut.typePath | ||
|
||
// then | ||
XCTAssertEqual(result, "FoundationExtensionsTests.TypePathConvertibleTests.A.B.C.yak") | ||
} | ||
} |