The document discusses several interesting features of the Swift programming language, including type inference, mutability, optionals, named parameters, enumerations, switch statements, closures, and generics. Type inference allows variable types to be inferred from values rather than explicitly declared. Optionals handle the absence of values and can be conditionally unwrapped. Closures provide block syntax similar to Objective-C but with additional optional syntax. Generics allow structures to work with different types rather than a single type.
Swift is a new programming language introduced by Apple for iOS and Mac app development. It has the best of both C and Objective-C with speed, interactivity and modern conventions.
Introduction to Swift programming language.Icalia Labs
Take a look to Swift, if you've been developing for iOS in Objective-C many things may look familiar, maybe just "upgraded". If you're a first timer diving into iOS development we strongly recommend you to understand first the basics of Cocoa.
We have this new language, Swift, which takes some familiar Apple patterns, and introduces some new ones. With tools like closures and method chaining, there are definitely some new ways to solve the age-old Obj-c architecture challenges. This talk will walk through some of the most common Obj-c design patterns rewritten in Swift, and showcase the strengths and weaknesses of this new language.
Swift is a new programming language introduced by Apple for iOS and Mac app development. It has the best of both C and Objective-C with speed, interactivity and modern conventions.
Introduction to Swift programming language.Icalia Labs
Take a look to Swift, if you've been developing for iOS in Objective-C many things may look familiar, maybe just "upgraded". If you're a first timer diving into iOS development we strongly recommend you to understand first the basics of Cocoa.
We have this new language, Swift, which takes some familiar Apple patterns, and introduces some new ones. With tools like closures and method chaining, there are definitely some new ways to solve the age-old Obj-c architecture challenges. This talk will walk through some of the most common Obj-c design patterns rewritten in Swift, and showcase the strengths and weaknesses of this new language.
A brief look at the new features coming in Javascript ES6:
- Scope and control
- Iterators and Generators
- Collections
- Typed objects
- Direct proxies
- Template strings
- API improvements
- Modularity
FITC events. For digital creators.
Save 10% off ANY FITC event with discount code 'slideshare'
See our upcoming events at www.fitc.ca
An Intro To ES6
with Grant Skinner
OVERVIEW
ECMAScript 6 is the approved and published standard for the next version of JavaScript. It offers new syntax and language features that provide new ways of tackling coding problems, and increase your productivity.
This session will introduce ES6 and delve into many of the new features of the language. It will also cover real-world use, including transpilers, runtimes, and browser support.
OBJECTIVE
Create confidence in evaluating and getting started using ES6.
TARGET AUDIENCE
JavaScript developers.
ASSUMED AUDIENCE KNOWLEDGE
JavaScript.
FOUR THINGS AUDIENCE MEMBERS WILL LEARN
Status of ES6
How to get started with ES6
ES6 feature overview
Practical considerations for adopting ES6
This contains all the slides used in Silicon Valley Code Camp presentation on Sunday Oct 4, 10:45 session on "Amazing new features in JavaScript". At the end ut also includes the last year presentation covering ES 5
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
An overview of some of the history of JavaScript, how it became ECMAScript (and what Ecma is), as well as highlights of the new features and syntax in ES6 aka ES2015.
Originally presented to the New York Public Library on June 4 2015.
In which Richard will tell you about some things you should never (probably ever) do to or in Python. Warranties may be voided. The recording of this talk is online at http://www.youtube.com/watch?v=H2yfXnUb1S4
Highlights a bunch of different Python tricks and tips - from the stupid to the awesome (and a bit of both).
See how to register a 'str'.decode('hail_mary') codec, call_functions[1, 2, 3] instead of call_functions(1, 2, 3), creating a "Clojure-like" threading syntax by overloading the pipe operator, create useful equality mocks by overloading the equality operator, ditch JSON for pySON and put together a tiny lisp based on Norvig's awesome article.
Functional Pe(a)rls - the Purely Functional Datastructures editionosfameron
All new material, this time about one of the fundamental functional datastructures, the Linked List, and the overview of an implementation in Moosey Perl.
This covers some of the same material as https://github.com/osfameron/pure-fp-book but perhaps with more explanation (and covering much less material - it was only a 20 minute talk)
From session at http://www.lambdalounge.org.uk/ on 18th April 2016. Here's the original blurb:
So, Haskell is "an advanced purely-functional programming language" which supports writing "declarative, statically typed code". It may be optimized for academic buzzwords you've never heard of but... is it any good for writing code in the way that you'd write Perl, Python, or Ruby?
What are strong types, and why are we so frightened of them anyway? Can you develop interactively in Haskell, the way you would in a dynamic language?
Does Haskell have "whipuptitude" (being able to get things done quickly) as well as "manipulexity" (being able to manipulate complex things)? And perhaps most importantly, can writing Haskell be *fun*?
Haskell is founded on decades of the finest mathematical and computer science research. Perl, quite demonstrably isn't... but why do so many Perl programmers also love Haskell?
Audrey Tang wrote the first prototype for Perl 6, Pugs, in Haskell, and coined the phrase "lambdacamel" for the substantial crossover between the languages.
What does a Perl programmer make of Haskell? What are the lessons that can be learned (in either direction). And do the languages have more in common than you might have thought?
... now write an interpreter (PHPem 2016)James Titcumb
Second half of my two part series on interpreters. In this, I demonstrate how easy it is to write a very basic maths sum interpreter, including a live demo of adding a new language feature!
Make beautiful plots and graphs using the open source R programming language.
How we represent our data is often as important as the quality of the data itself. In this course, you will learn how to make functional and elegant plots using the R language. R is a free/open source programming language that has become very popular in academia and among data scientists across all disciplines.
In this course, you will learn how to quickly make
bar plots
scatter plots
line plots
pie charts
and more...
You will also learn how to show trends over time and how to plot correlations and geographical data in this course.
This course is intended for students, professional, entrepeneurs and everyone in between.
Happy Plotting!
A brief look at the new features coming in Javascript ES6:
- Scope and control
- Iterators and Generators
- Collections
- Typed objects
- Direct proxies
- Template strings
- API improvements
- Modularity
FITC events. For digital creators.
Save 10% off ANY FITC event with discount code 'slideshare'
See our upcoming events at www.fitc.ca
An Intro To ES6
with Grant Skinner
OVERVIEW
ECMAScript 6 is the approved and published standard for the next version of JavaScript. It offers new syntax and language features that provide new ways of tackling coding problems, and increase your productivity.
This session will introduce ES6 and delve into many of the new features of the language. It will also cover real-world use, including transpilers, runtimes, and browser support.
OBJECTIVE
Create confidence in evaluating and getting started using ES6.
TARGET AUDIENCE
JavaScript developers.
ASSUMED AUDIENCE KNOWLEDGE
JavaScript.
FOUR THINGS AUDIENCE MEMBERS WILL LEARN
Status of ES6
How to get started with ES6
ES6 feature overview
Practical considerations for adopting ES6
This contains all the slides used in Silicon Valley Code Camp presentation on Sunday Oct 4, 10:45 session on "Amazing new features in JavaScript". At the end ut also includes the last year presentation covering ES 5
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
An overview of some of the history of JavaScript, how it became ECMAScript (and what Ecma is), as well as highlights of the new features and syntax in ES6 aka ES2015.
Originally presented to the New York Public Library on June 4 2015.
In which Richard will tell you about some things you should never (probably ever) do to or in Python. Warranties may be voided. The recording of this talk is online at http://www.youtube.com/watch?v=H2yfXnUb1S4
Highlights a bunch of different Python tricks and tips - from the stupid to the awesome (and a bit of both).
See how to register a 'str'.decode('hail_mary') codec, call_functions[1, 2, 3] instead of call_functions(1, 2, 3), creating a "Clojure-like" threading syntax by overloading the pipe operator, create useful equality mocks by overloading the equality operator, ditch JSON for pySON and put together a tiny lisp based on Norvig's awesome article.
Functional Pe(a)rls - the Purely Functional Datastructures editionosfameron
All new material, this time about one of the fundamental functional datastructures, the Linked List, and the overview of an implementation in Moosey Perl.
This covers some of the same material as https://github.com/osfameron/pure-fp-book but perhaps with more explanation (and covering much less material - it was only a 20 minute talk)
From session at http://www.lambdalounge.org.uk/ on 18th April 2016. Here's the original blurb:
So, Haskell is "an advanced purely-functional programming language" which supports writing "declarative, statically typed code". It may be optimized for academic buzzwords you've never heard of but... is it any good for writing code in the way that you'd write Perl, Python, or Ruby?
What are strong types, and why are we so frightened of them anyway? Can you develop interactively in Haskell, the way you would in a dynamic language?
Does Haskell have "whipuptitude" (being able to get things done quickly) as well as "manipulexity" (being able to manipulate complex things)? And perhaps most importantly, can writing Haskell be *fun*?
Haskell is founded on decades of the finest mathematical and computer science research. Perl, quite demonstrably isn't... but why do so many Perl programmers also love Haskell?
Audrey Tang wrote the first prototype for Perl 6, Pugs, in Haskell, and coined the phrase "lambdacamel" for the substantial crossover between the languages.
What does a Perl programmer make of Haskell? What are the lessons that can be learned (in either direction). And do the languages have more in common than you might have thought?
... now write an interpreter (PHPem 2016)James Titcumb
Second half of my two part series on interpreters. In this, I demonstrate how easy it is to write a very basic maths sum interpreter, including a live demo of adding a new language feature!
Make beautiful plots and graphs using the open source R programming language.
How we represent our data is often as important as the quality of the data itself. In this course, you will learn how to make functional and elegant plots using the R language. R is a free/open source programming language that has become very popular in academia and among data scientists across all disciplines.
In this course, you will learn how to quickly make
bar plots
scatter plots
line plots
pie charts
and more...
You will also learn how to show trends over time and how to plot correlations and geographical data in this course.
This course is intended for students, professional, entrepeneurs and everyone in between.
Happy Plotting!
Mindbody: A Digital Transformation Story. A presentation by Mindbody's Alex McClure at Apigee's Adapt or Die, San Francisco 2016. See events.apigee.com
The path to becoming an "uncarrier" required some serious changes in how T-Mobile's IT organization worked.
See how T-Mobile successfully adapted and evolved their digital journey. T-Mobile's Himanshu Kumar and Apigee's Paul Williams walk through key business and technical aspects of the journey.
Consultant Robert Broeckelmann shares his experience of implementing API management in a large enterprise and will share how to:
- define API governance
- explore the goals, requirements, implementation of API governance
- look at lessons learned from implementing one enterprise customer's API governance process
Developers are increasingly using Kubernetes to deploy, scale, and manage their containerized applications. So, how can you securely manage and gain visibility for the APIs deployed for these applications?
This webcast will cover:
- how native integration allows app developers to easily manage application endpoints
- how to transparently add security [oauth/key] for your application containers and endpoints
- how to transparently manage traffic and track analytics for endpoints exposed through Kubernetes
Are you stuck in the Java world? I’ll share my story about convincing my team and the client of the benefits of Kotlin. Furthermore I’ll delve into how we migrated an existing Java Android app, with 300k active users, to Kotlin.
Even if you have never seen Kotlin before, come and see how you will create better apps with this modern and elegant language. At the end of this talk you’ll be able to convince your team / client why it’s a great to use Kotlin.
The power of Kotlin can be leveraged everywhere you use Java, since it compiles to JVM bytecode. So even if you’re not an Android developer, check out this session to get acquainted with Kotlin!
No excuses: switch to Kotlin
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdfAndrey Breslav
New languages are inspired by existing languages: every generation learns from the previous one. Kotlin is no exception: its design is based substantially on the designs of languages such as Java, Scala, C#, Groovy, Python, Nice, etc. This talk will explain which parts of the design are inspired by which languages and what Kotlin does differently in each case.
Are you stuck in the Java world? I’ll share my story about convincing my team and the client of the benefits of Kotlin. Furthermore I’ll delve into how we migrated an existing Java Android app, with 300k active users, to Kotlin. Even if you have never seen Kotlin before, come and see how you will create better apps with this modern and elegant language. At the end of this talk you’ll be able to convince your team / client why it’s a great to use Kotlin. The power of Kotlin can be leveraged everywhere you use Java, since it compiles to JVM bytecode. So even if you’re not an Android developer, check out this session to get acquainted with Kotlin! No excuses: switch to Kotlin :)
Introducing Kotlin — JVM-based language made by JetBrains. Kotlin takes aim at the age and perceived uncoolness of the Java with fresh and popular language features. It can do anything the Java language can do and more, but often with a more concise and pleasant syntax.
Similar to A Few Interesting Things in Apple's Swift Programming Language (20)
Elixir is great for web servers and embedded devices, but is there anything else it’s good for?
Yes! Elixir is also great at being a multiplayer game server.
We’ll take a look through some existing applications that use Elixir as a multiplayer backend server, ExVenture and Kalevala.
See how they’re architected to be full of state and event driven to handle thousands of users.
DC |> Elixir Meetup - Going off the Rails into Elixir - Dan IvovichSmartLogic
Presentation from DC |> Elixir, March 19, 2019. Covered transitioning from Ruby on Rails to Elixir and Phoenix, and why developers want to make that transition, and why management should be supportive of that transition.
Monitoring Your Elixir Application with PrometheusSmartLogic
Get under the hood of your application, with metrics! What is your slowest external call? What are your total daily interactions? Find out with Prometheus!
We’ll use Prometheus and Grafana to give us insights into your application. Prometheus will gather time series metrics, and Grafana will give a powerful display of them.
We’ll cover how to add instrumentation through the lens of a real-world application.
Finally, we'll get alerted about key metrics via the Prometheus AlertManager.
You have an application that works well on a single node, and you’ve heard that Erlang lets you scale out in a cluster. How do you go about doing that?
We’ll walk through the steps I took to turn ExVenture (a multiplayer game server) into a distributed application.
Starting with connecting nodes in development and production, to picking a cluster leader via the Raft protocol, and dealing with process groups to fan calls throughout the cluster.
Finally we’ll see some of the hurdles I encountered when spanning multiple nodes.
SmartLogic's Eric Oestrich discusses Kubernetes at Baltimore Innovation Week. Kubernetes is a webscale cluster manager. By the end of the talk we will have a Rails application hosted inside of Kubernetes, Google's new cluster manager.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
3. Some Cool Stuff
● Type Inference
● Explicit Mutability
● Optionals
● Named Parameters
● Enumerations
● Exhaustive Switch
● Closures
● Generics
4. Type Inference
You can do this:
var x : Int = 0
var y : String = “foobar”
var z : Bool = true
Or, you can just do this:
var x = 0
var y = “foobar”
var z = true
9. Optionals
Optionals handle the absence of a value.
Either:
1. there is some value, and it equals x
var foo : Int? = 41 // { Some 41 }
1. or, there is no value at all
var bar : Int? // nil
11. Optionals: Unwrapping
You can unwrap the value contained in the
optional by using the bang operator, like so:
var foo : Int? = 41
foo! == 41 // true
But if it’s nil, you will get a runtime error,
so don’t do that.
12. Optional Binding
var possibleNumber = "2"
if let actualNumber =
possibleNumber.toInt() {
println("(possibleNumber) has an integer
value of (actualNumber)")
} else {
println("(possibleNumber) could not be
converted to an integer")
}
13. Optional Chaining
class Person {
var name : String
var address : Address?
init(name:String, atAddress address:Address?=nil) {
self.name = name
self.address = address
}
}
class Address {
func sendLetter() {
println("Sent a letter!")
}
}
let ara = Person(name: "Ara")
let paul = Person(name: "Paul", atAddress:Address())
let people = [ara, paul]
for person in people {
person.address?.sendLetter()
}
16. Exhaustive Switch
In Swift, the compiler enforces that a switch statement contains a case
for every possible value for that type.
enum Status {
case OnTime, Delayed(Int, String)
}
let trainStatus = Status.Delayed(5, “banana on tracks”)
switch trainStatus {
case .OnTime:
println(“Train is on time!”)
case .Delayed(let minutes, let reason):
println(“Train delay: (minutes) minute(s), Reason: (reason)”)
17. Closures
Just like blocks in ObjC...but there’s a lot of optional syntax.
let names = ["Paul", "Ara", "Eric", "Tom", "Dan"]
func backwards(s1: String, s2: String) -> Bool {
return s1 > s2
}
1. sort(names, backwards)
2. sort(names, { (s1: String, s2: String) -> Bool in return s1 > s2
})
3. sort(names, { s1, s2 in return s1 > s2 } )
4. sort(names, { s1, s2 in s1 > s2 } )
5. sort(names, { $0 > $1 } )
6. sort(names, >)
“Swift is a type safe language. A type safe language encourages you to be clear about the types of values your code can work with. If part of your code expects a String, you can’t pass it an Int by mistake.
Because Swift is type safe, it performs type checks when compiling your code and flags any mismatched types as errors. This enables you to catch and fix errors as early as possible in the development process.”
But it also has a feature called Type Inference which means if the compiler can infer the type of a variable from the context of its declaration, you don’t need to explicitly write the type, it will be inferred.
Type inference means, that you even if you don’t provide a type annotation, but the var is still strongly typed -- so you can’t clobber it with a different type.
Swift provides two collection types: arrays and dictionaries, for storing collections of values.
Collections are strongly typed, so you can’t insert the wrong value into a collection, and you always know what you’re going to get when you retrieve a value.
As with other types, the type can be inferred
For collections:
an array = can’t change the size, but can’t replace a value at an index
dictionary = can’t change values
Values of most types can never be nil.
Every value must be initialized before it is used.
So how do you deal with the possibility of the absence of a value?
Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes.”
“Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with.”
Use optionals to safely work with possibly missing values:
missing values are nil
present values are wrapped in an optional
“Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes.”
“Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with.”
“Swift’s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a non-existent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.”
Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes.”
“Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with.”
Use optionals to safely work with possibly missing values:
missing values are nil
present values are wrapped in an optional
var possibleNumber = "2"
if let actualNumber = possibleNumber.toInt() {
println("(possibleNumber) has an integer value of (actualNumber)")
} else {
println("(possibleNumber) could not be converted to an integer")
}
Say we have a person -- and people in our domain always have names, but they may not have addresses. So we have the name type as a String, but the address type is an optional Address class. We have this instance method (function) on Address called sendLetter, and we want to send a letter to each person who has an address.
DEMO
so, if the optional is nil it just swallows the method call. No undefined method for nilclass error.
One of the nice things, I think, about Objective C its verbosity. I like the self-documenting nature of named parameters. Swift is a lot more flexible in that it lets you use named parameters or get rid of them all together, or even use different external param names for callers than the names used within the function definition.
Enumerations define a type for a group of related values and you can work with those values in a type-safe way. Some cool things about enumerations in Swift, is 1) they don’t need member values, unlike in C, North, South, East, West don’t equal 1, 2, 3, or 4 or whatever.
Another cool thing is an enumeration can have associated values. So, if you have a Status enum with a status of OnTime and of Delayed -- the Delayed status can have an associated delay of minutes and maybe a string that contains the reason for the delay.
Swift has a really powerful switch statement. It is exhaustive, which means the compiler forces you to check for every possible value for the type that you are checking. Now, if you are switching on integers you don’t have to have a line for ‘n’ to infinity -- you can use the default case.
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. One of the coolest things about closures is that closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables, hence the name “closures”. Ruby has closures in the form of lambdas and procs, so I don’t really need to say much about them in Swift, other than to show the expression syntax for them in Swift.
struct Stack<T> {
var items = T[]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
}
var stack = Stack<String>()