-
Notifications
You must be signed in to change notification settings - Fork 1.1k
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
Add ListFormatter
#4794
Open
woxtu
wants to merge
3
commits into
swiftlang:main
Choose a base branch
from
woxtu:listformatter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add ListFormatter
#4794
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
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,99 @@ | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors | ||
// Licensed under Apache License v2.0 with Runtime Library Exception | ||
// | ||
// See http://swift.org/LICENSE.txt for license information | ||
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors | ||
// | ||
|
||
@_implementationOnly import CoreFoundation | ||
|
||
/* NSListFormatter provides locale-correct formatting of a list of items using the appropriate separator and conjunction. Note that the list formatter is unaware of the context where the joined string will be used, e.g., in the beginning of the sentence or used as a standalone string in the UI, so it will not provide any sort of capitalization customization on the given items, but merely join them as-is. The string joined this way may not be grammatically correct when placed in a sentence, and it should only be used in a standalone manner. | ||
*/ | ||
open class ListFormatter: Formatter { | ||
private let cfFormatter: CFListFormatter | ||
|
||
/* Specifies the locale to format the items. Defaults to autoupdatingCurrentLocale. Also resets to autoupdatingCurrentLocale on assignment of nil. | ||
*/ | ||
private var _locale: Locale = .autoupdatingCurrent | ||
open var locale: Locale! { | ||
get { return _locale } | ||
set { _locale = newValue ?? .autoupdatingCurrent } | ||
} | ||
|
||
/* Specifies how each object should be formatted. If not set, the object is formatted using its instance method in the following order: -descriptionWithLocale:, -localizedDescription, and -description. | ||
*/ | ||
/*@NSCopying*/ open var itemFormatter: Formatter? | ||
|
||
public override init() { | ||
self.cfFormatter = _CFListFormatterCreate(kCFAllocatorSystemDefault, CFLocaleCopyCurrent())! | ||
super.init() | ||
} | ||
|
||
public required init?(coder: NSCoder) { | ||
self.cfFormatter = _CFListFormatterCreate(kCFAllocatorSystemDefault, CFLocaleCopyCurrent())! | ||
super.init(coder: coder) | ||
} | ||
|
||
open override func copy(with zone: NSZone? = nil) -> Any { | ||
let copied = ListFormatter() | ||
copied.locale = locale | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I believe that we should just use the |
||
copied.itemFormatter = itemFormatter?.copy(with: zone) as? Formatter | ||
return copied | ||
} | ||
|
||
/* Convenience method to return a string constructed from an array of strings using the list format specific to the current locale. It is recommended to join only disjointed strings that are ready to display in a bullet-point list. Sentences, phrases with punctuations, and appositions may not work well when joined together. | ||
*/ | ||
open class func localizedString(byJoining strings: [String]) -> String { | ||
let formatter = ListFormatter() | ||
return formatter.string(from: strings)! | ||
} | ||
|
||
/* Convenience method for -stringForObjectValue:. Returns a string constructed from an array in the locale-aware format. Each item is formatted using the itemFormatter. If the itemFormatter does not apply to a particular item, the method will fall back to the item's -descriptionWithLocale: or -localizedDescription if implemented, or -description if not. | ||
|
||
Returns nil if `items` is nil or if the list formatter cannot generate a string representation for all items in the array. | ||
*/ | ||
open func string(from items: [Any]) -> String? { | ||
let strings = items.map { item in | ||
if let string = itemFormatter?.string(for: item) { | ||
return string | ||
} | ||
|
||
// Use the item’s `description(withLocale:)` if implemented | ||
if let item = item as? NSArray { | ||
return item.description(withLocale: locale) | ||
} else if let item = item as? NSDecimalNumber { | ||
return item.description(withLocale: locale) | ||
} else if let item = item as? NSDictionary { | ||
return item.description(withLocale: locale) | ||
} else if let item = item as? NSNumber { | ||
return item.description(withLocale: locale) | ||
} else if let item = item as? NSOrderedSet { | ||
return item.description(withLocale: locale) | ||
} else if let item = item as? NSSet { | ||
return item.description(withLocale: locale) | ||
} | ||
|
||
// Use the item’s `localizedDescription` if implemented | ||
if let item = item as? Error { | ||
return item.localizedDescription | ||
} | ||
|
||
return String(describing: item) | ||
} | ||
|
||
_CFListFormatterSetLocale(cfFormatter, locale._cfObject) | ||
return _CFListFormatterCreateStringByJoiningStrings(kCFAllocatorSystemDefault, cfFormatter, strings._cfObject)?._swiftObject | ||
} | ||
|
||
/* Inherited from NSFormatter. `obj` must be an instance of NSArray. Returns nil if `obj` is nil, not an instance of NSArray, or if the list formatter cannot generate a string representation for all objects in the array. | ||
*/ | ||
open override func string(for obj: Any?) -> String? { | ||
guard let list = obj as? [Any] else { | ||
return nil | ||
} | ||
|
||
return string(from: list) | ||
} | ||
} |
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
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,108 @@ | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors | ||
// Licensed under Apache License v2.0 with Runtime Library Exception | ||
// | ||
// See http://swift.org/LICENSE.txt for license information | ||
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors | ||
// | ||
|
||
#if NS_FOUNDATION_ALLOWS_TESTABLE_IMPORT | ||
#if canImport(SwiftFoundation) && !DEPLOYMENT_RUNTIME_OBJC | ||
@testable import SwiftFoundation | ||
#else | ||
@testable import Foundation | ||
#endif | ||
#endif | ||
|
||
class TestListFormatter: XCTestCase { | ||
private var formatter: ListFormatter! | ||
|
||
override func setUp() { | ||
super.setUp() | ||
|
||
formatter = ListFormatter() | ||
} | ||
|
||
override func tearDown() { | ||
formatter = nil | ||
|
||
super.tearDown() | ||
} | ||
|
||
func test_locale() throws { | ||
XCTAssertEqual(formatter.locale, Locale.autoupdatingCurrent) | ||
|
||
formatter.locale = Locale(identifier: "en_US_POSIX") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is not portable ( |
||
XCTAssertEqual(formatter.locale, Locale(identifier: "en_US_POSIX")) | ||
|
||
formatter.locale = nil | ||
XCTAssertEqual(formatter.locale, Locale.autoupdatingCurrent) | ||
} | ||
|
||
func test_copy() throws { | ||
formatter.itemFormatter = NumberFormatter() | ||
|
||
let copied = try XCTUnwrap(formatter.copy() as? ListFormatter) | ||
XCTAssertEqual(formatter.locale, copied.locale) | ||
XCTAssert(copied.itemFormatter is NumberFormatter) | ||
|
||
copied.locale = Locale(identifier: "en_US_POSIX") | ||
copied.itemFormatter = DateFormatter() | ||
XCTAssertNotEqual(formatter.locale, copied.locale) | ||
XCTAssert(formatter.itemFormatter is NumberFormatter) | ||
XCTAssertFalse(copied.itemFormatter is NumberFormatter) | ||
} | ||
|
||
func test_stringFromItemsWithItemFormatter() throws { | ||
let numberFormatter = NumberFormatter() | ||
numberFormatter.locale = Locale(identifier: "en_US_POSIX") | ||
numberFormatter.numberStyle = .percent | ||
|
||
formatter.locale = Locale(identifier: "en_US_POSIX") | ||
formatter.itemFormatter = numberFormatter | ||
XCTAssertEqual(formatter.string(from: [1, 2, 3]), "100%, 200%, and 300%") | ||
} | ||
|
||
func test_stringFromDescriptionsWithLocale() throws { | ||
formatter.locale = Locale(identifier: "en_US") | ||
XCTAssertEqual(formatter.string(from: [1000, 2000, 3000]), "1,000, 2,000, and 3,000") | ||
} | ||
|
||
func test_stringFromLocalizedDescriptions() throws { | ||
struct Item: LocalizedError { | ||
let errorDescription: String? = "item" | ||
} | ||
|
||
formatter.locale = Locale(identifier: "en_US_POSIX") | ||
XCTAssertEqual(formatter.string(from: [Item(), Item(), Item()]), "item, item, and item") | ||
} | ||
|
||
func test_stringFromItems() throws { | ||
struct Item {} | ||
|
||
formatter.locale = Locale(identifier: "en_US_POSIX") | ||
XCTAssertEqual(formatter.string(from: [Item(), Item(), Item()]), "Item(), Item(), and Item()") | ||
} | ||
|
||
func test_stringForList() throws { | ||
XCTAssertEqual(formatter.string(for: [42]), "42") | ||
} | ||
|
||
func test_stringForNonList() throws { | ||
XCTAssertNil(formatter.string(for: 42)) | ||
} | ||
|
||
static var allTests: [(String, (TestListFormatter) -> () throws -> Void)] { | ||
return [ | ||
("test_locale", test_locale), | ||
("test_copy", test_copy), | ||
("test_stringFromItemsWithItemFormatter", test_stringFromItemsWithItemFormatter), | ||
("test_stringFromDescriptionsWithLocale", test_stringFromDescriptionsWithLocale), | ||
("test_stringFromLocalizedDescriptions", test_stringFromLocalizedDescriptions), | ||
("test_stringFromItems", test_stringFromItems), | ||
("test_stringForList", test_stringForList), | ||
("test_stringForNonList", test_stringForNonList), | ||
] | ||
} | ||
} |
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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Most of the SCF does not support
initWithCoder
. Shall we follow precedent andfatalError()
here?