General:
TN3151 Choosing the right networking API
Networking Overview document — Despite the fact that this is in the archive, this is still really useful.
TLS for App Developers DevForums post
Choosing a Network Debugging Tool documentation
WWDC 2019 Session 712 Advances in Networking, Part 1 — This explains the concept of constrained networking, which is Apple’s preferred solution to questions like How do I check whether I’m on Wi-Fi?
TN3135 Low-level networking on watchOS
Adapt to changing network conditions tech talk
Foundation networking:
DevForums tags: Foundation, CFNetwork
URL Loading System documentation — NSURLSession, or URLSession in Swift, is the recommended API for HTTP[S] on Apple platforms.
Network framework:
DevForums tag: Network
Network framework documentation — Network framework is the recommended API for TCP, UDP, and QUIC on Apple platforms.
Building a custom peer-to-peer protocol sample code (aka TicTacToe)
Implementing netcat with Network Framework sample code (aka nwcat)
Configuring a Wi-Fi accessory to join a network sample code
Moving from Multipeer Connectivity to Network Framework DevForums post
Network Extension (including Wi-Fi on iOS):
See Network Extension Resources
Wi-Fi Fundamentals
Wi-Fi on macOS:
DevForums tag: Core WLAN
Core WLAN framework documentation
Wi-Fi Fundamentals
Secure networking:
DevForums tags: Security
Apple Platform Security support document
Preventing Insecure Network Connections documentation — This is all about App Transport Security (ATS).
Available trusted root certificates for Apple operating systems support article
Requirements for trusted certificates in iOS 13 and macOS 10.15 support article
About upcoming limits on trusted certificates support article
Apple’s Certificate Transparency policy support article
What’s new for enterprise in iOS 18 support article — This discusses new key usage requirements.
Technote 2232 HTTPS Server Trust Evaluation
Technote 2326 Creating Certificates for TLS Testing
QA1948 HTTPS and Test Servers
Miscellaneous:
More network-related DevForums tags: 5G, QUIC, Bonjour
On FTP DevForums post
Using the Multicast Networking Additional Capability DevForums post
Investigating Network Latency Problems DevForums post
Local Network Privacy FAQ DevForums post
Extra-ordinary Networking DevForums post
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here
Foundation
RSS for tagAccess essential data types, collections, and operating-system services to define the base layer of functionality for your app using Foundation.
Posts under Foundation tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Description:
I'm noticing that when using the completion handler variant of URLSession.dataTask(with:), the delegate method urlSession(_:dataTask:didReceive:) is not called—even though a delegate is set when creating the session.
Here's a minimal reproducible example:
✅ Case where delegate method is called:
class CustomSessionDelegate: NSObject, URLSessionDataDelegate {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
print("✅ Delegate method called: Data received")
}
}
let delegate = CustomSessionDelegate()
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
let request = URLRequest(url: URL(string: "https://httpbin.org/get")!)
let task = session.dataTask(with: request) // ✅ No completion handler
task.resume()
In this case, the delegate method didReceive is called as expected.
❌ Case where delegate method is NOT called:
class CustomSessionDelegate: NSObject, URLSessionDataDelegate {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
print("❌ Delegate method NOT called")
}
}
let delegate = CustomSessionDelegate()
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
let request = URLRequest(url: URL(string: "https://httpbin.org/get")!)
let task = session.dataTask(with: request) { data, response, error in
print("Completion handler called")
}
task.resume()
Here, the completion handler is executed, but the delegate method didReceive is never called.
Notes:
I’ve verified this behavior on iOS 16, 17, and 18.
Other delegate methods such as urlSession(_:task:didFinishCollecting:) do get called with the completion handler API.
This happens regardless of whether swizzling or instrumentation is involved — the issue is reproducible even with direct method implementations.
Questions:
Is this the expected behavior (i.e., delegate methods like didReceive are skipped when a completion handler is used)?
If yes, is there any official documentation that explains this?
Is there a recommended way to ensure delegate methods are invoked, even when using completion handler APIs?
Thanks in advance!
Does the new TextEditor in iOS 26, which supports rich text / AttributedString, also support the ability to add text attachments or tokens? For example, in Xcode, we can type <#foo#> to create an inline text placeholder/token which can be interacted with in a different way than standard text.
This is the issues I faced: NSBundle file:///System/Library/PrivateFrameworks/MetalTools.framework/ principal class is nil because all fallbacks have failed
How can I fix it because I'm not sure if I dowloaded the application correctly.
I am trying out the new AttributedString binding with SwiftUI’s TextEditor in iOS26. I need to save this to a Core Data database. Core Data has no AttributedString type, so I set the type of the field to “Transformable”, give it a custom class of NSAttributedString, and set the transformer to NSSecureUnarchiveFromData
When I try to save, I first convert the Swift AttributedString to NSAttributedString, and then save the context. Unfortunately I get this error when saving the context, and the save isn't persisted:
CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x600003721140> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null)
Here's the code that tries to save the attributed string:
struct AttributedDetailView: View {
@ObservedObject var item: Item
@State private var notesText = AttributedString()
var body: some View {
VStack {
TextEditor(text: $notesText)
.padding()
.onChange(of: notesText) {
item.attributedString = NSAttributedString(notesText)
}
}
.onAppear {
if let nsattributed = item.attributedString {
notesText = AttributedString(nsattributed)
} else {
notesText = ""
}
}
.task {
item.attributedString = NSAttributedString(notesText)
do {
try item.managedObjectContext?.save()
} catch {
print("core data save error = \(error)")
}
}
}
}
This is the attribute setup in the Core Data model editor:
Is there a workaround for this?
I filed FB17943846 if someone can take a look.
Thanks.
The value of ProcessInfo.processInfo.operatingSystemVersion on iOS 26 is returning 19.0.0 would of expected 26.0.0
We just dropped support for iOS 16 in our app and migrated to the new properties on Locale to extract the language code, region, and script. However, after doing this we are seeing an issue where the script property is returning a value when the language has no script.
Here is the initializer that we are using to populate the values. The identifier is coming from the preferredLanguages property that is found on Locale.
init?(identifier: String) {
let locale = Locale(identifier: identifier)
guard
let languageCode = locale.language.languageCode?.identifier
else {
return nil
}
language = languageCode
region = locale.region?.identifier
script = locale.language.script?.identifier
}
Whenever I inspect locale.language I see all of the correct values. However, when I inspect locale.language.script directly it is always returning Latn as the value. If I inspect the deprecated locale.scriptCode property it will return nil as expected.
Here is an example from the debugger for en-AU. I also see the same for other languages such as en-AE, pt-BR.
Since the language components show the script as nil, then I would expect locale.language.script?.identifier to also return nil.
Hello, thank you Apple for supporting custom store with SwiftData and the Schema type is superb to work with. I have successfully set one up with SQL and have some feedback and issues regarding its APIs.
There’s a highlighted message in the documentation about not using internal restricted symbols directly, but they contradict with the given protocols and I am concerned about breaking any App Store rules. Are we allowed to use these? If not, they should be opened up as they’re useful.
BackingData is required to set up custom snapshots, initialization, and getting/setting values. And I want to use it with createBackingData() to directly initialize instances from snapshots when transferring them between server and client or concurrency.
RelationshipCollection for casting to-many relationships from backing data or checking if an array contains a PersistentModel.
SchemaProperty for type erasure in a collection.
Schema.Relationship has KeyPath properties, but it is missing for Schema.Attribute and Schema.CompositeAttribute. Which means you can’t purely depend on the schema to map data. I am unable to access the properties of a custom struct type in a predicate unless I use Mirror with schemaMetadata() or CustomStringConvertible on the KeyPath directly to extract it.
Trivial, but… the KeyPath property name is inconsistent (it’s all lowercase).
It would be nice to retrieve property names from custom struct types, since you are unable access CodingKeys that are auto synthesized by Codable for structs. But I recently realized they’re a part Schema.CompositeAttribute, however I don’t know how to match these without the KeyPath…
I currently map my entities using CodingKeys to their PredicateCodableKeyPathProviding.… but I wish for a simpler alternative!
It’s unclear how to provide the schema to the snapshot before new models are created.
I currently use a static property, but I want to make it flexible if more schemas and configurations are added later on.
I considered saving and loading the schema in a temporary location, but doubtful that the KeyPath values will be available as they are not Codable.
I suspect schemaMetadata() has the information I need to map the backing data without a schema for snapshots, but as mentioned previously, properties are inaccessible…
Allow access to entity metatypes, like value types from SchemaProperty. They’re useful for getting data out of snapshots and casting them to CodingKeys and PredicateCodableKeyPathProviding. They do not carry over when you provide them in the Schema.
I am unable to retrieve the primary key from PersistentIdentifier.
It seems like once you create one, you can’t get it out, like the DataStoreConfiguration in ModelContainer is not the one you used to set it up. I cannot cast it, it is an entirely different struct?
I have to use JSONSerialization to extract it, but I want to get it directly since it is not a column in my database. It is transformed when it goes to/from my tables.
It’s unknown how to support some schema options, such as Spotlight and CloudKit.
Allow for extending macro options, such as adding options to set as primary key, whether to auto increment, etc…
You can create a schema for super and sub entities, but it doesn’t appear you can actually set them up from the @Model macro or use inheritance on these models…
SwiftData history tracking seems incomplete for HistoryDelete, because that protocol requires HistoryTombstone, but this type cannot be instantiated, nor does it contain anything useful to infer from.
As an aside, I want to create my own custom ModelActor that is a global actor. However, I’m unable to replicate the executor that Apple provides where the executor has a ModelContext, because this type does not conform to Sendable. So how did Apple do this? The documentation doesn’t mention unchecked Sendable, but I figure if the protocol is available then we would be able to set up our own.
And please add concurrency features!
Anyway, I hope for more continued support in the future and I am looking forward to what’s new this WWDC! 😊
Hello, I have encountered an issue with an iPhone 15PM with iOS 18.5. The NSHTTPCookieStorage failed to clear cookies, but even after clearing them, I was still able to retrieve them. However, on the same system
It is normal on iPhone 14PM. I would like to know the specific reason and whether there are any adaptation related issues. Following code:
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies]) {
[storage deleteCookie:cookie];
}
We have FrameworkA which needs to use another FrameworkB internally to fetch a token.
Now when I try to use this FrameworkA, we are seeing an issue with internal framework i.e. No such module 'FrameworkB'.
But when I use @_implementationOnly import for the internal FrameworkB, I didn't see any issues.
So just wanted to check If I can go ahead and use this @_implementationOnly import flag in Production?
I have an app which uses key-value storage and will not sync data past a certain size -- meaning that device "A" will send the data to the cloud but device "B" will never receive the updated data. Device "B" will receive the NSUbiquitousKeyValueStoreDidChangeExternallyNotification that the KVS changed but the data is empty.
The data in in the KVS is comprised of 4 keys, each containing a value of NSData generated by NSKeyedArchiver. The NSData is comprised of property-list data types (e.g. numbers, strings, dates, etc.)
I've verified that the KVS meets the limits of:
A total of 1 MB per app, with a per-key limit of 1 MB
A per-key value size limit of 1 MB, and a maximum of 1024 keys
A maximum length for key strings is 64 bytes using UTF8 encoding
Also, the app has never received an NSUbiquitousKeyValueStoreQuotaViolationChange notification.
Of the 4 keys, 3 of them contain no more than 30 KB of data each. However, one of the keys can contain as much as 160 KB of data which will not sync to another device. Strangely, if I constrain the data to 100 KB it will work, however, that is not ideal as it is a fraction of the necessary data.
I don't see any errors in the debug log either.
Any suggestions on what to try next to get this working?
Is there a public method to know when an APNS has appeared on the screen?
wrapping up a very high end photogrammetry app, using the front facing camera and screen illumination-
incoming notifications completely throw off the math.
Ideally, it would be great to turn on Do Not Disturb for the short process, but we’d settle for just the detection of the notification banner.
also: extra credit - programattically adjusting Auto Dimming, and True Tone would be lovely too.
I have an accessory with MFi authenticaiton passed(got 0xAA05) and identification accepted (got 0x1D02). But when I try to open the target stream by using iAP2 EA session framework, I always enounter the same error looking like:
XPC connection error: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.accessories.externalaccessory-server was invalidated from this process." UserInfo={NSDebugDescription=The connection to service named com.apple.accessories.externalaccessory-server was invalidated from this process.}
anybody can tell me what it related with? And what can I do to go through it quickly? Thank you much in advance.
I have been working on updating an old app that makes extensive use of Objective-C's NSTask. Now using Process in Swift, I'm trying to gather updates as the process runs, using readabilityHandler and availableData. However, my process tends to exit before all data has been read. I found this post entitled "Running a Child Process with Standard Input and Output" but it doesn't seem to address gathering output from long-running tasks. Is there a straightforward way to gather ongoing output from a long running task without it prematurely exiting?
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
Foundation
Inter-process communication
Hi,
I’m trying to download a remote file in the background, but I keep getting a strange behaviour where URLSession download my file indefinitely during a few minutes, without calling urlSession(_:downloadTask:didFinishDownloadingTo:) until the download eventually times out.
To find out that it’s looping, I’ve observed the total bytes written on disk by implementing urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:).
Note that I can't know the size of the file. The server is not able to calculate the size.
Below is my implementation.
I create an instance of URLSession like this:
private lazy var session: URLSession = {
let configuration = URLSessionConfiguration.background(withIdentifier: backgroundIdentifier)
configuration.isDiscretionary = false
configuration.sessionSendsLaunchEvents = true
return URLSession(configuration: configuration,
delegate: self,
delegateQueue: nil)
}()
My service is using async/await so I have implemented an AsyncThrowingStream :
private var downloadTask: URLSessionDownloadTask?
private var continuation: AsyncThrowingStream<(URL, URLResponse), Error>.Continuation?
private var stream: AsyncThrowingStream<(URL, URLResponse), Error> {
AsyncThrowingStream<(URL, URLResponse), Error> { continuation in
self.continuation = continuation
self.continuation?.onTermination = { @Sendable [weak self] data in
self?.downloadTask?.cancel()
}
downloadTask?.resume()
}
}
Then to start the download, I do :
private func download(with request: URLRequest) async throws -> (URL, URLResponse) {
do {
downloadTask = session.downloadTask(with: request)
for try await (url, response) in stream {
return (url, response)
}
throw NetworkingError.couldNotBuildRequest
} catch {
throw error
}
}
Then in the delegate :
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
guard let response = downloadTask.response,
downloadTask.error == nil,
(response as? HTTPURLResponse)?.statusCode == 200 else {
continuation?.finish(throwing: downloadTask.error)
return
}
do {
let documentsURL = try FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
let savedURL = documentsURL.appendingPathComponent(location.lastPathComponent)
try FileManager.default.moveItem(at: location, to: savedURL)
continuation?.yield((savedURL, response))
continuation?.finish()
} catch {
continuation?.finish(throwing: error)
}
}
I also tried to replace let configuration = URLSessionConfiguration.background(withIdentifier: backgroundIdentifier) by let configuration = URLSessionConfiguration.default and this time I get a different error at the end of the download:
Task <0457F755-9C52-4CFB-BDB2-F378D0C94912>.<1> failed strict content length check - expected: 0, received: 530692, received (uncompressed): 0
Task <0457F755-9C52-4CFB-BDB2-F378D0C94912>.<1> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=https:/<host>:8190/proxy?Func=downloadVideoByUrl&SessionId=slufzwrMadvyJad8Lkmi9RUNAeqeq, NSErrorFailingURLKey=https://<host>:8190/proxy?Func=downloadVideoByUrl&SessionId=slufzwrMadvyJad8Lkmi9RUNAeqeq, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDownloadTask <0457F755-9C52-4CFB-BDB2-F378D0C94912>.<1>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDownloadTask <0457F755-9C52-4CFB-BDB2-F378D0C94912>.<1>, NSUnderlyingError=0x300d9a7c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x302139db0 [0x1fcb1f598]>{length = 16, capacity = 16, bytes = 0x10021ffe91e227500000000000000000}}}}
The log "failed strict content length check” made me look into the response header, which has the following:
content-length: 0
Content-Type: application/force-download
Transfer-encoding: chunked
Connection: KEEP-ALIVE
Content-Transfer-Encoding: binary
So it should be fine the way I setup my URLSession.
The download works fine in Chrome/Safari/Chrome or Postman.
My code used to work a couple of weeks before, so I expect something has changed on the server side, but I can’t find what, and I don’t get much help from the guys on the server side.
Has anyone an idea of what’s going on?
Topic:
App & System Services
SubTopic:
Networking
Tags:
Network
Background Tasks
CFNetwork
Foundation
Hi there.
How can I do for the title?
URLRequest seems not to have property for protocols.
NSURLSessionWebSocketTask seems to have either URLRequest or protocols, but have neither of them.
What I want to do is setting both protocols and headers when using WebSocket.
Should I use Network.framework instead?
Our app needs to read server settings that are configured in the app's settings. In iPadOS 17.7.7 specifically (iPadOS 17.7.6, iPadOS 18.5, and other versions works fine) one can't retrieve any setting from the settings bundle using:
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"setting_hostname"] != nil)
serverHostname = [[NSUserDefaults standardUserDefaults] objectForKey:@"setting_hostname"];
Also, when writing a custom value in NSUserDefaults like:
[[NSUserDefaults standardUserDefaults] setObject:@"Test" forKey:@"test"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSString* test = [[NSUserDefaults standardUserDefaults] objectForKey:@"test"];
NSLog(@"%@", test);
Shows an error in the console:
Couldn't write values for keys ( test ) in CFPrefsPlistSource<0x3017ecc60> (Domain: <redacted_bundle_id>, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: No): setting these preferences requires user-preference-write or file-write-data sandbox access
When closing the app and reopening it, and then reading the value of [[NSUserDefaults standardUserDefaults] objectForKey:@"test"]; returns null
Recently, some feedback has been received. After users upgrade to ipados 17.7.7 and return to the login status and restart the App, it will become invalid. We checked the log and found that the content stored in NSUserdefault would be lost after restarting the App. Has anyone encountered this problem?
Looking to start developing at Swift. What is the best way to get started with a job related to Swift development? Is there any specific demanded certification I could pursue?
Thank you.
Testing Environment: iOS 18.4.1 / macOS 15.4.1
I am working on an iOS project that aims to utilize the user's iCloud Drive documents directory to save a specific directory-based file structure. Essentially, the app would create a root directory where the user chooses in iCloud Drive, then it would populate user generated files in various levels of nested directories.
I have been attempting to use NSMetadataQuery with various predicates and search scopes but haven't been able to get it to directly monitor changes to files or directories that are not in the root directory.
Instead, it only monitors files or directories in the root directory, and any changes in a subdirectory are considered an update to the direct children of the root directory.
Example
iCloud Drive Documents (Not app's ubiquity container)
User Created Root Directory (Being monitored)
File A
Directory A
File B
An insertion or deletion within Directory A would only return a notification with userInfo containing data for NSMetadataQueryUpdateChangedItemsKey relating to Directory A, and not the file or directory itself that was inserted or deleted. (Query results array also only contain the direct children.)
I have tried all combinations of these search scopes and predicates with no luck:
query.searchScopes = [
rootDirectoryURL,
NSMetadataQueryUbiquitousDocumentsScope,
NSMetadataQueryAccessibleUbiquitousExternalDocumentsScope,
]
NSPredicate(value: true)
NSPredicate(format: "%K LIKE '*.md'", NSMetadataItemFSNameKey)
NSPredicate(format: "%K BEGINSWITH %@", NSMetadataItemPathKey, url.path(percentEncoded: false))
I do see these warnings in the console upon starting my query:
[CRIT] UNREACHABLE: failed to get container URL for com.apple.CloudDocs
[ERROR] couldn't fetch remote operation IDs: NSError: Cocoa 257 "The file couldn’t be opened because you don’t have permission to view it."
"Error returned from daemon: Error Domain=com.apple.accounts Code=7 "(null)""
But I am not sure what to make of that, since it does act normally for finding updates in the root directory.
Hopefully this isn't a limitation of the API, as the only alternative I could think of would be to have multiple queries running for each nested directory that I needed updates for.
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
Files and Storage
iCloud Drive
Foundation
I'm trying to understand the behavior I'm seeing here. In the following example, I have a custom @Observable class that adopts RandomAccessCollection and am attempting to populate a List with it.
If I use an inner collection property of the instance (even computed as this shows), the top view identifies additions to the list.
However, if I just use the list as a collection in its own right, it detects when a change is made, but not that the change increased the length of the list. If you add text that has capital letters you'll see them get sorted correctly, but the lower list retains its prior count. The choice of a List initializer with the model versus an inner ForEach doesn't change the outcome, btw.
If I cast that type as an Array(), effectively copying its contents, it works fine which leads me to believe there is some additional Array protocol conformance that I'm missing, but that would be unfortunate since I'm not sure how I would have known that. Any ideas what's going on here? The new type can be used with for-in scenarios fine and compiles great with List/ForEach, but has this issue. I'd like the type to not require extra nonsense to be used like an array here.
import SwiftUI
fileprivate struct _VExpObservable6: View {
@Binding var model: ExpModel
@State private var text: String = ""
var body: some View {
NavigationStack {
VStack(spacing: 20) {
Spacer()
.frame(height: 40)
HStack {
TextField("Item", text: $text)
.textFieldStyle(.roundedBorder)
.textContentType(.none)
.textCase(.none)
Button("Add Item") {
guard !text.isEmpty else { return }
model.addItem(text)
text = ""
print("updated model #2 using \(Array(model.indices)):")
for s in model {
print("- \(s)")
}
}
}
InnerView(model: model)
OuterView(model: model)
}
.listStyle(.plain)
.padding()
}
}
}
// - displays the model data using an inner property expressed as
// a collection.
fileprivate struct InnerView: View {
let model: ExpModel
var body: some View {
VStack {
Text("Model Inner Collection:")
.font(.title3)
List {
ForEach(model.sorted, id: \.self) { item in
Text("- \(item)")
}
}
.border(.darkGray)
}
}
}
// - displays the model using the model _as the collection_
fileprivate struct OuterView: View {
let model: ExpModel
var body: some View {
VStack {
Text("Model as Collection:")
.font(.title3)
// - the List/ForEach collections do not appear to work
// by default using the @Observable model (RandomAccessCollection)
// itself, unless it is cast as an Array here.
List {
// ForEach(Array(model), id: \.self) { item in
ForEach(model, id: \.self) { item in
Text("- \(item)")
}
}
.border(.darkGray)
}
}
}
#Preview {
@Previewable @State var model = ExpModel()
_VExpObservable6(model: $model)
}
@Observable
fileprivate final class ExpModel: RandomAccessCollection {
typealias Element = String
var startIndex: Int { 0 }
var endIndex: Int { sorted.count }
init() {
_listData = ["apple", "yellow", "about"]
}
subscript(_ position: Int) -> String {
sortedData()[position]
}
var sorted: [String] {
sortedData()
}
func addItem(_ item: String) {
_listData.append(item)
_sorted = nil
}
private var _listData: [String]
private var _sorted: [String]?
private func sortedData() -> [String] {
if let ret = _sorted { return ret }
let ret = _listData.sorted()
_sorted = ret
return ret
}
}