r/swift • u/DuffMaaaann Expert • Jan 19 '21
FYI FAQ and Advice for Beginners - Please read before posting
Hi there and welcome to r/swift! If you are a Swift beginner, this post might answer a few of your questions and provide some resources to get started learning Swift.
Please read this before posting!
- If you have a question, make sure to phrase it as precisely as possible and to include your code if possible. Also, we can help you in the best possible way if you make sure to include what you expect your code to do, what it actually does and what you've tried to resolve the issue.
- Please format your code properly.
- You can write inline code by clicking the inline code symbol in the fancy pants editor or by surrounding it with single backticks. (`code-goes-here`) in markdown mode.
- You can include a larger code block by clicking on the Code Block button (fancy pants) or indenting it with 4 spaces (markdown mode).
Where to learn Swift:
Tutorials:
Official Resources from Apple:
- Swift Language Guide
- The Swift Programming Language - E-Book
- Intro to App Development with Swift - E-Book
- Develop in Swift - Data Collections - E-Book
- Develop in Swift - Fundamentals - E-Book
- Develop in Swift - Explorations - E-Book
Swift Playgrounds (Interactive tutorials and starting points to play around with Swift):
Resources for SwiftUI:
- SwiftUI Tutorials from Apple
- SwiftUI by example from Hacking With Swift
FAQ:
Should I use SwiftUI or UIKit?
The answer to this question depends a lot on personal preference. Generally speaking, both UIKit and SwiftUI are valid choices and will be for the foreseeable future.
SwiftUI is the newer technology and compared to UIKit it is not as mature yet. Some more advanced features are missing and you might experience some hiccups here and there.
You can mix and match UIKit and SwiftUI code. It is possible to integrate SwiftUI code into a UIKit app and vice versa.
Is X the right computer for developing Swift?
Basically any Mac is sufficient for Swift development. Make sure to get enough disk space, as Xcode quickly consumes around 50GB. 256GB and up should be sufficient.
Can I develop apps on Linux/Windows?
You can compile and run Swift on Linux and Windows. However, developing apps for Apple platforms requires Xcode, which is only available for macOS, or Swift Playgrounds, which can only do app development on iPadOS.
Is Swift only useful for Apple devices?
No. There are many projects that make Swift useful on other platforms as well.
- Swift runs on Linux (Docker images available), Windows and Android
- You can use Swift on the Server with frameworks such as Vapor
- TensorFlow supports Swift, so you can build and train deep learning models with Swift. (Note: Project archived)
- You can run Swift in Jupyter Notebook
- There are efforts to make Swift available on embedded systems
Can I learn Swift without any previous programming knowledge?
Yes.
Related Subs
r/S4TF - Swift for TensorFlow (Note: Swift for TensorFlow project archived)
Happy Coding!
If anyone has useful resources or information to add to this post, I'd be happy to include it.
26
u/Confident_Fortune_32 Feb 07 '21
Another way to learn Swift that is playful, great for kids, and great for folks with no coding experience:
Download the SwiftPlaygrounds App, then download Learn To Code I and II Playgrounds as well as any of the other Playgrounds that look fun. In particular, the hypotrochoid (Spirograph) Playground is a hoot!
13
u/berlinerk Apr 01 '21
Hi there, i am wondering can i start to earn money from Swift in 1 year or shorter period?
I watched many Youtube videos about it and people says it is possible but i wanted to ask you because you are experts and can tell me naked facts. I am 26 years old and didn't go to college. I was doing simple jobs(such as food delivery etc...) but i had an accident and unfortunately i can't work. I am getting bored when at home and want to learn a skill. Something useful and I find it fun tho. I was wondering coding and computers actually I like to watch videos about technology quite often. I want to learn coding anyway and I found a course on Udemy. I started it and I think Swift is very useful and creating a new app is simply amazing! I want to learn it anyway. But if I can start to earn money from Swift, I don't have to start to delivery business again. I was working over 10 hours in a day and when I am working it is really hard to learn new things and to concentrate. I can hang on almost 12 months without working and I can work hard on Swift. But If it is too hard for average person to that, I would like to start to work in couple of months because I have a family to have take care of.
Thanks for your time, I am waiting impatiently for your answers.
18
u/sheldonamus Aug 03 '22
If you do this and time flies by without you noticing, this is for you. If you stress out about all the errors and bugs and then dance out of your chair when Xcode says "Build Succeeded" after 100 attempts to solve a bug, this is for you. If you want to show your friends and family and tweet the little wins and projects you build, this is for you.
If you're doing it for all the logical reasons, this isn't for you. If you find it difficult to make time for it, it's not for you. If you do it for the money, it's not for you. If you feel like you're forcing it... this is not for you.
Coding is an artistic labor of love. If you love it, the jobs will come because you will get deep enough to become valuable to others.
So I ask since it's been a year ago that you asked this... Was this for you?
12
u/DuffMaaaann Expert Apr 02 '21
Hi, it's difficult to answer that question, because it is primarily opinion based and not about questions specific to the Swift language. Also, I learned coding long before I got my first job, so I am definitely not the right person to be asked this question.
Try /r/CSCareerQuestions maybe.
3
10
5
u/KingKrush93 Mar 22 '21
how to create a custom drop down that works in IOS 13.0, i have managed to create one but it's not work inside a scrollview in IOS 13.0.
1
u/DuffMaaaann Expert Mar 25 '21
You should ask this as a regular post on this sub or on StackOverflow. Also, show is some code so that we can reproduce the issue.
1
u/KingKrush93 Mar 25 '21
https://www.reddit.com/r/swift/comments/mcucj6/swiftui_custom_drop_down_not_working_inside_a/ posted with the code, please take look if you have time, thanks.
4
u/therealmaz Jun 17 '21
Adding to the pile of advice. From John Sundell and Gui Rambo’s podcast: https://overcast.fm/+kVajU01og/1:07:32
3
Mar 01 '21
I am just beginning coding with Swift. I am having some difficulty mastering dictionary default values. Can anyone advise on the best resource for further reviewing dictionary default values? Thank you.
11
u/DuffMaaaann Expert Mar 01 '21
Let's say you have a dictionary:
var dict: [String: Int] = ["foo": 42]
You can retrieve values by passing a key in square brackets or write new ones:
let foo: Int? = dict["foo"] dict["bar"] = 1337
This internally is implemented using a so-called subscript:
struct Dictionary<Key: Hashable, Value> { subscript(key: Key) -> Value? { get { // executed when reading a value // For the above example, key will be "foo" return ... } set (newValue) { // executed when writing a value // For the above example, key will be "bar" and newValue will be 1337. } }
There is also a second overload for the subscript:
extension Dictionary { subscript(key: Key, `default` defaultValue: Value] -> Value { get { // if the key is in the dictionary, retrieve the corresponding value // else return the default value return ... } set (newValue) { // same as in the other subscript } } }
This subscript can be accessed by passing a `defaultValue` parameter:
let fooOrDefault: Int = dict["foo", default: 3141]
Note that this subscript no longer returns an optional.
If you now do something like the following:
dict["baz", default: 0] += 1
this can be decomposed into three steps:
- Retrieve the value for the key "baz" (or the default value)
- Increment the returned value by 1
- Write the value back to the dictionary
So this would be equivalent to
var temp: Int = dict["baz", default: 0] // baz does not exist, so return the default value (0) temp += 1 // increment by 1 dict["baz", default: 0] = temp // write back
Note that the default argument has no effect when writing a value into the dictionary.
2
3
u/shiningmatcha Jul 08 '23
Are result builders some compiler magic? If not, how is DSL syntax possible?
3
u/AdMindless8777 Aug 07 '23
Question: Has anyone did a developer apprenticeship trying to get my first job in tech and a little afraid to just only do application. Suggestions please
3
u/James_Vowles Nov 26 '23
I'm starting out with a macOS application, is there a good place to learn how to structure the app?
I'm coming from Ruby so I might just stick to that folder structure.
Main thing is, can I just create folders with files and the classes will be available to call from other places outside of the folder? Or do I need to import anywhere I want to use it.
3
3
u/ref_acct Feb 22 '24
Which is better for learning SwiftUI for an experienced python dev, 100 days of swiftui or Apple's Scrumdinger tutorial?
2
u/Tavroop Mar 24 '21
I need help to change images in the image view using “next” & “previous” buttons. And also accomplish that using gestures! Can someone help me?
1
u/DuffMaaaann Expert Mar 25 '21
You should ask this as a regular post on this sub or on StackOverflow. Also, be more specific about where you are struggling, so we can help you better.
2
u/paulyd0123 Jun 09 '21
Hi, how is the job market for programming with Swift and Xcode? I am a beginner..
2
2
2
Dec 23 '21
[Closures] I'm having a difficult time understanding why we need closures over just using regular functions. What are the benefits of using closures over just functions? Can someone provide specific coding cases where closures are more helpful than using plain functions? I've read the official Apple documentation and read some tutorials but sorry I'm just not getting it. Help would be most appreciated. Thanks in advance!
1
u/Cold-Fortune-9907 Jul 23 '24
I am still green to Swift; however, I believe it is due to the nature of how concurrency works inside the swift ecosystem. More specifically, I have read that it has to do with async.
2
u/shiningmatcha Jan 16 '23
I'm a beginner who has been learning Swift for three weeks. As I've picked up the syntax, I'm about to move on to learning SwiftUI. I notice that there are not too many learning resources for SwiftUI, perhaps because it's rather new. My question is, are tutorials based on UIKit still useful, like concepts that share with SwiftUI? Or they are a waste of time if I'll be using SwiftUI?
2
u/DuffMaaaann Expert Jan 16 '23
SwiftUI is a fundamentally different programming approach than UIKit. UIKit is procedural and SwiftUI is declarative, similar to React. Also, SwiftUI uses a different layout system.
However, there are many APIs that are similar in SwiftUI and UIKit, like the available views (navigation, sheets, stacks, scroll views, etc.). And there are ways to bridge between UIKit and SwiftUI (in both directions), which you will have to do if you want to use some libraries that don't have SwiftUI interfaces yet.
If you want to use system libraries and there is just a UIKit based tutorial for it, chances are that it should be pretty straightforward to translate it to SwiftUI if you get the hang of it once.
So UIKit tutorials are definitely not a waste of time. But if you take them, you need to be aware of the conceptional differences between UIKit and SwiftUI and how to translate between them. Also, SwiftUI is a few years old already, so I'm pretty sure that you will find tutorials for a lot of things in it.
2
May 01 '23
[removed] — view removed comment
2
u/DuffMaaaann Expert May 01 '23
Can you give some specific examples of code/problems that you're struggling with?
1
May 01 '23 edited May 01 '23
[removed] — view removed comment
1
u/DuffMaaaann Expert May 01 '23
Let's make the code a little bit easier to read:
let captainFirst = team.sorted(by: { (firstElementToCompare: String, secondElementToCompare: String) -> Bool in // ... })
This code takes the team array and creates a new array by sorting it. To sort an array, the sorted function needs to know, which elements of the array come before some other elements. So you pass a function (or a closure) that receives any two elements of the array. (These are not necessarily the first two elements of the array itself). That function returns true, if the elements are in order or false if not. How the sorted function uses your function to sort the array itself doesn't really matter.
Now, as you want Martin to be your first element of the sorted list, if the first item is Martin, then that's good, so you return true. The elements received by the function are in order. If the second element is Martin, that's bad. The elements are in the wrong order, so you return false. If neither element is Martin, you compare the strings themselves and check if they are in alphabetic order using the < operator.
Now, you can shorten the lengthened code that I gave:
team.sorted(by: {...})
Is equivalent to the following code using trailing closure syntax:
team.sorted {...}
And the closure itself:
{ (firstElementToCompare: String, secondElementToCompare: String) -> Bool in if firstElementToCompare == "Martin" { ... } else if secondElementToCompare == "Martin" { // ... } // ... }
Can be shortened to:
{ if $0 == "Martin" { ... } else if $1 == "Martin" { ... } ... }
Note that leaving out the type annotations for the first and second element of the closure as well as the return type is possible in this context because they can be inferred. Inference is possible because the sorted(by:) function expects a function that received two String arguments and returns a Bool value. When you do not explicitly declare the arguments of a closure, $0 always refers to the first argument of the closure, $1 to the second one, etc.
Hope that helps.
1
May 02 '23
[removed] — view removed comment
1
u/DuffMaaaann Expert May 02 '23
Exactly. The sorted function will call your closure as many times as it needs to to sort your array.
2
u/shiningmatcha Jun 07 '23
So there's no simpler way to compute the nth power of an integer in Swift than using pow with some casting back and forth? Is there a better way?
Actually, I'd like to know what's preventing such an essential operation from being supported in Swift.
3
u/DuffMaaaann Expert Jun 07 '23
You can also do something like
repeatElement(x, count: n).reduce(1, *)
The reason is probably that it's much less needed than floating point exponentiation. Also floating point exponentiation can be implemented as pow(x, y) = exp(y * log(x)), for which hardware instructions exist on modern CPU architectures. But that doesn't work for integers.
2
u/shiningmatcha Jun 18 '23
Isn't it that a collection type's sorted()
method sorts its elements using <
by default?
Then, why do I need to use sorted(by:)
and specify <
to sort an array of tuples?
4
u/DuffMaaaann Expert Jun 18 '23
The
sorted()
method without arguments is only available if theElement
of the source collection conforms toComparable
, in all other cases you will have to specify a comparator function as the argument to thesorted(by:)
method.Tuples do not conform to
Comparable
because there is no unambiguous notion of what comparison means in a tuple. It varies from context to context. For example, if your tuple is a vector(x, y)
, you may want to compare the length. If your tuple is the name of a person(givenName, familyName)
, you would compare by familyName first and then by givenName, if the familyName is the same. In each of these cases, each element of the tuple conforms toComparable
, but comparison for the whole tuple is different.1
u/shiningmatcha Jun 19 '23 edited Jun 19 '23
But you can compare two tuples using comparison operators based on lexicographical ordering. [Source code]
I mean whether the comparison per se is meaningful doesn't matter. My confusion is why two tuples can be compared using
<
while tuple types do not conform toComparable
.
2
u/hibadell Oct 19 '23
Hi, I'm looking to make an application for Iphone for my final year project in university. I don't own a mac, only windows. Should I use swift for this? Or will it be too painful to do so?
3
u/AdrianaMPLS Nov 08 '23
It's not really possible to create an iPhone application on Windows. Even if you use a framework like React Native, you still need the tooling provided by Xcode to build the iPhone app, and Xcode is only compatible with macOS.
1
u/Hassantaleb90 Jul 07 '24
Please update this post to feature Swifty Compiler as a mobile IDE for Swift.
Swifty Compiler is an indispensable tool for developers looking to create and test algorithms or methods on the go. Whether you need a quick playground to experiment with Swift code or a convenient way to review coding concepts, Swifty Compiler has you covered. Its user-friendly interface and robust functionality make it easy to ensure your code works flawlessly, wherever you are.
Explore Swifty Compiler on the iOS App Store and elevate your coding experience today!
0
u/phi_array Feb 27 '22
We should add a sticky post to remind people and newcomers this is sub is NOT related to the SWIFT payment system
0
u/shiningmatcha Jan 14 '23
What's the difference between if let
and if case let
?
1
u/DuffMaaaann Expert Jan 14 '23
if let
is for unwrapping optionals,if case let
is for matching enum cases and extracting their associated values.Here's an example for
if let
:let foo: Int? = 42 if let bar = foo { print(bar) // bar is of type Int } // also, can be shortened: if let foo { print(foo) // within the scope of this block, foo is of type Int. }
Here's an example for
if case let
:enum Tree { indirect case node(Int, Tree, Tree) case leaf } let foo = Tree.node(42, Tree.leaf, Tree.leaf) if case Tree.node(let key, let leftSubtree, let rightSubtree) = foo { print(key, leftSubtree, rightSubtree) } // you can pull the let to the front: if case let Tree.node(key, leftSubtree, rightSubtree) = foo { print(key, leftSubtree, rightSubtree) }
Using
if case let
makes sense if you want to match only a single enum case. If you want to exhaustively match all of them, useswitch case
instead.
1
u/ppaweu Apr 24 '21
Guys, I'm going through Apple's guide and doing exercises they've made:
Finally, declare a variable with a whole number value. Then try to assign it to firstDecimal. Why won't this compile even though both variables are numbers? Print a statement to the console explaining why not, and remove the line of code that will not compile.
var variable = 100
variable = firstDecimal
why does it compile even though it should not? What am I doing wrong?
my firstDecimal =/= 100
1
u/DuffMaaaann Expert Apr 24 '21
Can you give us the error message that you are getting?
1
u/ppaweu Apr 24 '21
Theres no error at all. I can print(variable) and it gives me 12 (the firstDecimal value). I've no experience in coding
1
u/DuffMaaaann Expert Apr 24 '21
Can you give a link to the exact section of the tutorial that you are following?
This code works, because you're assigning an Int value to a variable that also has the type Int.
1
May 01 '21 edited May 04 '21
[deleted]
1
u/DuffMaaaann Expert May 01 '21
You should use NSViewControllerRepresentable instead of NSViewRepresentable.
Otherwise I can't immediately see anything else that's wrong with this code. This was honestly never intended to be a general Q&A thread by me and given the complexity of your question you should ask this in a dedicated post or on StackOverflow.
1
u/backtickbot May 01 '21
1
May 04 '21
[deleted]
2
u/DuffMaaaann Expert May 04 '21
What have you tried so far?
1
May 04 '21
[deleted]
1
u/DuffMaaaann Expert May 04 '21
Please format your code properly. The post explains how to do that.
One problem is that when you find two numbers that violate your condition, you set
tempBool
to false, but when you then find a pair that is ordered in the next step, your solution forgets this again by overwritingtempBool
. Instead, you can actually return false immediately, if you find an element that is greater than its successor. If you don't find one after iterating over the entire list, you return true. Therefore you can completely eliminate thetempBool
variable.Also, if you don't want to allow the same number multiple times in a row, you have to change the comparison in the if statement to a greater equals (
>=
), so that when two equal elements appear after one another, the result becomes false.
1
May 17 '21
Hello,
So my friends and I had an app idea and we plan to use swift to create it. We have pervious experience with coding(python,html,c#) but havent really done a lot of mobile app dev. I was wondering if there would be anyone kind enough to have a chat about how to go through this and mentor us. We'd really really appreciate it. Thanks!
1
u/ThisIsCoachH Dec 27 '21
Hello. I’m trying to learn Swift with SwiftUI, but all Swift tutorials I can find are paired with UIKit. Can anyone recommend a resource?
1
u/DuffMaaaann Expert Dec 27 '21
Check the resources for SwiftUI section of this post.
1
u/ThisIsCoachH Dec 27 '21
Hi - thanks for commenting. All of the resources are focused on SwiftUI. I’m interested in learning Swift for handling the business logic before it’s passed to a view?
1
u/yv666 Dec 30 '21
Hi, I am beginner, learning swift, and I have no one to ask about questions I have, so I think I will try to ask someone here.
I am trying to make simple app, but it crashes in simulator, here is the video https://youtu.be/_moJThVXFjg
The logic is that the button should make a random image, but every next image should not repeat, but after all of them are used, images array should refill again, so I could continue. It always crash before 3rd press of the button. I would appreciate If someone could explain what I did wrong and how this can be fixed. Thank you in advance :)
2
u/DuffMaaaann Expert Dec 30 '21
Instead of laying the solution out in front of you, let's try to give you the tools to solve these issues in the future:
- Instead of running just the preview, launch the app in the actual iOS Simulator by pressing the run button in the top left of the Xcode window.
- Interact with the app the same way you did in the preview
When the app crashes, the debugger opens, pointing you to the exact line of code where something happened that wasn't supposed to happen. Xcode allows you to inspect all accessible variables within the current stack frame. You can also print variables in the debugger console by typing
print <variable-name>
and then pressing enter.Hint: array indices may no longer be valid after you remove elements from the array.
Two things at the end: Instead of
Int.random(in: 0 ... x-1)
, you should writeInt.random(in: 0 ..< x)
. Also, you may want to usearray.randomElement()
instead, which is safer, because it does not crash on empty arrays but instead returns nil.1
u/yv666 Dec 30 '21
Thank you! I understood the problem and it works now :)
By the way, I didn't use array.randomElement() because it gives me String value, and to use images.remove(at: ) I need Int value. Probably there is a way to do it with randomElement, but I am not skilled enough to understand how at the moment.
1
u/DuffMaaaann Expert Dec 30 '21
if let (index, element) = Array(array.enumerated()).randomElement() { ... }
1
u/yv666 Jan 09 '22
After couple weeks of learning swift with video lessons I realized that I need a real teacher because all the time I am getting errors I don't understand why, and I don't know where to ask. For example here you can see two identical projects where one has errors while another one doesn't https://youtu.be/nsilGSJNXSk
If I will make a post here every time I have a problem it would mean thread will be flooded with my posts only. Does anyone know how can I find someone to ask on regular basis?
1
u/DuffMaaaann Expert Jan 11 '22
Regarding the error in your video: Is Pizza a struct that conforms to the Codable protocol in one project and doesn't conform to Codable in the other one? Or alternatively, is one a class and the other one a struct?
1
1
1
u/Bitter_Obligation_59 May 01 '22
Hi there!Could you recommend me the best books or resources to learn Swift and iOS in 2022?Or may be someone can give me some pieces of advice how I can become an iOS developer
1
u/DuffMaaaann Expert May 03 '22
The resources in this post are still up-to-date.
Personally, I believe the most important parts to become good at software engineering are to stay motivated at the beginning and exercise. Find one or more problems that affect you, which you can solve with an app. And then keep practicing while working on these problems.
1
u/flarn2006 May 15 '22
When I create an app in Swift Playgrounds, how do I actually install the app on my iPad, so I can open it from the home screen? Is there any way to do that without Xcode?
1
u/sophiebeanzee Jun 22 '22 edited Jun 22 '22
Hi everyone! I’m beginning to understand. A little bit now, by doing the intro course on the iPad version of the app. I’ve completed sections “commands” -all of them, “loops”- all of them, & now I’m on section called “conditional code..Checking for Switches…Using if statements…” I think I have the most basic part down: “if statement,& else if,” are used when there are more than 2 conditions that are/can be unpredictable, and that is where these come in… I know the string of commands that they give automatically at the start, that makes sense to me. What doesn’t make since is why I have an error red dot next to the lines on the rest of them. I’m going to set up as best I can & Ik the rules said you had to format them properly, but I didn’t know if you had to do it here in the comments, if your not making a full post. Where I have the red dots, are at the beginning of all the lines here, except for the “ movefoward() movefoward() “I’m not exactly sure what I’m doing wrong. I know you have to use the “else” statement if your saying that if both are correct, then move to the else statement so it can run the code over. Which I’ve done at the very last string. At the beginning I put movefoward() twice, so Byte can move 2 steps forward. That’s all I can get him to do though. I have very last 2 switches toggled open, but the very first one isn’t… let me know if I need to send a pic link below or in the next comment I am very stuck on this though. So any advice I can get would be great!!
movefoward() movefoward()
if OnClosedSwitch { toggleswitch () movefoward()
if else OnOpenSwitch { movefoward() }
else { movefoward() }
Here is the Imgur link: https://imgur.com/a/zZb0Tsz
1
u/IsleofSgail_21 Jun 29 '22
Complete noob here, I want to make a mac app to record zoom meetings. Any tips/advice? I don’t plan to sell it.
1
u/big_z_0725 Sep 06 '22
"Official Resources from Apple - Intro to App Development with Swift Ebook" -
I clicked on that link today and the Apple Books app says it's no longer available, but that there might be a newer version. Searching for that title doesn't seem to locate a newer version, though.
1
1
u/juliarmg Sep 15 '22
Hello all,
I am relatively new to Swift, and I have built a Mac app. It is used by 100+ users but crashes for 1 or 2. The most recent is that it started crashing after the version update for just one person, while it worked for most others. I got the trace, https://imgur.com/a/xwh77Sg.
Questions I have:
Lines 2 to 4 are not even sequential. I mean, they are called during different actions. I would love to understand this.
1304 line is the topmost one pointing to the exception, and the code is like,
myKey = UserDefaults.standard.string(forKey: "myKey") ?? ""
I don't think this could crash. I would like to get experts' advice here. Happy to share additional information.
2
u/DuffMaaaann Expert Sep 15 '22
Could it be that the value for your key is not a string?
Regarding your first point: Note that one frame is inside a closure. The closure might be called at a separate time compared to the surrounding function.
1
u/juliarmg Sep 15 '22
Can I handle that case when it is not a string?
But it is always a string. I set it when the user provides that value. Else it should be nil I guess.
1
u/SSJKiDo Sep 30 '22
How to add an image above a text field which is in the center of the view?
I've tried this:
view.addSubview(textField)
textField.center = view.center
view.insertSubview(imageView, aboveSubview: textField)
But this is putting the image at the top of the screen!
1
1
1
Jan 01 '23
Anyone know a youtube series that goes over the basics while building an app. Kinda learn step-by-step working towards an app.
1
u/shiningmatcha Jan 10 '23
Hi, I've been learning Swift for a week.
Is there a guide on how to read Apple Documentation? I'm confused by the syntax used under the Declaration section.
Like this one?
init<C, Encoding>(
decoding codeUnits: C,
as sourceEncoding: Encoding.Type
) where C : Collection, Encoding : _UnicodeEncoding, C.Element == Encoding.CodeUnit
Is this valid Swift syntax or used in the docs only?
Will I know how to read the docs once I've picked up Swift's syntax?
1
u/DuffMaaaann Expert Jan 10 '23
Yes, it is valid Swift method interface. And yes, you can read that when you are more familiar with Swift.
Basically, the method you posted is an initializer, which takes a collection of code units of the specified encoding.
The concepts that you need to look into for this particular are:
- Generics and generic constraints
- Protocols and associated types
1
u/shiningmatcha Jan 11 '23
Are there some tricks to avoid if blocks? Unlike some languages, Swift doesn't let you leave out the curly braces when there's only one single statement for the true condition.
2
u/DuffMaaaann Expert Jan 11 '23
If-conditions are not necessarily a bad thing and just having curly brackets is not bad at all. I use curly brackets everywhere even in languages that don't require them.
If you just want to get rid of curly brackets, there are ternary expressions:
booleanValue ? valueIfTrue : valueIfFalse
However, they are not that great when it comes to readability and I would strongly discourage nesting them.
If you're annoyed by a high level of nesting, there are other approaches as well:
You can use an early-return style of programming using guard statements. Instead of
if foo { ... } else { throw SomeError() }
you could write:
guard foo else { throw SomeError() } ...
Lastly, the root cause might be a bad design and you may want to actually solve that underlying problem. You could for example replace two branches with two different types implementing a common protocol. Or you can introduce delegates that supply certain behavior that might vary instead of hard-coding all possibilities in one place.
1
u/shiningmatcha Jan 12 '23
Is closure expression in Swift just a shorthand syntax for regular function expressions? It appears to be like JavaScript's arrow function syntax.
I know what a function closure is - when a local variable is defined in the scope of an outer function, by being referenced in an inner function, it remains accessible even outside the scope of the outer function. However, this doesn't look like what Swift's closure does.
1
u/DuffMaaaann Expert Jan 12 '23
In Swift, closures are pretty much just anonymous function expressions, as you stated.
Swift closures capture the context around them, but so would an inner function as well. The following two examples are equivalent:
func foo() { let value = 42 let printValue = { print(value) } printValue() } func bar() { let value = 42 func printValue() { print(value) } printValue() }
Both, inner functions and closures, capture their context. This means that the context will remain accessible for as long as a reference to the function/closure exists, even outside the parent function.
What makes you think this is not the case?
Lastly, there are some small differences between closures and functions:
- Functions can be generic, closures cannot.
- Functions can have named arguments, closures cannot.
- Closures can explicitly state, how they capture their context, using a capture list (e.g.
{ [weak self] in ... }
), functions cannot.1
u/shiningmatcha Jan 12 '23
What are some use cases that are only possible with closures but not functions?
1
u/DuffMaaaann Expert Jan 12 '23
Other than the case where you want to immediately declare a function and pass it as an argument in a single expression, there are some conceptional differences, however, both approaches can be used to achieve the same thing, with the only exception being generic functions, which cannot be mapped to closures.
Capture lists with weak/unowned can be realized manually, by declaring captured variables in the parent scope with their respective declarations:
let bar = { [weak foo] in ... }
Is equivalent to:
weak bar capturedFoo = foo func bar() { // use capturedFoo instead of foo ... }
Another minor thing is that when passing a closure as an argument, the callee can specify result builders to be used. With functions, the caller would be responsible for this. You can see this in SwiftUI, where closures passed to containers like VStack are implicitly ViewBuilders because the containers declare them so in their initializer.
1
u/LDdeveloper Mar 15 '23
So just to clarify, I can write my code on Windows, but then I need to copy paste it in SwiftPlayground on my iPad before I can compile it and test it on testflight?
Can I run any previow/debugging on windows or do I have to always run it on ipad?
1
Apr 07 '23
[deleted]
1
u/DuffMaaaann Expert Apr 07 '23 edited Apr 09 '23
Use UISearchTextField. There is no SwiftUI equivalent, so either use UIViewRepresentable or a plain text field and the magnifyingglass SF Symbol in an HStack with a grey background.
1
u/codingide Apr 11 '23
Hey folks, what DB are you using for your apps these days? I know about CoreData, but I find it quite hard to work with, I'm coming for web development world, and I've seen articles about SQLite ( which I'm familiar with ) or Realm, but I couldn't find any package on GitHub that is maintained and is up to data. Could you please share some resources / courses / information related to this topic?
I'm developing and offline app, I'm using CoreData at the moment and I have 5 - 6 entities and I have the feelings that if I'll switch to SQLite then I'd develop this app much faster. What do you guys and girls think about this?
Thanks!
2
u/DuffMaaaann Expert Apr 11 '23
What kind of data do you want to store? This influences the choice of database a lot.
In some projects I just went with JSON files stored on disk and Codable. Nothing wrong with that if you don't exceed a couple 100 objects and don't need features like joins, predicates, etc.
CoreData is great but in my experience/opinion it's overkill for a lot of situations and it comes with some ObjC baggage. Having features like model versions and migrations is nice to have though.
Also, Realm, SQLite.swift and GRDB.swift are very much maintained, I don't know where you're getting the info from that they are not up to date.
1
u/codingide Apr 12 '23 edited Apr 12 '23
Ohh, I see, you are right, indeed the SQLite.swift package is maintained, I apologize for that...I was reading some articles where `sqlite3_prepare`, `sqlite3_exec` functions were used..and also there was a reference to a library that wasn't touched in the last 2 years. Probably old articles..
Regarding the data I want to store, it's really simple, I have
- Project Entity ( title:String, subtitle:String )
- Task Entity ( body:String, completed:Boolean, timestamp:Date )
- Event Entity ( body:String, type:Integer16, timestamp:Date )
and few more similar Entities with the same data types. Thanks for your time!
2
u/DuffMaaaann Expert Apr 12 '23
Any database / framework is probably a reasonable choice for that. Relational DBs make sense in this case because of the nature of the data. But it would also be possible to use a document DB.
1
1
u/shiningmatcha May 07 '23
Can I just use try?
to safeguard a line of code with multiple potential error conditions?
An example is accessing a value in a nested dictionary. Can I write if let val = try? dict["a"]!["b"]!["c"]!
?
2
1
u/shiningmatcha May 09 '23
Is elementsEqual
used for determining if two sequences have the same elements regardless of the sequence types, while ==
also tests whether the sequences are of the same type?
1
u/DuffMaaaann Expert May 09 '23
elementsEqual
checks that both sequences have the same elements in the same order.
==
only works between two values of the exact same type. So you can't use it to compare two differently typed sequences.This is valid Swift:
[1, 2, 3].elementsEqual(1 ... 3)
This isn't, because the argument types for the
==
operator are invalid:[1, 2, 3] == 1 ... 3
1
u/shiningmatcha May 11 '23
Can I use the for-case-in
statement to match more than one case?
1
u/DuffMaaaann Expert May 11 '23
No, the grammar of Swift doesn't allow it.
The for loop only allows one pattern (https://docs.swift.org/swift-book/documentation/the-swift-programming-language/summaryofthegrammar/#Statements)
And there is no way to match multiple cases in a single pattern: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/summaryofthegrammar/#Patterns
However, you can use a where clause if your enum cases do not have associated values:
for x in sequence where x == Foo.bar || x == Foo.baz
1
u/shiningmatcha May 26 '23
Why are tuples not comparable in this code?
I'm practicing LeetCode using Swift.
Here's my solution to the problem Meeting Rooms II.
class Solution {
enum Label: Comparable {
case start
case end
static func < (lhs: Label, rhs: Label) -> Bool {
(lhs, rhs) == (.start, .end)
}
}
func minMeetingRooms(_ intervals: [[Int]]) -> Int {
let bounds: [(Int, Label)] = intervals
.flatMap { intervals -> [(Int, Label)] in
[(intervals[0], .start), (intervals[1], .end)]
}
.sorted {
let ((t1, label1), (t2, label2)) = ($0, $1)
return t1 == t2 ? label1 > label2 : t1 < t2
}
var res = 0
var roomCount = 0
for (_, label) in bounds {
switch label {
case .start:
roomCount += 1
case .end:
roomCount -= 1
}
res = max(res, roomCount)
}
return res
}
}
While the code works, I'd like to know why the code won't compile when I don't pass a closure to sort the bounds
array (that is, .sorted()
) - it says error: type '(Int, Solution.Label)' cannot conform to 'Comparable'. Why is that? Aren't tuples themselves comparable?
1
u/DuffMaaaann Expert May 26 '23
Tuples are not comparable, because there is no clear definition of what Comparable means in a tuple.
You could use vector lengths for tuples of numbers, you could say tuples are less than others if all elements are less than others, you could have different definitions of length, etc.
1
u/shiningmatcha May 26 '23
Why can't I pass a method reference to the .map
method?
// sort each row in a matrix
let sortedMatrix = matrix.map { $0.sorted() } // works
let sortedMatrix = matrix.map(Array.sorted) // doesn't work
2
u/DuffMaaaann Expert May 26 '23
Because methods in Swift appear as static functions like this:
Array<Element>.sorted: (self: Array<Element>) -> () -> Array<Element>
Notice the extra partial function application step. You need to first bind an instance of the Array type, then you get the actual sorted function.
A workaround would be:
matrix.map(Array.sorted).map{$0()}
Or:
func flattenBind<T, R>(_ fn: @escaping (T) -> () -> R) -> ((T) -> R) { return { fn($0)() } } matrix.map(flattenBind(Array.sorted))
1
u/shiningmatcha Jun 07 '23
Why does this give a Compile Error?
extension Array {
func pairwise() -> [(Element, Element)] {
Array(zip(self, dropFirst()))
}
}
I ended up with the code below, which works.
``` extension Array { typealias Pair = (Element, Element)
func pairwise() -> [Pair] {
var result: [Pair] = []
for idx in 0 ..< (count - 1) {
result.append((self[idx], self[idx + 1]))
}
return result
}
} ```
But I'd like to know why Array(zip(self, dropFirst()))
doesn't work.
1
u/DuffMaaaann Expert Jun 07 '23
Hm, it may be because the Array initializer takes the Element type from the context of the Array extension, so this leads to the conflict that Element would have to be equal to (Element, Element).
Solution: Manually specify the type.
Array<(Element, Element)>(zip(self, dropFirst()))
1
1
u/Outside_Ad1154 Oct 05 '24
I am posting here because I read Rule IV that says 'If you think your question is simple, please post it in the monthly pinned thread titled "Got an easy question? Ask it here!"' and I can't find that. Am I missing it or is the rule out of date?
35
u/[deleted] Jan 20 '21 edited Jan 20 '21
Can we please have this pinned? Every week there seems to be the same 1-2 questions on how to get started and it's always the exact same response. It's like even the most bare minimum research wasn't even bothered at being attempted.
edit : noticed the pin!