♪ ♪Ben: Hello, and welcome to "What's New in Swift 5.9."I'm Ben, and along with my colleague Doug,we will go through some improvements with youto the Swift language this year.We will discuss some ways in which it is easier to express what you meanusing Swift's clean syntax, some powerful new featureshelping framework authors make their new APIs more natural to use,and we'll look at some new ways to take more control over performanceand security in low-level code.
But let's start by talking about the Swift open source project.This is a great update to Swift and it couldn't have happenedwithout the swift community,the contributors and users of the languagewho gather at swift.org and collaborate to develop the languageand support new initiatives.Swift follows an open language evolution process.New features or significant behavioral changes are proposedand openly reviewed on the Swift forums.If you want to follow along, you can find a dashboardof all language suggestions on the Swift website.
A year ago we saw a major restructuringof the Swift project board.The core team announces the formation of the Language Steering Committee,who took primary responsibility for overseeing the Swift languageand evolution of standard libraries.Since then, the language group has supervised40 new language proposals,and we're going to talk about some of them today.
But sometimes individual language representationscome together as part of a broader theme,such as the addition of Swift concurrency,which was introduced through ten separate proposals.
For cases like this the steering group languageintroduced a new way to connect these proposals,through vision documents.These documents contain a proposal for major language changes.First accepted by the language steering groupwas a vision of Swift macros, a new feature in Swift 5.9which we will discuss later in this conversation.
Of course, the evolution of language is only part of itof the work of the Swift community.A successful language needs much more.It needs great tooling, robust multi-platform support,and rich documentation.To monitor progress in this area, the core team createsan ecosystem steering committee parallel to the language steering committee.This new structure was recently outlined in a blog post on Swift.org,watch for further announcementsabout the formation of this new group soon.Now let's talk about Swift language changes this year,starting with better ways to express yourself in your code.Swift 5.9 includes someis probably our most requested language enhancement,allow if/else and switch statements to be used as expressions,provide a nice way to clean up your code.
For example, if you want to initialize a variable letbased on a complex condition, you had to resort to tricks,like this hard-to-read compound ternary expression.
If statements allow you to use a much more familiar one insteadand readable chain of if statements.
Another place where this helpsis if you initialize a global variable or a stored property.Single expressions work fine here, but if you want a condition,you had to use the trick of wrapping it in a claspwhich you then immediately executed.
Now that an if statement can be an expression,you can just drop that junk, leaving you with a neater code.
Result Builders, the declarative syntax that powers features like SwiftUI,have seen significant improvements this year,including optimized type-check performance,code completion and improved error reporting.
This improvement was specifically aimed at invalid code.Previously it took a long time for result builder code to fail with errors,while the type-check explored the many possible invalid paths.
As of Swift 5.8, the type of invalid code is checked much faster,and invalid code errors are now more accurate.Previously, for example, an invalid code could resultto misleading errors in a completely different part of the result builder.In Swift 5.7 you would get an error like this,when the error actually lies here.
In the latest release you will receive nowa more accurate compiler diagnosis that identifies the real problem.
Next, let's talk about how an addition to the generic drug systemwill enable some great improvements to frameworks you use every day.
Nearly all of the Swift you write use generics in one way or another.Type inference allows the use of these types without needto understand the advanced capabilities with which they are built.For example, the Array type of the standard library uses generic namesto provide an array that works with any type of datathat you may want to save.When using an array, you only need to specify the elements.It is not necessary to specify an explicit element type argumentbecause it can be derived from the element values.
Swift's generic system enables natural APIsthat retain type informationso that your code works seamlessly on the concrete types you provide.
Here's an example inspired by the Swift compiler's own codebase:An API that takes on a request typeand evaluates it to produce a strongly typed value.So you can query a Boolean valueand return a boolean result.
Now some APIs don't just want to abstract about concrete types,but also the number of arguments you pass.So a function can take one request and return one resultor two requests and return two results, or three and return three results.
To support this, the generic system must be usedalong with a mechanism to handle multiple argument lengthsso that all the species you let in are linked to the species you take out.
Before Swift 5.9 the only way to achieve this patternwas by adding an overload for each specific argument lengththe API supported.But this approach has limitations.It enforces an artificial upper limiton the number of arguments you can pass,resulting in compiler errorsif you pass too many.
In this case, there is no overload that can handlemore than six arguments, but we passed seven.
This overload pattern and its limitations are ubiquitousabout APIs conceptually dealing with arbitrary length arguments.
In Swift 5.9, the generic system gets premium supportfor this API pattern by enabling generic abstraction over argument length.This is done with a new language conceptwhich can represent multiple individual type parametersthat are "wrapped" together.This new concept is called a type-parameter package.
using parameter packs,APIs that currently have individual overloadsfor any fixed argument lengthcan be collapsed into a single function.
Instead of accepting a single type parameter, Result,represents the result type of a single request,the evaluation function now accepts a separate request for each result type.
The function returns each result instance in parentheses,which will be a single value or a tuple containing each value.
The evaluation function now handles all argument lengths with no artificial limit.
Type inference makes APIs using parameter packs natural to usewithout you needing to know that the API is using them.
Invoke our new evaluation functionwhich can now handle any number of arguments,is exactly like calling fixed-length overloads.Swift infers the type of each argument along with the total numberbased on how you call the function.For more information on writing generic library APIs like this one,see generalizing APIs using parameter packages.
Calling generic APIs in a natural way demonstrates oneof Swift's fundamental design goals, clear expression through concise code.
Swift's advanced language features enable beautiful APIsthat makes it easier to say what you mean.
You benefit from these advanced language featuresfrom the very first lines of Swift you ever write,whether using generics through arrays or dictionariesor designing a user interface in SwiftUI.Swift's embrace of progressive disclosure means you can learnabout the more advanced features when you're ready.
Swift 5.9 takes this design approach to the next levelby offering library authors a new toolboxfor expressive API design using a new macro system.Here's Doug to tell you more.Doug: Macros allow you to extend the capabilities of the language itself,eliminating boilerplate and unlocking more of Swift's expressive power.Let's take a look at the ever-present assert function,that checks whether a condition is true.Assert stops the program if the condition is false,but when that happens, you get very little informationabout what went wrong, just the file and line number.You need to add some logging or catch the program in the debugger for more information.Attempts have been made to improve this.XCTest provides an assert-equal operation that takes the two values separately,so if things fail you can at least see the two values that are not equal.But we still don't know which value is wrong here.Was it a, b or the result of max?And this approach is really not scalable for all types of auditswe perform in assertions.Going back to the original claim, there is so much information herein the source code we'd like to see in the log if our assertion fails.What was the code?What are the values of a, and b, and c?What has max produced?We couldn't improve this in Swift before without a custom function,but macros make it possible.
In this example, the "hash-assert" syntax extends the macro named "assert".The hash syntax may look familiarbecause Swift already has a few things with the same spelling,such as hash file, hash selector and hash warning.The assert macro looks and feels like the function version,but because it's a macro, it can provide a richer experiencewhen the claim fails.
Now the program shows the code for the failed assertion,together with each of the values that contributed to the result.
In Swift, macros are APIs, just like types or functions,so you access them by importing the module that defines them.Like many other APIs, macros are distributed as packages.The assert macro here comes from the power asserts library,an open-source Swift package available on GitHub.
If you were to look into the macro package,you would find a macro declaration for assert.It is introduced with the keyword "macro",but otherwise it looks a lot like a function.There is a single unlabeled bool parameterto check the condition.If this macro produced a value,that result type would be writtenusing the usual arrow syntax.The use of the macro is controlled by typeagainst the parameters.That means, if you were to make a mistakewhen using the macro,like forgetting to comparethe maximum value against something,you will get a helpful error messageimmediately,before the macro ever expands.This allows Swift to providea great development experiencewhen using macros because macros workon well-typed input and producing codethat increases your programin predictable ways.Most macros are definedals "externe macro's",specifying the module and type for a macro implementation via strings.The external macro types are defined in separate programswhich act as compiler plugins.The Swift compiler passes the source codefor using the macro to the plugin.The plugin produces new source code,which is then integrated back into the Swift program.Here the macro extends the assertion in codethat defines the individual valuesand where they should appear in the source code.You wouldn't want to write the boilerplate yourself,but the macro does it for you.Macro declarations have one additional piece of information, their role.The assert macro here is a free-standing expression macro.It is called freestanding because it uses the "hash" syntaxand acts directly on that syntax to produce new code.It is an expression macro because it can be used anywherethat one can produce a value.The new Foundation Predicate APIs are a good example of an expression macro.Predicates can be written with the predicate macroin a type-safe manner by means of closures.The resulting predicate values can then be used with a number of other APIs,including the Swift collection operations SwiftUI and SwiftData.
The macro itself is genericabout the range of input types.It accepts a closing argumentthat is a function that works on valuesof those input types and producesa boolean result,does the set of inputs match or not?And the macro returns an instanceof the new predicate type,that can be used elsewherein the program.
But there's more to macros because a lot of the boilerplatewe end up writing because we need to complete codewe wrote with something else derived from it.Let's take an example.I find myself using a lot of enumerations in my own code,like this Path enumeration that captures relative or absolute paths.But I'll often find myself needing to check for a specific case,for example, by filtering all absolute paths from a collection.I can of course write this isAbsolute check as a computed property.But sooner or later I will have to write another one.This gets a bit annoying.
Macros can help here by generating the boilerplate for us.
Case detection is an attached macro,written using the same custom attribute syntax as property wrappers.Attached macros take as input the syntax of the declaration they apply to--here it's the enum declaration itself - and will generate new code.
This macro expanded code is regular Swift code,which integrates the compiler into your program.You can inspect the macro-generated code in your editor, debug it,copy it if you want to customize it further, and so on.
Attached macros are organized into five different rolesbased on how they complete the statement to which they are attached.The case detection macro we just discussed is an attached "member" macro,meaning it creates new members in a type or extension.
Peer macros add new declarations in addition to the declaration they are associated with,for example to create a completion handler versionof an asynchronous method or vice versa.
Accessor macros can convert a stored property into a calculated property,which can be used to perform specific actions on property accessor summarize the actual storage in a manner similar to,but more flexible than proprietary packaging.And attached macros can introduce attributeson specific members of a type, as well as adding new protocol conformances.
Multiple linked macro roles can be assembled togetherto achieve beneficial effects.An important example of this is with observation.
Observation has always been a part of SwiftUI.To observe changes in a class's properties,one only needs to make the type conform to ObservableObject,and mark each property on-Published,and use the ObservedObject property wrapper in your view.
That's a lot of steps, and missing a step can meanthat the user interface is not updating as expected.We can do better with macro-based observation.
Associating the observable macro with a class provides observationfor all its stored properties.It is not necessary to annotate every saved propertyor worry about what will happen if you don'tbecause the Observable macro can handle it all.
The observable macro works through the composition of three macro roles.Let's see how these roles work together.
Each macro role corresponds to a specific wayin which the Person class is complemented by the Observable macro.The member role introduces new properties and methods.
The member attribute role adds the @ObservationTracked macroto the stored properties of the observed class,which in turn expands to getters and setters to trigger observation events.Finally, the conformance role introduces conformityaccording to the observable protocol.
This may seem like a lot of code, but it's all normal Swift code,and it's neatly tucked away behind the observable macro.
When you want to see how a macro expandsto better understand its effect on your program,it's at your fingertips in Xcode.
Use the "Expand macro" action.to see the macro expanded source code in your editor.Any error messages within macro-generated codeautomatically shows the extended code,and you can step in and out of it with your debugger.
Quick macros provide a new tool to enable more expressive APIsand remove default from your Swift code,help unlock Swift's expressive power.Macros check their input, produce normal Swift code,and integrate at defined points in your program,so their effects are easy to reason out.And every time you want to understand what a macro did,the extended source code is right there in your editor.We've just scratched the surface of macros."Extending on Swift Macros" takes a deep dive into the design of Swift macrosto answer all those questions you must have.And you can get hands-on with implementing your own macroswith "Write Swift Macros."I can't wait to see what new macros the Swift community will build.
Ben: From the beginning, Swift was designed as a scalable language.
Swift's design emphasizes expressiveness with clear and concise codewhich is unceremonious and easy to read and write.By taking advantage of Swift's powerful features,such as generics and support for native concurrency,frameworks such as SwiftUI or SwiftDatalet you quickly achieve the desired results,so you have more time to focus on what's important.
Despite these high-quality capabilities,Fast is also efficient.It compiles natively and using value typesand of reference counting instead of garbage collection meansit is capable of achieving a low memory footprint.
This scalability means we can push Swift to more placesthan was previously possible with Objective-C,to low-level systems, where you might have expected beforeto have to use C or C++.This means Swift's clearer code and critical security guarantees are providedto more places.We recently opened the start of a rewriteof the Foundation framework in Swift.This initiative will lead to one shared implementationof Foundation on both Apple and non-Apple platforms.But it also meant rewriting large amounts of Objective-C and C code in Swift.
Starting with macOS Sonoma and iOS 17, there are new Swift-supported implementationsof essential types such as Date and Calendar,of formatting and internationalization requirementssuch as Locale and AttributedString,and a new Swift implementation of JSON encoding and decoding.And the performance gains were significant.
The calendar's ability to calculate important dates can benefit betterof Swift's value semantics to avoid intermediate assignments,resulting in an improvement of more than 20% in some benchmarks.
Date formatting using FormatStyle also wonsome major performance upgrades, with a massive 150% improvementin a formatting benchmark with a standard date and time template.
Even more exciting are the improvements to JSON decoding in the new package.Foundation has a brand new Swift implementationfor JSONDecoder and JSONEncoder, eliminating expensive round-tripsfrom and to Objective-C collection types.The tight integration of JSON parsing in Swift for initializing codable typesalso improves performance.In benchmarks parsing test data, the new implementationis between two and five times faster.These improvements resulted from both reducing bridging costsfrom the old Objective-C implementation to Swift,but also because the new Swift-based implementations are faster.
Let's look at a benchmark as an example.In Ventura, calling enumerateDates from Objective-C was slightly fasterthen calling from Swift due to bridging charges.In MacOS Sonoma,Calling that same functionality from within Swift is 20% faster.Part of that acceleration comes from eliminating bridging costs,but the new function implementation itself is also faster,as seen when calling from Objective-C.This particular date calculation is not overly complicated,so this is a great way to see the reductionin overhead between the two languages.Now, sometimes, when you operate at a lower levelof the system, you need more fine-grained controlto achieve a necessary level of performance.Swift 5.9 introduces some new opt-in capabilitiesthat help you achieve this level of control.These capabilities focus on the concept of ownership, that is,which part of the code "owns" a value when passed by your application.
To see when you want to use these features,Let's look at some sample code first.
Here we have a very simple file descriptor wrapperthat would allow us to give low-level system calls a nicer Swift interface.But there are still some easy ways to go wrong with this API.For example, you can try to write to the file after calling close .And you have to be careful to always close it manuallyby calling the close method before the type goes out of scope.Otherwise you would get a source leak.
One solution would be to make it a classwith a deinit that closes it automatically when the type is out of range.
But that has other drawbacks,such as making an additional memory allocation,which is usually not a big problem,except in some very limited system contexts.
Classes also have reference semantics.You could inadvertently share a file description type in different threads,lead to race conditions, or save inadvertently.
But let's go back and look at the struct version.
Really, this structure also behaves like a reference type.It contains an integer that refers to the actual value,that is an open file.Making such a copy may also lead to accidental sharingof changeable state in your app in ways that can lead to bugs.What you want is to suppress the possibility of making a copy of this structure.
Swift types, whether structs or classes, are copyable by default.This is usually the right choice.While excessive unnecessary copying can sometimes be a bottleneck in your code,it is better to spend the time finding those bottlenecksoccasionally in instruments than being harassed constantlyby the compiler requiring you to be explicit about those copies.
But sometimes that implicit copy isn't what you want, espwhen copying a value can lead to correctness issues,like with our file descriptor wrapper.In Swift 5.9 you can with this new syntax that can be appliedto structure and list declarationsand that suppresses the implicit ability to copy a type.Once a type is uncopyable you can deinit it,like you can a class,which is executed when a value of type is out of range.
Uncopyable types can also be used to solve the problem of close calling,and then use other methods.
The close operation can be marked as consuming.Calling a consuming method or argument gives up ownershipof a value for the method you called.Since our type cannot be copied,giving up ownership means you can no longer use the value.
By default, methods in Swift borrow their arguments, including themselves.So you can call the write method, which borrows the file descriptor,uses it to write to the buffer, and after that,ownership of the value returns to the caller,and you can call another method like close.
But since close is marked as consuming,not the standard of borrowing, it must be the final use.
This means that if you first close the file and then try to call another method,like writing, you get an error while compiling,instead of a runtime error.The compiler also indicates where the consuming use occurred.
Non-copyable types are a powerful new featurefor system-level programming in Swift.They are still at the beginning of their evolution.Later versions of Swift will extend uncopyable types in generic code.
If you are interested in following this work,it is being actively discussed in the Swift forums.Doug: A key to Swift's success is its interoperability with Objective-C.From the beginning, developers have been abletaking incremental steps towards Swift adoption in their existing codebases,mix in Swift a single file or module at a time.But we know that many of you haven't just written code in Objective-C.Many apps have also implemented core business logic in C++,and dealing with it was not so easy.Often this meant adding an extra manual bridging layer ranging from Swift,through Objective-C, and then into C++, and all the way back.Swift 5.9 introduces the ability to interact with C++ typesand works directly from Swift.C++ interoperability works just as Objective-C interoperability has always done,Mapping C++ APIs to their Swift equivalentswhich you can use directly from Swift code.
C++ is a big language with its own notions of ideassuch as classes, methods, containers, and so on.The Swift compiler understands common C++ idioms,so many kinds can be used directly.For example, this person type defines the five special member functionsexpected from a C++ value type: copy and move constructors,assignment operators and a destructor.The Swift compiler treats this as a value typeand automatically calls the right member special function at the right time.In addition, C++ containers like vectors and mapsare accessible as Swift collections.
The result of all this is that we can write simple Swift codethat directly uses C++ functions and types.We can filter over the person instance vector,Call C++ member functions and access data members directly.
In the other direction, using Swift code from C++is based on the same mechanism as Objective-C.The Swift compiler produces a "generated header"which contains a C++ representation of the Swift APIs.However, unlike Objective-C, you don't have to limit yourselfto use only Swift classes annotated with the objc attribute.C++ can directly use most Swift types and their full APIs,including properties, methods and initializers,without any bridging.
Here we can see how C++ can make use of our Point structure.After recording the generated header,C++ can call Swift initializers to create Point instances,resort to mutating methods,and access both saved and calculated properties,all without any changes to the Swift code itself.
Swift's C++ interoperability makes it easier than everto integrate Swift with existing C++ codebases.Many C++ idioms can be expressed directly in Swift,often automatic, but occasionally requires some annotationsto indicate the desired semantics.And Swift APIs can be accessed directly from C++,no annotation or code changes required,making it possible to use Swift step-by-step across an entire code baseusing a combination of C, C++ and Objective-C.
C++ interoperability is an evolving story,supervised by the C++ Interoperability Working Group.For more information, see the lecture "Combining Swift and C++",or join us in the discussion on the Swift forums.
Interoperability at language level is very important,but you also need to be able to build your code.And replace your existing build system with Xcodeor the Swift Package Manager to even get started with Swiftcan be as big a barrier as rewriting a large amount of code.
That's why we partnered with the CMake communityto improve Swift support in CMake.You can integrate Swift code into your CMake build by declaring Swiftas one of the languages for the project and placing Swift files in a target.
More importantly, you can combine C++ and Swift within one goal,and CMake will compile each one separatelyand link all appropriate supporting libraries and runtimesfor both languages.This means you can use Swift in your cross-platform C++ projects today,file by file or target by target.We also provide a sample repositorywith CMake projects containing Swift and mixed C++/Swift targets,including the use of the bridging and generated headers,to get you started.
A few years ago we introduced a new concurrency modelin Swift based on the building blocks of async/wait,structured concurrency and actors.Swift's concurrency model is an abstract model,which can be adapted to different environments and libraries.The abstract model has two main parts: tasks and actors.Tasks represent a sequential unit of work that can conceptually be performed anywhere.Tasks can be suspended when there is a "wait" in the program,and then continue as soon as the task can be continued.
Actors are a synchronization mechanismthat provide mutually exclusive access to an isolated state.Entering an actor from the outside requires a "wait"because it can suspend the task.
Tasks and actors are integrated in the abstract language model,but within that model they can be implemented in different waysfit in different environments.Jobs run on the global concurrent pool.How that global concurrent pool decides to schedule work is up to the environment.For Apple's platforms, the Dispatch library providesoptimized scheduling for the entire operating system,and is extensively tuned for each platform.In more restrictive environments,the overhead of a multithreaded scheduler may not be acceptable.Swift's concurrency model is implemented therewith a single-threaded cooperative queue.The same Swift code works in both environmentsbecause the abstract model is flexible enough to mapto various runtime environments.
In addition, interoperability with callback-based librarieswas built into Swift's async/wait support from the start.The withCheckedContinuation operations allow one to interrupt a task,and resume it later in response to a callback request.This allows integration with existing librarieswho manage their own tasks.
The default implementation of actors in the Swift concurrency runtimeis a lock-free queue of tasks to be performed on the actor,but it is not the only possible implementation.In a more limited environment one may have no atoms,and could use another concurrency primitive like spinlocks instead.If that environment was single-threaded, no synchronization is needed,but the actor model maintains the abstract concurrency modelanyway for the program.You can still take that same code to another environmentdat is multithreaded.With Swift 5.9, custom actor performers are possiblea particular actor to implement its own synchronization mechanism.This makes actors more flexible and more adaptable to existing environments.Let's take an example.
Here we consider an actor that manages a database connection.Swift provides mutually exclusive access to this actor's storage,so there will be no simultaneous access to the database.But what if you need more control over the specific waywhat is synchronized with?For example, what if you want to use a specific send queuefor your database connection, perhaps because that queue is sharedwith other code that didn't take on any actors?With custom actor executors you can.
Here we have added a serial send queue to our actorand an implementation of executor's non-ownershipthat the executor produces that corresponds to that dispatch queue.With this change, all synchronizationfor our actor instances will be through that queue.
When you "wait" for the call to prune OldEntries from outside the actor,this will now perform a dispatch async on the corresponding queue.This gives you more control over how individual actorsprovide sync and even let you sync an actorwith other code that doesn't use actors yet,maybe because it's written in Objective-C or C++.
The synchronization of actors via dispatch queues is made possiblebecause the send queue complies with the new SerialExecutor protocol.You can use your own synchronization mechanism to use with actorsby defining a new type that conforms to this protocolwhich has only a few core activities:Checking if the code is already running in the context of the executor.For example, are we walking on the red thread?Extract a non-proprietary reference to the executor to allow access to itwithout excessive reference counting traffic.And the most core operation, queue,who takes ownership of a "task" from an executor.A job is part of an asynchronous job that is neededto run synchronously on the performer.At the point where enqueue is called, it's the responsibilityof the performer to perform that task at a given timewhen no other code is executed on the serial executor.For example, a dispatch queue would call dispatch async on that queue.
Swift Concurrency has been around for a few years now,and the abstract model consisting of tasks and actorscovers a large number of simultaneous programming tasks.The abstract model itself is quite flexible,making it adaptable to different execution environments,from iPhones to Apple Watches, to servers and more.It also allowed for customization on key points to make it work togetherwith code that Swift Concurrency has not fully adopted yet.For more information, see our "Behind the Scenes" talk,evenals "Beyond the basics of Structured Concurrency."I want to close with a bit of a case study on how Swift worksin an environment very different from the iOS or MacOS appswhere we are used to seeing it.FoundationDB is a distributed database that provides a scalable solutionfor very large key-value stores running on basic hardwareand supports various platforms, including MacOS, Linux, and Windows.
FoundationDB is an open source project with a large code base written in C++.The code is heavily asynchronous,with its own form of distributed actors and runtimewhich provides an extremely important deterministic simulation environmentfor testing purposes.FoundationDB wanted to modernize their code baseand felt that Swift was a good match for his performance,security and clarity of the code.A complete rewrite would be a big, risky undertaking.Instead, we took advantage of Swift's interoperabilityintegrate into the existing code base.For example, here is part of the C++ implementationvan FoundationDB's "master data" actor.
There's a lot going on hereand you don't need to understand everything about C++.However, I want to point out some important aspects of the code.First, C++ has no async/wait,so FoundationDB has its own preprocessor-like approachto imitate it.
Like many C++ codebases,they implemented their own C++ Future typeto manage asynchronous tasks.
Combine these with explicit messagesto send responses to the requests.Please pay attention to the careful linking of sendinga response with return of the function.Finally, FoundationDBits own reference-counted smart pointersto help manage memory automatically.We can implement all of thismuch cleaner in Swift.
That's better.This function can be implemented directly in Swift as an asynchronous function.We have a normal return type and normal return statementsto provide the answer to this request so that you are never out of step.We have a "guard" to indicate the suspension pointin the same way as any other Swift asynchronous code.And this Swift code is in line with the C++ Future typemodified using continuations.
We use a number of C++ types here.The MasterData type in C++ used a credential-counted smart pointer.Annotating the type in C++ allows the Swift compiler to use itthis type like any other class,automatically manage reference counts for us.
Other types, such as the request and response types,are C++ value types used directly in Swift.And the interoperability goes both ways.This asynchronous function,and indeed, all the work introduced by the Swift concurrency model,run on the existing FoundationDB deterministic runtime.So that we can get the benefits of Swift where we want it,interface with the existing C++ to allow gradual adoption.
We covered a lot of ground in this session.We have described functions such as parameter packsand macros that enable more expressive APIsand can help you write better code faster.We talked about using Swift in performance sensitive codeand the introduction of non-copyable typesto provide resource management without credential counting overhead.
Then we dove into C++ interoperability,which supports using C++ APIs in Swift and vice versa,making it easier to bring the benefits of Swift to more of your code.
Finally, we talked about Swift's flexible concurrency modelcan adapt to countless environmentsacross devices and languages to make concurrency easier and more secure.Parameter packs, macros, non-copyable types,and all other language improvements in Swift 5.9 are designedand developed openly through the Swift Evolution process,and community feedback was critical in shaping these features.Swift 5.9 is the culmination of countless contributionsfrom members across the Swift community, including active design discussions,bug reports, pull requests, educational content and more.Thanks for making Swift 5.9 the great release it is.♪ ♪
A new version of SwiftUI came up with a new way to set gradients and shadows to views. Simply add gradients with colour and swiftUI will automatically generate a gradient layout for view. We can also use a shadow modifier to simply add a shadow effect to the view. There are two types of shadow drop and inner.What's new on Swift? ›
So Swift has dramatically improved any types. It's introduced the any keyword so you can see where you're using them. It allows you to pass them to generic arguments. It's abolished the restriction that kept many protocols from being used with them.What's new in Swift WWDC21? ›
In particular, it's not blocking a thread. This allows the Swift runtime to reuse the thread this function was running on for other work. This allows a very few threads to be shared among many asynchronous processes. Syntactically, the async and await keywords are used similarly to throws and try.What's the latest version of Xcode? ›
Xcode 14 - Apple Developer.What are the downsides of SwiftUI? ›
SwiftUI's restricted support for earlier iOS versions is one of its key downsides. Developers who want to support iOS versions prior to iOS 13 may need to utilize an alternative framework since SwiftUI is only accessible on iOS 13 and later.
The framework is designed to make it easy for developers to build complex UIs using simple and declarative syntax. While SwiftUI has gained popularity among developers due to its ease of use, the question remains: is it production-ready? The short answer is YES, SwiftUI is production-ready.What crypto will replace Swift? ›
Ripple to replace SWIFT – Newest GPI direct response to ODL's expansion to more than 40 countries.What are the new Swift 5 features? ›
- Async await.
- Async sequences.
- Effectful read-only properties.
- Structured concurrency.
- async let bindings.
- Continuations for interfacing async tasks with synchronous code.
- Global actors.
Integrating with Swift Concurrency
To integrate with the async - await syntax in Swift 5.5, Future can provide its value to an awaiting caller. This is particularly useful because unlike other types that conform to Publisher and potentially publish many elements, a Future only publishes one element (or fails).
Swift is an easy-to-learn programming language that even new iOS developers can pick up. Swift's syntax is very similar to Python, another popular programming language, so it may be less challenging than other languages out there, making the transition smoother.
In summary, SwiftUI is ideal for creating apps with simple to medium-complexity interfaces that need to be developed quickly. It is excellent for prototyping and testing new ideas and creating simple UIs for your app. UIKit, on the other hand, is ideal for creating more complex interfaces with advanced functionality.What's new in Swift 5 5? ›
Raw strings, future enum cases, compactMapValues(), and more! Swift 5.0 is the next major release of Swift, and brings ABI stability at long last. That's not all, though: several key new features are already implemented, including raw strings, future enum cases, a Result type, checking for integer multiples and more.Can Xcode run Python? ›
"How to use Xcode IDE for Python development Open Xcode and start with creating a new project: From the templates, choose Cross-platform > External Build System Give it a name. You can update Organizatin Name and Identifier if you want. Make sure you enter a correct path for Python bin.Which is better Xcode or Visual Studio? ›
Microsoft Visual Studio has 2788 reviews and a rating of 4.62 / 5 stars vs Xcode 12 which has 39 reviews and a rating of 4.49 / 5 stars.What is latest Swift version? ›
Swift 5.5, officially announced by Apple at the 2021 WWDC, significantly expands language support for concurrency and asynchronous code, notably introducing a unique version of the actor model.Which architecture is best for SwiftUI? ›
The leading architecture often proposed is MVVM (Model-View-View Model). That said, it really should be written as Model — View Model — View (MVMV), since the View Model exists to mediate between your application's data (the model) and the requirements of the view (the layout).Is SwiftUI the future of iOS development? ›
SwiftUI is the way to go if you want to build awesome user interfaces on Apple platforms. It's a declarative framework that makes it super easy to create your views, and it's constantly evolving.Which is better SwiftUI or storyboard? ›
Better Source Control
SwiftUI is all Swift, at home in source code control systems. Handling merge conflicts on SwiftUI files is like handling any other Swift source files. However, a storyboard file is a large and complex machine-generated XML file, making merge conflicts almost nerve-wracking to resolve.
How Long Does It Take to Learn Swift? It takes around one to two months to develop a basic understanding of Swift, assuming you devote about an hour a day to studying. If you study part-time or full-time, you can learn the fundamentals of Swift in a shorter period of time.Can you make a game in SwiftUI? ›
It's a simple game that's truly addictive. We were also “infected” with the Wordle hype, played a lot, and realized that it's the perfect project for getting started with SwiftUI! So in less than two days, we built the game from scratch in SwiftUI. In this article, we're going to show you how.
SwiftUI is supported only from iOS 13 and higher.Could Russia use crypto instead of SWIFT? ›
Despite fears, crypto is no viable alternative to SWIFT for sanctioned Russian banks.Who are competitors to SWIFT? ›
swift.com's top 5 competitors in April 2023 are: epaynetwork.com, omgeo.com, euroclear.com, iotafinance.com, and more.Who competes with SWIFT? ›
|MARUTI SUZUKI SWIFT PETROL-AUTOMATIC | BUYING RECOMMENDATION|
|VXI||Rank 3||Suitable for budget buyers; consider upgrading to ZXI for better value and features|
|ZXI||Rank 1||Top recommended|
|ZXI Plus||Rank 2||Value upgrade over ZXI variant|
5.99 Lakh and goes upto Rs. 9.03 Lakh. Maruti Swift is offered in 11 variants - the base model of Swift is LXI and the top variant Maruti Swift ZXI Plus DT AMT which comes at a price tag of Rs. 9.03 Lakh.Is new Swift worth buying? ›
Yes new swift is the best car in the segment but swift falls on NCAP crash test and scores only 2 stars on safety. Maruti Swift interior quality is not best in its class, poor rear glass area and not much airy, falls on safety features, light weight, build quality is not best in its class.Is Swift worth learning in 2023? ›
If you want to build applications for iOS, iPadOS, macOS, tvOS, and watchOS, you should learn Swift. If you are interested in working on web development, machine learning, automation tools, and data science, you should learn Python.Does Apple own Swift? ›
Swift is a robust and intuitive programming language created by Apple for building apps for iOS, Mac, Apple TV, and Apple Watch. It's designed to give developers more freedom than ever.Why isn t Swift more popular? ›
There's a few reasons, but mostly is due to economics and the way Apple builds its own software. Swift came out of the iOS side of the company, and was sponsored to make writing iOS apps easier. It was therefore constrained to fit into a particular shape; in particular, Objective-C compatibility was a must have.
Swift is easy to learn, even without prior experience in coding. Apple designed it to be a programming language suitable for beginners, efficient, and easy to use. First-time coders can download Swift Playgrounds to learn the coding language with gamified Apple-designed lessons.Does Apple hire Swift developer? ›
Many roles at Apple also require knowledge of Swift and Objective-C, the core programming languages of the Apple ecosystem. If you want a role at the company that overlaps in any way with iOS, macOS, or any of its other software platforms, you'll need to know these languages.Is Swift faster than C++? ›
Swift is an evolution of Objective C, whereas C++ is an evolution of C. C++ is known to many for its excellent performance and is typically somewhat faster than Swift code but due to Apple's OS dominance in the mobile space, creating mobile apps with C++ may be futile.Should I learn UIKit or SwiftUI 2023? ›
Learn UIKit: It's great and a mature technology
UIKit has a long history at the heart of Apple's mobile development ecosystem. UIKit is unlikely to die. There are so many applications working with UIKit, and the interoperability between UIKit and SwiftUI means that it is likely that hybrid Apps will be around… well.
Each project will have its own use cases for SwiftUI or UIKit, however in the future Apple will begin deprecating UIKit. This is due to SwiftUI being better optimized for newer devices. As well as providing more powerful code elements, which enables developers to create better apps.What big apps use SwiftUI? ›
- 2021 Best Open Source iOS Apps written in SwiftUI. Asil Arslan. ...
- Wiggles. Beautiful Puppy adoption app built to Demonstrate the SwiftUI and MVVM Architecture. ...
- Expense Tracker. ...
- Word Of The Day. ...
- Bank App. ...
- ClassifiedAds. ...
- GradeCalc — GPA Calculator. ...
- Hour Blocks: Day Planner.
However, if you are wondering about the Swift 4 vs Swift 5 difference, let us make it clear for you. Swift 5 improves Swift 4.2 by adding a slew of new features and stabilising the language's ABI. This is a significant turning point in the evolution of the language, as there will be fewer changes in the future.What changes from Swift 4 to 5? ›
A “Swift” guide of migrating your code from Swift 4 to Swift 5. It's the next major release of Swift and it brings ABI Stability at last. Besides this, several new key features are also added which include raw Strings, future enum cases, a Result type, checking multiple integers and more.What is Swift 4? ›
Swift 4 is a new programming language developed by Apple Inc for iOS and OS X development. Swift 4 adopts the best of C and Objective-C, without the constraints of C compatibility. Swift 4 makes use of safe programming patterns. Swift 4 provides modern programming features.Is Xcode just a IDE? ›
What is Xcode? Xcode is Apple's IDE or integrated development environment. This simply means that Xcode provides you with the tools to create software that runs on Apple's platforms, iOS (and iPadOS), tvOS, macOS, and watchOS.
This tutorial will get you set up to do C or C++ development with XCode, but you can also use XCode for iPhone and iOS development. Installing XCode will give you access to a powerful IDE as well as command line tools like gcc and g++ in addition to a graphical IDE. (You need to install XCode even to get g++ and gcc.)Is Xcode an IDE or compiler? ›
Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, tvOS, and visionOS.Is Xcode better than code blocks? ›
Compare Code::Blocks and Xcode
based on preference data from user reviews. Code::Blocks rates 4.4/5 stars with 84 reviews. By contrast, Xcode rates 4.2/5 stars with 938 reviews.
Platform Focus: Visual Studio Code is a cross-platform tool, compatible with Windows, macOS, and Linux, making it suitable for developers working on different operating systems. Xcode is exclusively designed for macOS, limiting its availability to Apple developers working on macOS and iOS projects.What is Xcode best for? ›
Xcode provides all tools to create apps (design, develop, and publish) for all Apple's platforms: iOS, iPadOS, tvOS, watchOS, and macOS. In addition, Xcode supports the source code for many popular programming languages, including Swift, Objective-C, Objective-C++, C, C++, Java, Python, and more.What's new in Swift wwdc22? ›
The new Swift Concurrency view in Instruments can help you investigate performance issues. The Swift Tasks and Swift Actors instruments provide a full suite of tools to help you visualize and optimize your concurrency code.What language is Swift written in? ›
The Swift compiler is written mostly in C++, and this won't change in the near future. You can extend the standard library using Swift, but if you want to contribute a new language feature or some optimization, you'll need to write C++.What language is Swift most similar to? ›
This year, we can take on more challenging apps thanks to SwiftUI's maturity, with new features like concurrency with async / await, SF Symbols 3 with new styles, Markdown support using Text, button styles, swipe actions, blur materials, drawing graphics with canvas and much more.What's new in SwiftUI iOS 14? ›
Adaptive layout — here the grid will try to add as many items of the minimum size into each row in the grid based on the width of the grid. Flexible layout — here you can specify the number of columns in the grid, and each of which takes equal spaces by default.
- Design. Xcode 13 introduces a new file icon according to file type. ...
- Autocompletion improvement. Automatic import. ...
- Column breakpoint. Now you can add a breakpoint in a certain point instead of the whole line.
- Version control. Apple introduced version control in Xcode. ...
- Xcode Cloud. Select the Archive Action.
Although you can use any design pattern to build your SwiftUI apps, MVVM pattern is preferred due to the declarative nature of the SwiftUI framework.What is the newest version of SwiftUI? ›
SwiftUI 4.0: New and updated APIs with code examples.What are the different animations in SwiftUI? ›
In SwiftUI, Animation is nothing but the change of the state from start to finish with different curves and velocities. The syntax is mostly easy to understand and quick to implement. Animating is quite easy with the use of different implicit animation like easeIn, easeOut, linear, spring, and interpolating spring.What is the difference between Xcode 13 and 14? ›
Lighter Xcode with optional SDKs
Xcode 14 is about 30% percent smaller than Xcode 13. For example, Xcode 13.4. 1 is roughly 10 GB, while Xcode 14 Beta 3 is only 7 GB. watchOS and tvOS are also available as optional SDKs that you can download separately if you are building apps for these platforms.
With iOS 13, UIImage has been added with wide variety of system icons with addition of many graphics that represent system glyphs such as forwad and backward arrows. With iOS 13, Apple had introduced over a range of 1500 icons with differnt of weights and sizes.
Xcode 14 eliminates scheduling dependencies between targets and test classes to increase parallelism during testing even more. If you have long-running tests in different test classes and targets, this feature could improve your test execution time by up to 30 percent.Is iOS developer a good career in 2023? ›
iOS development is in high demand because it allows you to be creative and a problem-solver. These are the two most important skills that can lead to a fulfilling career but aren't always found in a single position.Which architecture is better for SwiftUI? ›
The leading architecture often proposed is MVVM (Model-View-View Model). That said, it really should be written as Model — View Model — View (MVMV), since the View Model exists to mediate between your application's data (the model) and the requirements of the view (the layout).What are the iOS app development trends for 2023? ›
The creation of iOS apps in 2023 is crucial to the virtual world. You may now concentrate on developing real-time applications for improved user experiences. Augmented Reality(AR) and Virtual Reality(VR) make this possible, cementing their position as the next significant iOS app development trends in 2023.