1598387640
Almost every active website worldwide uses jQuery, you can check stats here , but using it without optimization might make the DOM very slow. The same goes for other javascript libraries, such as SizzleJS. To ensure the performance of your DOM, you have to follow some best practices for it.
In this article I am going to list down some of the most critical factors that you need to watch out. Even though this not a complete list; taking care of these will help you optimize those jQuery Selector.
** Let’s start!**
Whenever you apply any selector in jQuery or SizzleJS, the selector engine goes through the whole DOM to find the specified element.
For example, if you use the code below, it will go through the whole DOM twice in order to find “.myClass” selector.
$(".myClass").show();
$(".myClass").addClass("anotherClass");
But instead of that, if you make all the methods in a chained format like this. It will only try to find that class once.
$(".myClass").show().addClass("anotherClass");
Or if you want to use this element in other places; you can do so by doing it in this way.
#jquery
1657254050
In this tutorial, we'll summarise what the top 9+ CSS mistakes are and how to avoid them.
It’s easy to get tripped up with CSS. Here are some common CSS mistakes we all make.
Web browsers are our fickle friends. Their inconsistencies can make any developer want to tear their hair out. But at the end of the day, they’re what will present your website, so you better do what you have to do to please them.
One of the sillier things browsers do is provide default styling for HTML elements. I suppose you can’t really blame them: what if a “webmaster” chose not to style their page? There has to be a fallback mechanism for people who choose not to use CSS.
In any case, there’s rarely a case of two browsers providing identical default styling, so the only real way to make sure your styles are effective is to use a CSS reset. What a CSS reset entails is resetting (or, rather, setting) all the styles of all the HTML elements to a predictable baseline value. The beauty of this is that once you include a CSS reset effectively, you can style all the elements on your page as if they were all the same to start with.
It’s a blank slate, really. There are many CSS reset codebases on the web that you can incorporate into your work. I personally use a modified version of the popular Eric Meyer reset and Six Revisions uses a modified version of YUI Reset CSS.
You can also build your own reset if you think it would work better. What many of us do is utilizing a simple universal selector margin/padding reset.
* { margin:0; padding:0; }
Though this works, it’s not a full reset.
You also need to reset, for example, borders, underlines, and colors of elements like list items, links, and tables so that you don’t run into unexpected inconsistencies between web browsers. Learn more about resetting your styles via this guide: Resetting Your Styles with CSS Reset.
Being overly specific when selecting elements to style is not good practice. The following selector is a perfect example of what I’m talking about:
ul#navigation li a { ... }
Typically the structure of a primary navigation list is a <ul>
(usually with an ID like #nav
or #navigation
) then a few list items (<li>
) inside of it, each with its own <a>
tag inside it that links to other pages.
This HTML structure is perfectly correct, but the CSS selector is really what I’m worried about. First things first: There’s no reason for the ul
before #navigation
as an ID is already the most specific selector. Also, you don’t have to put li
in the selector syntax because all the a
elements inside the navigation are inside list items, so there’s no reason for that bit of specificity.
Thus, you can condense that selector as:
#navigation a { ... }
This is an overly simplistic example because you might have nested list items that you want to style differently (i.e. #navigation li a
is different from #navigation li ul li a
); but if you don’t, then there’s no need for the excessive specificity.
I also want to talk about the need for an ID in this situation. Let’s assume for a minute that this navigation list is inside a header div (#header
). Let us also assume that you will have no other unordered list in the header besides the navigation list.
If that is the case, we can even remove the ID from the unordered list in our HTML markup, and then we can select it in CSS as such:
#header ul a { ... }
Here’s what I want you to take away from this example: Always write your CSS selectors with the very minimum level of specificity necessary for it to work. Including all that extra fluff may make it look more safe and precise, but when it comes to CSS selectors, there are only two levels of specificity: specific, and not specific enough.
Take a look at the following property list:
#selector { margin-top: 50px; margin-right: 0; margin-bottom: 50px; margin-left 0; }
What is wrong with this picture? I hope that alarm bells are ringing in your head as you notice how much we’re repeating ourselves. Fortunately, there is a solution, and it’s using CSS shorthand properties.
The following has the same effect as the above style declaration, but we’ve reduced our code by three lines.
#selector { margin: 50px 0; }
Check out this list of properties that deals with font styles:
font-family: Helvetica; font-size: 14px; font-weight: bold; line-height: 1.5;
We can condense all that into one line:
font: bold 14px/1.5 Helvetica;
We can also do this for background
properties. The following:
background-image: url(background.png); background-repeat: repeat-y; background-position: center top;
Can be written in shorthand CSS as such:
background: url(background.png) repeat-y center top;
Say you want to add a 20px margin to the bottom of an element. You might use something like this:
#selector { margin: 20px 0px 20px 0px; }
Don’t. This is excessive.
There’s no need to include the px
after 0
. While this may seem like I’m nitpicking and that it may not seem like much, when you’re working with a huge file, removing all those superfluous px
can reduce the size of your file (which is never a bad thing).
Declaring red
for color values is the lazy man’s #FF0000
. By saying:
color: red;
You’re essentially saying that the browser should display what it thinks red is. If you’ve learned anything from making stuff function correctly in all browsers — and the hours of frustration you’ve accumulated because of a stupid list-bullet misalignment that can only be seen in IE7 — it’s that you should never let the browser decide how to display your web pages.
Instead, you should go to the effort to find the actual hex value for the color you’re trying to use. That way, you can make sure it’s the same color displayed across all browsers. You can use a color cheatsheet that provides a preview and the hex value of a color.
This may seem trivial, but when it comes to CSS, it’s the tiny things that often lead to the big gotchas.
My process for writing styles is to start with all the typography, and then work on the structure, and finally on styling all the colors and backgrounds. That’s what works for me. Since I don’t focus on just one element at a time, I commonly find myself accidentally typing out a redundant style declaration.
I always do a final check after I’m done so that I can make sure that I haven’t repeated any selectors; and if I have, I’ll merge them. This sort of mistake is fine to make while you’re developing, but just try to make sure they don’t make it into production.
Similar to the one above, I often find myself having to apply the same properties to multiple selectors. This could be styling an <h5>
in the header to look exactly like the <h6>
in the footer, making the <pre>
‘s and <blockquote>
‘s the same size, or any number of things in between. In the final review of my CSS, I will look to make sure that I haven’t repeated too many properties.
For example, if I see two selectors doing the same thing, such as this:
#selector-1 { font-style: italic; color: #e7e7e7; margin: 5px; padding: 20px } .selector-2 { font-style: italic; color: #e7e7e7; margin: 5px; padding: 20px }
I will combine them, with the selectors separated by a comma (,
):
#selector-1, .selector-2 { font-style: italic; color: #e7e7e7; margin: 5px; padding: 20px }
I hope you’re seeing the trend here: Try to be as terse and as efficient as possible. It pays dividends in maintenance time and page-load speed.
In a perfect world, every computer would always have every font you would ever want to use installed. Unfortunately, we don’t live in a perfect world. @font-face aside, web designers are pretty much limited to the few so called web-safe fonts (e.g.
Arial, Georgia, serif, etc.). There is a plus side, though. You can still use fonts like Helvetica that aren’t necessarily installed on every computer.
The secret lies in font stacks. Font stacks are a way for developers to provide fallback fonts for the browser to display if the user doesn’t have the preferred font installed. For example:
#selector { font-family: Helvetica; }
Can be expanded with fallback fonts as such:
#selector { font-family: Helvetica, Arial, sans-serif; }
Now, if the user doesn’t have Helvetica, they can see your site in Arial, and if that doesn’t work, it’ll just default to any sans-serif font installed.
By defining fallback fonts, you gain more control as to how your web pages are rendered.
When it comes to trying to reduce your CSS file sizes for performance, every space counts. When you’re developing, it’s OK to format your code in the way that you’re comfortable with. However, there is absolutely no reason not to take out excess characters (a process known as minification) when you actually push your project onto the web where the size of your files really counts.
Too many developers simply don’t minify their files before launching their websites, and I think that’s a huge mistake. Although it may not feel like it makes much of a difference, when you have huge CSS files
When you’re writing CSS, do yourself a favor and organize your code. Through comments, you can insure that the next time you come to make a change to a file you’ll still be able to navigate it.
I personally like to organize my styles by how the HTML that I’m styling is structured. This means that I have comments that distinguish the header, body, sidebar, and footer. A common CSS-authoring mistake I see is people just writing up their styles as soon as they think of them.
The next time you try to change something and can’t find the style declaration, you’ll be silently cursing yourself for not organizing your CSS well enough.
This one’s subjective, so bear with me while I give you my perspective. I am of the belief, as are others, that it is better to split stylesheets into a few different ones for big sites for easier maintenance and for better modularity. Maybe I’ll have one for a CSS reset, one for IE-specific fixes, and so on.
By organizing CSS into disparate stylesheets, I’ll know immediately where to find a style I want to change. You can do this by importing all the stylesheets into a stylesheet like so:
@import url("reset.css"); @import url("ie.css"); @import url("typography.css"); @import url("layout.css");
Let me stress, however, that this is what works for me and many other developers. You may prefer to squeeze them all in one file, and that’s okay; there’s nothing wrong with that.
But if you’re having a hard time maintaining a single file, try splitting your CSS up.
In order to style your site on pages that will be printed, all you have to do is utilize and include a print stylesheet. It’s as easy as:
<link rel="stylesheet" href="print.css" media="print" />
Using a stylesheet for print allows you to hide elements you don’t want printed (such as your navigation menu), reset the background color to white, provide alternative typography for paragraphs so that it’s better suited on a piece of paper, and so forth. The important thing is that you think about how your page will look when printed.
Too many people just don’t think about it, so their sites will simply print the same way you see them on the screen.
No matter how long you've been writing code, it's always a good time to revisit the basics. While working on a project the other day, I made 2 beginner mistakes with the CSS I was writing. I misunderstood both CSS specificity and how transform:scale affects the DOM!
Stack Overflow about transform:scale - https://stackoverflow.com/questions/32835144/css-transform-scale-does-not-change-dom-size
CSS Specificity - https://www.w3schools.com/css/css_specificity.asp
#css
1675107840
Swift Library for Font Icons
Please ★ this library.
Now, you don't have to download different libraries to include different font icons. This SwiftIcons library helps you use icons from any of the following font icons.
SwiftIcons supports different objects from the object library.
CocoaPods is a dependency manager for Cocoa projects.
Make sure you have the latest version of CocoaPods by running:
$ gem install cocoapods
# (or if the above fails)
$ sudo gem install cocoapods
Update your local specs repo by running:
$ pod repo update
Add the following lines to your Podfile
:
target 'YourProject' do
use_frameworks!
pod 'SwiftIcons', '~> 3.0'
end
Then run the following command
$ pod install
You can start using the library by importing it wherever you want
import SwiftIcons
Carthage is a decentralized dependency manager for Cocoa projects.
Install the latest version of Carthage.
Add this line to your Cartfile
:
github "ranesr/SwiftIcons" ~> 3.0
or for master
,
github "ranesr/SwiftIcons" "master"
Then run carthage update --platform ios
and add the built framework to your project by following these instructions from Carthage.
Copy all the files from Source
folder. Link to files.
Check to import all ttf files in project, "Project" > "Target" > "Copy Bundle Resources"
You can check library reference documentation here.
There are different font types for each of the font icons
Font Icons | Version | Font Types | Icons |
---|---|---|---|
Dripicons | 2.0 | dripicons | dripicons |
Emoji | emoji | emoji | |
FontAwesome | 5.1.0 | fontAwesome | fontAwesome |
Icofont | 1.0.0 Beta | icofont | icofont |
Ionicons | 2.0.1 | ionicons | ionicons |
Linearicons | 1.0.0 | linearIcons | linearIcons |
Map-icons | 3.0.2 | mapicons | mapicons |
Material icons | 2.2.0 | googleMaterialDesign | googleMaterialDesign |
Open iconic | 1.1.1 | openIconic | openIconic |
State face icons | state | state | |
Weather icons | 2.0.10 | weather | weather |
TypIcons | 2.0.7 | TypIcons | Typicons |
When setting an icon to any object, you have to mention which font type it is and then select which icon you want to set from that particular font icon.
import SwiftIcons
UIImage.init(icon: .emoji(.airplane), size: CGSize(width: 35, height: 35))
// Icon with colors
UIImage.init(icon: .emoji(.airplane), size: CGSize(width: 35, height: 35), textColor: .red)
UIImage.init(icon: .emoji(.airplane), size: CGSize(width: 35, height: 35), textColor: .white, backgroundColor: .red)
// Stacked icons with bigger background
UIImage.init(bgIcon: .fontAwesomeRegular(.circle), topIcon: .fontAwesomeRegular(.square))
// Stacked icons with smaller background
UIImage.init(bgIcon: .fontAwesomeSolid(.camera), topIcon: .fontAwesomeSolid(.ban), topTextColor: .red, bgLarge: false)
// Stacked icons with custom size
UIImage.init(bgIcon: .fontAwesomeSolid(.camera), topIcon: .fontAwesomeSolid(.ban), topTextColor: .red, bgLarge: false, size: CGSize(width: 50, height: 50))
import SwiftIcons
// Setting icon to image view
imageView.setIcon(icon: .weather(.rainMix))
// Icon with colors
imageView.setIcon(icon: .mapicons(.amusementPark), textColor: .white, backgroundColor: .blue, size: nil)
import SwiftIcons
// Setting icon to label
label.setIcon(icon: .ionicons(.paintbrush), iconSize: 70)
// Icon with colors
label.setIcon(icon: .googleMaterialDesign(.rowing), iconSize: 70, color: .white, bgColor: textColor)
// Icon with text around it
label.setIcon(prefixText: "Bus ", icon: .linearIcons(.bus), postfixText: " icon", size: 20)
// Icon with color & colored text around it
label.setIcon(prefixText: "Medal ", prefixTextColor: .red, icon: .ionicons(.ribbonA), iconColor: .red, postfixText: "", postfixTextColor: .red, size: nil, iconSize: 40)
// Icon with text with different fonts around it
label.setIcon(prefixText: "Font ", prefixTextFont: font1!, icon: .fontAwesomeSolid(.font), postfixText: " icon", postfixTextFont: font2!)
// Icon with text with different fonts & colors around it
label.setIcon(prefixText: "Bike ", prefixTextFont: font1!, prefixTextColor: .red, icon: .mapicons(.bicycling), iconColor: textColor, postfixText: " icon", postfixTextFont: font2!, postfixTextColor: .blue, iconSize: 30)
import SwiftIcons
// Setting icon to button
button.setIcon(icon: .linearIcons(.phone), forState: .normal)
// Icon with size and color
button.setIcon(icon: .openIconic(.clipboard), iconSize: 70, color: .blue, forState: .normal)
// Icon with text around it
button.setIcon(prefixText: "Please ", icon: .googleMaterialDesign(.print), postfixText: " print", forState: .normal)
// Icon with color & colored text around it
button.setIcon(prefixText: "Lock ", prefixTextColor: .red, icon: .googleMaterialDesign(.lock), iconColor: .yellow, postfixText: " icon", postfixTextColor: .blue, forState: .normal, textSize: 15, iconSize: 20)
// Icon with text with different fonts around it
button.setIcon(prefixText: "Happy ", prefixTextFont: font1!, icon: .ionicons(.happy), postfixText: " face", postfixTextFont: font2!, forState: .normal)
// Icon with text with different fonts & colors around it
button.setIcon(prefixText: "Pulse ", prefixTextFont: font1!, prefixTextColor: .darkGray, icon: .openIconic(.pulse), iconColor: .red, postfixText: " icon", postfixTextFont: font2!, postfixTextColor: .purple, forState: .normal, iconSize: 40)
// Icon with title below icon
button.setIcon(icon: .emoji(.ferrisWheel), title: "Ferris Wheel", color: .red, forState: .normal)
// Icon with title below icon with different color & custom font
button.setIcon(icon: .weather(.rainMix), iconColor: .yellow, title: "RAIN MIX", titleColor: .red, font: font!, backgroundColor: .clear, borderSize: 1, borderColor: .green, forState: .normal)
import SwiftIcons
// Setting icon at particular index
segmentedControl.setIcon(icon: .linearIcons(.thumbsUp), forSegmentAtIndex: 0)
segmentedControl.setIcon(icon: .linearIcons(.thumbsDown), forSegmentAtIndex: 1)
// Icons with sizes & colors
segmentedControl.setIcon(icon: .fontAwesomeSolid(.male), color: .red, iconSize: 50, forSegmentAtIndex: 0)
segmentedControl.setIcon(icon: .fontAwesomeSolid(.female), color: .purple, iconSize: 50, forSegmentAtIndex: 1)
import SwiftIcons
// Setting icon to tab bar item
tabBar.items?[0].setIcon(icon: .fontAwesomeSolid(.font), size: nil, textColor: .lightGray)
// Stacked icons for tab bar item
tabBar.items?[1].setIcon(bgIcon: .fontAwesomeRegular(.circle), bgTextColor: .lightGray, topIcon: .fontAwesomeSolid(.square), topTextColor: .lightGray, bgLarge: true, size: nil)
import SwiftIcons
// Change minimum & maximum value icons
slider.setMaximumValueIcon(icon: .emoji(.digitNine))
slider.setMinimumValueIcon(icon: .emoji(.digitZero))
// Change minimum & maximum value icons with colors
slider.setMaximumValueIcon(icon: .linearIcons(.pointerUp), customSize: nil, textColor: .red, backgroundColor: .clear)
slider.setMinimumValueIcon(icon: .linearIcons(.pointerDown), customSize: nil, textColor: .blue, backgroundColor: .clear)
import SwiftIcons
// Setting icon to bar button item
barButtonItem.setIcon(icon: .ionicons(.iosFootball), iconSize: 30)
// Icon with colors
barButtonItem.setIcon(icon: .ionicons(.iosFootball), iconSize: 30, color: textColor)
// Icon with custom cgRect
barButtonItem.setIcon(icon: .ionicons(.iosFootball), iconSize: 30, color: textColor, cgRect: CGRect(x: 0, y: 0, width: 30, height: 30), target: self, action: #selector(barButtonItem(sender:)))
// Icon with text around it
barButtonItem.setIcon(prefixText: "Please ", icon: .ionicons(.iosDownload), postfixText: " download", cgRect: CGRect(x: 0, y: 0, width: 30, height: 30), size: 23, target: self, action: #selector(barButtonItem(sender:)))
// Icon with color & colored text around it
barButtonItem.setIcon(prefixText: "Blue ", prefixTextColor: .red, icon: .ionicons(.iosFootball), iconColor: .blue, postfixText: " football", postfixTextColor: .green, cgRect: CGRect(x: 0, y: 0, width: 30, height: 30), size: 20, iconSize: 30, target: self, action: #selector(barButtonItem(sender:)))
// Icon with text with different fonts around it
barButtonItem.setIcon(prefixText: "Digit ", prefixTextFont: font1!, icon: .emoji(.digitOne), postfixText: " One", postfixTextFont: font2!, cgRect: CGRect(x: 0, y: 0, width: 30, height: 30), target: self, action: #selector(barButtonItem(sender:)))
// Icon with text with different fonts & colors around it
barButtonItem.setIcon(prefixText: "", prefixTextFont: font1!, prefixTextColor: .red, icon: .ionicons(.iosFootball), iconColor: .blue, postfixText: " football", postfixTextFont: font2!, postfixTextColor: .green, cgRect: CGRect(x: 0, y: 0, width: 30, height: 30), iconSize: 24, target: self, action: #selector(barButtonItem(sender:)))
import SwiftIcons
// Setting icon to the title
self.setTitleIcon(icon: .emoji(.animalHorse), iconSize: 30, color: .red)
import SwiftIcons
// Setting left view icon
textfield.setLeftViewIcon(icon: .fontAwesomeSolid(.search))
// Left view icon with colors & leftViewMode
textfield.setLeftViewIcon(icon: .state(.TX), leftViewMode: .always, textColor: .blue, backgroundColor: .clear, size: nil)
textfield.setLeftViewIcon(icon: .googleMaterialDesign(.plusOne), leftViewMode: .unlessEditing, textColor: .green, backgroundColor: .clear, size: nil)
// Setting right view icon
textfield.setRightViewIcon(icon: .openIconic(.questionMark))
// Right view icon with colors & rightViewMode
textfield.setRightViewIcon(icon: .weather(.rainMix), rightViewMode: .always, textColor: .red, backgroundColor: .clear, size: nil)
import SwiftIcons
// Setting icons
stepper.setDecrementIcon(icon: .ionicons(.iosPause), forState: .normal)
stepper.setIncrementIcon(icon: .ionicons(.iosPlay), forState: .normal)
Please check out the SwiftIcons App. In the demo project, if you click on any object, you will see the method description in the logs for the icon of that object.
If you are using SwiftIcons in your app and want to be listed here, simply create a new issue here.
I am always curious who is using my projects 😊
Author: Ranesr
Source Code: https://github.com/ranesr/SwiftIcons
License: MIT license
1662112200
Please ★ this library.
Now, you don't have to download different libraries to include different font icons. This SwiftIcons library helps you use icons from any of the following font icons.
SwiftIcons supports different objects from the object library.
CocoaPods is a dependency manager for Cocoa projects.
Make sure you have the latest version of CocoaPods by running:
$ gem install cocoapods
# (or if the above fails)
$ sudo gem install cocoapods
Update your local specs repo by running:
$ pod repo update
Add the following lines to your Podfile
:
target 'YourProject' do
use_frameworks!
pod 'SwiftIcons', '~> 3.0'
end
Then run the following command
$ pod install
You can start using the library by importing it wherever you want
import SwiftIcons
Carthage is a decentralized dependency manager for Cocoa projects.
Install the latest version of Carthage.
Add this line to your Cartfile
:
github "ranesr/SwiftIcons" ~> 3.0
or for master
,
github "ranesr/SwiftIcons" "master"
Then run carthage update --platform ios
and add the built framework to your project by following these instructions from Carthage.
Copy all the files from Source
folder. Link to files.
Check to import all ttf files in project, "Project" > "Target" > "Copy Bundle Resources"
You can check library reference documentation here.
There are different font types for each of the font icons
Font Icons | Version | Font Types | Icons |
---|---|---|---|
Dripicons | 2.0 | dripicons | dripicons |
Emoji | emoji | emoji | |
FontAwesome | 5.1.0 | fontAwesome | fontAwesome |
Icofont | 1.0.0 Beta | icofont | icofont |
Ionicons | 2.0.1 | ionicons | ionicons |
Linearicons | 1.0.0 | linearIcons | linearIcons |
Map-icons | 3.0.2 | mapicons | mapicons |
Material icons | 2.2.0 | googleMaterialDesign | googleMaterialDesign |
Open iconic | 1.1.1 | openIconic | openIconic |
State face icons | state | state | |
Weather icons | 2.0.10 | weather | weather |
TypIcons | 2.0.7 | TypIcons | Typicons |
When setting an icon to any object, you have to mention which font type it is and then select which icon you want to set from that particular font icon.
import SwiftIcons
UIImage.init(icon: .emoji(.airplane), size: CGSize(width: 35, height: 35))
// Icon with colors
UIImage.init(icon: .emoji(.airplane), size: CGSize(width: 35, height: 35), textColor: .red)
UIImage.init(icon: .emoji(.airplane), size: CGSize(width: 35, height: 35), textColor: .white, backgroundColor: .red)
// Stacked icons with bigger background
UIImage.init(bgIcon: .fontAwesomeRegular(.circle), topIcon: .fontAwesomeRegular(.square))
// Stacked icons with smaller background
UIImage.init(bgIcon: .fontAwesomeSolid(.camera), topIcon: .fontAwesomeSolid(.ban), topTextColor: .red, bgLarge: false)
// Stacked icons with custom size
UIImage.init(bgIcon: .fontAwesomeSolid(.camera), topIcon: .fontAwesomeSolid(.ban), topTextColor: .red, bgLarge: false, size: CGSize(width: 50, height: 50))
import SwiftIcons
// Setting icon to image view
imageView.setIcon(icon: .weather(.rainMix))
// Icon with colors
imageView.setIcon(icon: .mapicons(.amusementPark), textColor: .white, backgroundColor: .blue, size: nil)
import SwiftIcons
// Setting icon to label
label.setIcon(icon: .ionicons(.paintbrush), iconSize: 70)
// Icon with colors
label.setIcon(icon: .googleMaterialDesign(.rowing), iconSize: 70, color: .white, bgColor: textColor)
// Icon with text around it
label.setIcon(prefixText: "Bus ", icon: .linearIcons(.bus), postfixText: " icon", size: 20)
// Icon with color & colored text around it
label.setIcon(prefixText: "Medal ", prefixTextColor: .red, icon: .ionicons(.ribbonA), iconColor: .red, postfixText: "", postfixTextColor: .red, size: nil, iconSize: 40)
// Icon with text with different fonts around it
label.setIcon(prefixText: "Font ", prefixTextFont: font1!, icon: .fontAwesomeSolid(.font), postfixText: " icon", postfixTextFont: font2!)
// Icon with text with different fonts & colors around it
label.setIcon(prefixText: "Bike ", prefixTextFont: font1!, prefixTextColor: .red, icon: .mapicons(.bicycling), iconColor: textColor, postfixText: " icon", postfixTextFont: font2!, postfixTextColor: .blue, iconSize: 30)
import SwiftIcons
// Setting icon to button
button.setIcon(icon: .linearIcons(.phone), forState: .normal)
// Icon with size and color
button.setIcon(icon: .openIconic(.clipboard), iconSize: 70, color: .blue, forState: .normal)
// Icon with text around it
button.setIcon(prefixText: "Please ", icon: .googleMaterialDesign(.print), postfixText: " print", forState: .normal)
// Icon with color & colored text around it
button.setIcon(prefixText: "Lock ", prefixTextColor: .red, icon: .googleMaterialDesign(.lock), iconColor: .yellow, postfixText: " icon", postfixTextColor: .blue, forState: .normal, textSize: 15, iconSize: 20)
// Icon with text with different fonts around it
button.setIcon(prefixText: "Happy ", prefixTextFont: font1!, icon: .ionicons(.happy), postfixText: " face", postfixTextFont: font2!, forState: .normal)
// Icon with text with different fonts & colors around it
button.setIcon(prefixText: "Pulse ", prefixTextFont: font1!, prefixTextColor: .darkGray, icon: .openIconic(.pulse), iconColor: .red, postfixText: " icon", postfixTextFont: font2!, postfixTextColor: .purple, forState: .normal, iconSize: 40)
// Icon with title below icon
button.setIcon(icon: .emoji(.ferrisWheel), title: "Ferris Wheel", color: .red, forState: .normal)
// Icon with title below icon with different color & custom font
button.setIcon(icon: .weather(.rainMix), iconColor: .yellow, title: "RAIN MIX", titleColor: .red, font: font!, backgroundColor: .clear, borderSize: 1, borderColor: .green, forState: .normal)
import SwiftIcons
// Setting icon at particular index
segmentedControl.setIcon(icon: .linearIcons(.thumbsUp), forSegmentAtIndex: 0)
segmentedControl.setIcon(icon: .linearIcons(.thumbsDown), forSegmentAtIndex: 1)
// Icons with sizes & colors
segmentedControl.setIcon(icon: .fontAwesomeSolid(.male), color: .red, iconSize: 50, forSegmentAtIndex: 0)
segmentedControl.setIcon(icon: .fontAwesomeSolid(.female), color: .purple, iconSize: 50, forSegmentAtIndex: 1)
import SwiftIcons
// Setting icon to tab bar item
tabBar.items?[0].setIcon(icon: .fontAwesomeSolid(.font), size: nil, textColor: .lightGray)
// Stacked icons for tab bar item
tabBar.items?[1].setIcon(bgIcon: .fontAwesomeRegular(.circle), bgTextColor: .lightGray, topIcon: .fontAwesomeSolid(.square), topTextColor: .lightGray, bgLarge: true, size: nil)
import SwiftIcons
// Change minimum & maximum value icons
slider.setMaximumValueIcon(icon: .emoji(.digitNine))
slider.setMinimumValueIcon(icon: .emoji(.digitZero))
// Change minimum & maximum value icons with colors
slider.setMaximumValueIcon(icon: .linearIcons(.pointerUp), customSize: nil, textColor: .red, backgroundColor: .clear)
slider.setMinimumValueIcon(icon: .linearIcons(.pointerDown), customSize: nil, textColor: .blue, backgroundColor: .clear)
import SwiftIcons
// Setting icon to bar button item
barButtonItem.setIcon(icon: .ionicons(.iosFootball), iconSize: 30)
// Icon with colors
barButtonItem.setIcon(icon: .ionicons(.iosFootball), iconSize: 30, color: textColor)
// Icon with custom cgRect
barButtonItem.setIcon(icon: .ionicons(.iosFootball), iconSize: 30, color: textColor, cgRect: CGRect(x: 0, y: 0, width: 30, height: 30), target: self, action: #selector(barButtonItem(sender:)))
// Icon with text around it
barButtonItem.setIcon(prefixText: "Please ", icon: .ionicons(.iosDownload), postfixText: " download", cgRect: CGRect(x: 0, y: 0, width: 30, height: 30), size: 23, target: self, action: #selector(barButtonItem(sender:)))
// Icon with color & colored text around it
barButtonItem.setIcon(prefixText: "Blue ", prefixTextColor: .red, icon: .ionicons(.iosFootball), iconColor: .blue, postfixText: " football", postfixTextColor: .green, cgRect: CGRect(x: 0, y: 0, width: 30, height: 30), size: 20, iconSize: 30, target: self, action: #selector(barButtonItem(sender:)))
// Icon with text with different fonts around it
barButtonItem.setIcon(prefixText: "Digit ", prefixTextFont: font1!, icon: .emoji(.digitOne), postfixText: " One", postfixTextFont: font2!, cgRect: CGRect(x: 0, y: 0, width: 30, height: 30), target: self, action: #selector(barButtonItem(sender:)))
// Icon with text with different fonts & colors around it
barButtonItem.setIcon(prefixText: "", prefixTextFont: font1!, prefixTextColor: .red, icon: .ionicons(.iosFootball), iconColor: .blue, postfixText: " football", postfixTextFont: font2!, postfixTextColor: .green, cgRect: CGRect(x: 0, y: 0, width: 30, height: 30), iconSize: 24, target: self, action: #selector(barButtonItem(sender:)))
import SwiftIcons
// Setting icon to the title
self.setTitleIcon(icon: .emoji(.animalHorse), iconSize: 30, color: .red)
import SwiftIcons
// Setting left view icon
textfield.setLeftViewIcon(icon: .fontAwesomeSolid(.search))
// Left view icon with colors & leftViewMode
textfield.setLeftViewIcon(icon: .state(.TX), leftViewMode: .always, textColor: .blue, backgroundColor: .clear, size: nil)
textfield.setLeftViewIcon(icon: .googleMaterialDesign(.plusOne), leftViewMode: .unlessEditing, textColor: .green, backgroundColor: .clear, size: nil)
// Setting right view icon
textfield.setRightViewIcon(icon: .openIconic(.questionMark))
// Right view icon with colors & rightViewMode
textfield.setRightViewIcon(icon: .weather(.rainMix), rightViewMode: .always, textColor: .red, backgroundColor: .clear, size: nil)
import SwiftIcons
// Setting icons
stepper.setDecrementIcon(icon: .ionicons(.iosPause), forState: .normal)
stepper.setIncrementIcon(icon: .ionicons(.iosPlay), forState: .normal)
Please check out the SwiftIcons App. In the demo project, if you click on any object, you will see the method description in the logs for the icon of that object.
If you are using SwiftIcons in your app and want to be listed here, simply create a new issue here.
I am always curious who is using my projects 😊
Saurabh Rane
Special thanks to Patrik Vaberer and his initial work on Font-Awesome-Swift library
Author: ranesr
Source code: https://github.com/ranesr/SwiftIcons
License: MIT license
#swift
1622879640
The goal isn't to just write CSS that works. Code CSS that is efficient and easy to maintain
Here are some common mistakes that most web developers make, and how identifying and avoiding them can help you write better and more efficient CSS!
1. Using Color Names Instead of Hexadecimal
When you say color: blue; you're essentially telling the computer to display whatever shade of color it thinks blue is. By doing this, you’re giving the browser control over how your web page should be displayed, and as a developer, this is something you should never do. By vaguely naming the color as blue, it can easily differ from the shade of blue that you had in mind, and worse it can also vary from browser to browser.
Using hexadecimal values eg. color: #4169E1; hence becomes something that all developers should adopt. It ensures specificity, is supported by all browsers, and gives back to you the control to decide exactly how you want your web page to be displayed.
Note: An efficient way for finding and using hexadecimal values is by first putting in the name of the closest color to the desired shade, and then inspecting the element to find the hex value using the color dropper.
2. Hard Coding px Instead of Relative Units
While it sometimes becomes imperative to use absolute px values, you should always use relative measurements such as em, % (percent), rem (root-Em), and others whenever possible.
This ensures that the website scales proportionally according to the user’s choice of zoom level and screen/browser size.
So, instead of declaring the sizes in absolutes,
p {
font-size: 16px;
line-height: 20px;
margin-bottom: 8px;
}
do this instead:
p {
font-size: 1rem;
line-height: 1.25em;
margin-bottom: 0.5rem;
}
3. Not Using Font Fallbacks
No matter how beautiful a particular font makes your page look, or how much it catches the eye, you always have to consider that not all font types are supported by all computers. If you’re using a font that some browsers do not support, it means that your web page might not be as beautiful and eye-catching as you’re designing it to be for all users.
So, after you use your favorite font, say Helvetica, always make sure to list fallback fonts that the browser can use in case it isn't supported.
Instead of writing this,
#selector {
font-family: Helvetica;
}
expand the code by font fallbacks such as:
#selector {
font-family: Helvetica, Arial, sans-serif;
}
Now, even if the browser doesn't support Helvetica, it would fall back to the second most preferred option Arial before going to the browser default.
4. Not Using CSS Shorthands
Take a look at the CSS below:
font-family: Helvetica;
font-size: 14px;
font-weight: bold;
line-height: 1.5;
This can easily be condensed into a single line using the CSS shorthand for font:
font: bold 14px/1.5 Helvetica;
Similarly, this list of properties for a background image:
background-image: url(background.png);
background-repeat: repeat-y;
background-position: center top;
can be written as:
background: url(background.png) repeat-y center top;
Why are we doing this? The reason is simple. It not only reduces your CSS file size but also makes the stylesheet easier to read and more organized.
Here’s a list of CSS shorthands to help you write cleaner code. It’s all about ingraining it into your coding habits, but once you do it, there's no going back!
5. Over Qualifying Selectors
Just like every other thing in excess, too much specificity is a bad thing. And more often than not, it is not even necessary. Take a look at the CSS below:
header #nav ul li a {...}
First of all, the header specification is absolutely unnecessary since an ID, having the highest specificity, has already been used (IDs are unique and only associated with one element). Moreover, an unordered list (ul) always has list items (li) within. So having to mention that becomes pointless. The same selector can now be written as:
#nav ul a {...}
With CSS there are only two levels of specificity — specific and not specific enough. Including all those extra elements might make it look ‘safe’ but are actually unnecessary and are only adding to the length of your stylesheet.
As a general rule, your selectors should be as short as possible. Be just as specific as is necessary for it to work.
6. Using ID’s instead of Classes
The most cogent argument against using ID’s is that it has a much higher specificity than classes, which is why it becomes hard to overwrite and extend your styles. A class on its own can’t overwrite styles belonging to an ID. To “beat” the ID, you would need either more IDs or to use !important, which can begin specificity wars in your stylesheets.
Class selectors can also be used for several HTML elements on the same page, unlike IDs which are unique to each element. Being able to reuse styles is one of the advantages of CSS.
To maintain a consistent convention, use only the class attributes to define styles and IDs while integrating interactivity with Javascript instead.
7. Not Using CSS Reset
If you have ever displayed an HTML page with no CSS styling, you know that the web browser itself “styles” the page using some default values as a fallback. The text has a particular font size and style, the margin and padding are set to certain values.
While this is a good thing for someone who does not use CSS, it is important to first reset these values when you put your own styles into the page. These values vary from browser to browser, hence a CSS Reset is the only way to ensure that all your styles are uniform and effective.
This entails resetting all the styles of all the HTML elements to a predictable baseline value. Once you do this, you can style all the elements on your page as if they were the same to start with. A blank slate.
An easier but incomplete way to do this is by resetting the margin and padding using a universal selector:
* {margin:0; padding:0;}
For a complete reset, however, you can use the Eric Meyer reset (modifying it as per your choice), to reset borders, underlines, and colors of elements like list items, links, and tables so that you don’t run into unexpected inconsistencies between web browsers.
8. Repetitive Code (Redundant Selectors and Properties)
In general, repeating yourself while coding is not considered a good practice. CSS is no different. Take a look at the code below:
#selector-1 {
font-style: italic;
color: #e7e7e7;
margin: 5px;
padding: 20px
}
.selector-2 {
font-style: italic;
color: #e7e7e7;
margin: 5px;
padding: 20px
}
A better way to write this is by combining them, with the selectors separated by a comma (,):
#selector-1, .selector-2 {
font-style: italic;
color: #e7e7e7;
margin: 5px;
padding: 20px
}
This is not just more efficient, but also reduces maintenance time and page-load speed.
9. Not Separating Design from Layout
The job of CSS is to provide styling, and the job of HTML is to provide structure. Generally, HTML should be written in a way that captures the information hierarchy of the page, ignoring any design concerns. Afterward, CSS can be added to make things ‘look nice.’
However, while HTML provides structure, it cannot always position elements on the exact spot of a page you want it to appear, which is where we use CSS to scaffold the layout of the page. Once an element is put into the right place on the page, it’s easy to style it without worrying about the display and position. This is why Layout CSS should be separated from Design CSS.
Instead of putting the layout as well as design properties together,
.article {
display: inline-block;
width: 50%;
margin-bottom: 1em;
font-family: sans-serif;
border-radius: 1rem;
box-shadow: 12px 12px 2px 1px rgba(0, 0, 0, .2);
}
.sidebar {
width: 25%;
margin-left: 5px;
}
<div class="article"></div>
<div class="article sidebar"></div>
Separate the design and layout of elements:
/* layout */
.article, .sidebar {
display: inline-block;
}
.article {
width: 50%;
margin-bottom: 1em;
}
.sidebar {
width: 25%;
margin-left: 5px;
}
/* display */
.card {
font-family: sans-serif;
border-radius: 1rem;
box-shadow: 12px 12px 2px 1px rgba(0, 0, 0, .2);
}
<div class="article card"></div>
<div class="sidebar card"></div>
This ensures separation of concerns, which is a common software engineering principle that helps keep our code maintainable and easy to understand.
10. Writing Unorganized CSS
Instead of writing your styles just as you think of them, do yourself a favor and organize your code neatly. This will ensure that next time you come to make a change to your file, you’re still able to navigate it.
#css #programming #developer
1661583489
The Official raywenderlich.com Swift Style Guide.
This style guide is different from others you may see, because the focus is centered on readability for print and the web. We created this style guide to keep the code in our books, tutorials, and starter kits nice and consistent — even though we have many different authors working on the books.
Our overarching goals are clarity, consistency and brevity, in that order.
Strive to make your code compile without warnings. This rule informs many style decisions such as using #selector
types instead of string literals.
When writing for raywenderlich.com, you are strongly encouraged — and some teams may require — to use our SwiftLint configuration. See the SwiftLint Policy for more information.
Descriptive and consistent naming makes software easier to read and understand. Use the Swift naming conventions described in the API Design Guidelines. Some key takeaways include:
camelCase
(not snake_case
)UpperCamelCase
for types and protocols, lowerCamelCase
for everything elsemake
When referring to methods in prose, being unambiguous is critical. To refer to a method name, use the simplest form possible.
addTarget
.addTarget(_:action:)
.addTarget(_: Any?, action: Selector?)
.For the above example using UIGestureRecognizer
, 1 is unambiguous and preferred.
Pro Tip: You can use Xcode's jump bar to lookup methods with argument labels. If you’re particularly good at mashing lots of keys simultaneously, put the cursor in the method name and press Shift-Control-Option-Command-C (all 4 modifier keys) and Xcode will kindly put the signature on your clipboard.
Swift types are automatically namespaced by the module that contains them and you should not add a class prefix such as RW. If two names from different modules collide you can disambiguate by prefixing the type name with the module name. However, only specify the module name when there is possibility for confusion, which should be rare.
import SomeModule let myClass = MyModule.UsefulClass()
When creating custom delegate methods, an unnamed first parameter should be the delegate source. (UIKit contains numerous examples of this.)
Preferred:
func namePickerView(_ namePickerView: NamePickerView, didSelectName name: String)
func namePickerViewShouldReload(_ namePickerView: NamePickerView) -> Bool
Not Preferred:
func didSelectName(namePicker: NamePickerViewController, name: String)
func namePickerShouldReload() -> Bool
Use compiler inferred context to write shorter, clear code. (Also see Type Inference.)
Preferred:
let selector = #selector(viewDidLoad)
view.backgroundColor = .red
let toView = context.view(forKey: .to)
let view = UIView(frame: .zero)
Not Preferred:
let selector = #selector(ViewController.viewDidLoad)
view.backgroundColor = UIColor.red
let toView = context.view(forKey: UITransitionContextViewKey.to)
let view = UIView(frame: CGRect.zero)
Generic type parameters should be descriptive, upper camel case names. When a type name doesn't have a meaningful relationship or role, use a traditional single uppercase letter such as T
, U
, or V
.
Preferred:
struct Stack<Element> { ... }
func write<Target: OutputStream>(to target: inout Target)
func swap<T>(_ a: inout T, _ b: inout T)
Not Preferred:
struct Stack<T> { ... }
func write<target: OutputStream>(to target: inout target)
func swap<Thing>(_ a: inout Thing, _ b: inout Thing)
Use US English spelling to match Apple's API.
Preferred:
let color = "red"
Not Preferred:
let colour = "red"
Use extensions to organize your code into logical blocks of functionality. Each extension should be set off with a // MARK: -
comment to keep things well-organized.
In particular, when adding protocol conformance to a model, prefer adding a separate extension for the protocol methods. This keeps the related methods grouped together with the protocol and can simplify instructions to add a protocol to a class with its associated methods.
Preferred:
class MyViewController: UIViewController {
// class stuff here
}
// MARK: - UITableViewDataSource
extension MyViewController: UITableViewDataSource {
// table view data source methods
}
// MARK: - UIScrollViewDelegate
extension MyViewController: UIScrollViewDelegate {
// scroll view delegate methods
}
Not Preferred:
class MyViewController: UIViewController, UITableViewDataSource, UIScrollViewDelegate {
// all methods
}
Since the compiler does not allow you to re-declare protocol conformance in a derived class, it is not always required to replicate the extension groups of the base class. This is especially true if the derived class is a terminal class and a small number of methods are being overridden. When to preserve the extension groups is left to the discretion of the author.
For UIKit view controllers, consider grouping lifecycle, custom accessors, and IBAction in separate class extensions.
Unused (dead) code, including Xcode template code and placeholder comments should be removed. An exception is when your tutorial or book instructs the user to use the commented code.
Aspirational methods not directly associated with the tutorial whose implementation simply calls the superclass should also be removed. This includes any empty/unused UIApplicationDelegate methods.
Preferred:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Database.contacts.count
}
Not Preferred:
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return Database.contacts.count
}
Import only the modules a source file requires. For example, don't import UIKit
when importing Foundation
will suffice. Likewise, don't import Foundation
if you must import UIKit
.
Preferred:
import UIKit
var view: UIView
var deviceModels: [String]
Preferred:
import Foundation
var deviceModels: [String]
Not Preferred:
import UIKit
import Foundation
var view: UIView
var deviceModels: [String]
Not Preferred:
import UIKit
var deviceModels: [String]
if
/else
/switch
/while
etc.) always open on the same line as the statement but close on a new line.Preferred:
if user.isHappy {
// Do something
} else {
// Do something else
}
Not Preferred:
if user.isHappy
{
// Do something
}
else {
// Do something else
}
There should be one blank line between methods and up to one blank line between type declarations to aid in visual clarity and organization. Whitespace within methods should separate functionality, but having too many sections in a method often means you should refactor into several methods.
There should be no blank lines after an opening brace or before a closing brace.
Closing parentheses should not appear on a line by themselves.
Preferred:
let user = try await getUser(
for: userID,
on: connection)
Not Preferred:
let user = try await getUser(
for: userID,
on: connection
)
? :
, empty dictionary [:]
and #selector
syntax addTarget(_:action:)
.Preferred:
class TestDatabase: Database {
var data: [String: CGFloat] = ["A": 1.2, "B": 3.2]
}
Not Preferred:
class TestDatabase : Database {
var data :[String:CGFloat] = ["A" : 1.2, "B":3.2]
}
Long lines should be wrapped at around 70 characters. A hard limit is intentionally not specified.
Avoid trailing whitespaces at the ends of lines.
Add a single newline character at the end of each file.
When they are needed, use comments to explain why a particular piece of code does something. Comments must be kept up-to-date or deleted.
Avoid block comments inline with code, as the code should be as self-documenting as possible. Exception: This does not apply to those comments used to generate documentation.
Avoid the use of C-style comments (/* ... */
). Prefer the use of double- or triple-slash.
Remember, structs have value semantics. Use structs for things that do not have an identity. An array that contains [a, b, c] is really the same as another array that contains [a, b, c] and they are completely interchangeable. It doesn't matter whether you use the first array or the second, because they represent the exact same thing. That's why arrays are structs.
Classes have reference semantics. Use classes for things that do have an identity or a specific life cycle. You would model a person as a class because two person objects are two different things. Just because two people have the same name and birthdate, doesn't mean they are the same person. But the person's birthdate would be a struct because a date of 3 March 1950 is the same as any other date object for 3 March 1950. The date itself doesn't have an identity.
Sometimes, things should be structs but need to conform to AnyObject
or are historically modeled as classes already (NSDate
, NSSet
). Try to follow these guidelines as closely as possible.
Here's an example of a well-styled class definition:
class Circle: Shape {
var x: Int, y: Int
var radius: Double
var diameter: Double {
get {
return radius * 2
}
set {
radius = newValue / 2
}
}
init(x: Int, y: Int, radius: Double) {
self.x = x
self.y = y
self.radius = radius
}
convenience init(x: Int, y: Int, diameter: Double) {
self.init(x: x, y: y, radius: diameter / 2)
}
override func area() -> Double {
return Double.pi * radius * radius
}
}
extension Circle: CustomStringConvertible {
var description: String {
return "center = \(centerString) area = \(area())"
}
private var centerString: String {
return "(\(x),\(y))"
}
}
The example above demonstrates the following style guidelines:
x: Int
, and Circle: Shape
.internal
when they're already the default. Similarly, don't repeat the access modifier when overriding a method.centerString
inside the extension using private
access control.For conciseness, avoid using self
since Swift does not require it to access an object's properties or invoke its methods.
Use self only when required by the compiler (in @escaping
closures, or in initializers to disambiguate properties from arguments). In other words, if it compiles without self
then omit it.
For conciseness, if a computed property is read-only, omit the get clause. The get clause is required only when a set clause is provided.
Preferred:
var diameter: Double {
return radius * 2
}
Not Preferred:
var diameter: Double {
get {
return radius * 2
}
}
Marking classes or members as final
in tutorials can distract from the main topic and is not required. Nevertheless, use of final
can sometimes clarify your intent and is worth the cost. In the below example, Box
has a particular purpose and customization in a derived class is not intended. Marking it final
makes that clear.
// Turn any generic type into a reference type using this Box class.
final class Box<T> {
let value: T
init(_ value: T) {
self.value = value
}
}
Keep short function declarations on one line including the opening brace:
func reticulateSplines(spline: [Double]) -> Bool {
// reticulate code goes here
}
For functions with long signatures, put each parameter on a new line and add an extra indent on subsequent lines:
func reticulateSplines(
spline: [Double],
adjustmentFactor: Double,
translateConstant: Int,
comment: String
) -> Bool {
// reticulate code goes here
}
Don't use (Void)
to represent the lack of an input; simply use ()
. Use Void
instead of ()
for closure and function outputs.
Preferred:
func updateConstraints() -> Void {
// magic happens here
}
typealias CompletionHandler = (result) -> Void
Not Preferred:
func updateConstraints() -> () {
// magic happens here
}
typealias CompletionHandler = (result) -> ()
Mirror the style of function declarations at call sites. Calls that fit on a single line should be written as such:
let success = reticulateSplines(splines)
If the call site must be wrapped, put each parameter on a new line, indented one additional level:
let success = reticulateSplines(
spline: splines,
adjustmentFactor: 1.3,
translateConstant: 2,
comment: "normalize the display")
Use trailing closure syntax only if there's a single closure expression parameter at the end of the argument list. Give the closure parameters descriptive names.
Preferred:
UIView.animate(withDuration: 1.0) {
self.myView.alpha = 0
}
UIView.animate(withDuration: 1.0, animations: {
self.myView.alpha = 0
}, completion: { finished in
self.myView.removeFromSuperview()
})
Not Preferred:
UIView.animate(withDuration: 1.0, animations: {
self.myView.alpha = 0
})
UIView.animate(withDuration: 1.0, animations: {
self.myView.alpha = 0
}) { f in
self.myView.removeFromSuperview()
}
For single-expression closures where the context is clear, use implicit returns:
attendeeList.sort { a, b in
a > b
}
Chained methods using trailing closures should be clear and easy to read in context. Decisions on spacing, line breaks, and when to use named versus anonymous arguments is left to the discretion of the author. Examples:
let value = numbers.map { $0 * 2 }.filter { $0 % 3 == 0 }.index(of: 90)
let value = numbers
.map {$0 * 2}
.filter {$0 > 50}
.map {$0 + 10}
Always use Swift's native types and expressions when available. Swift offers bridging to Objective-C so you can still use the full set of methods as needed.
Preferred:
let width = 120.0 // Double
let widthString = "\(width)" // String
Less Preferred:
let width = 120.0 // Double
let widthString = (width as NSNumber).stringValue // String
Not Preferred:
let width: NSNumber = 120.0 // NSNumber
let widthString: NSString = width.stringValue // NSString
In drawing code, use CGFloat
if it makes the code more succinct by avoiding too many conversions.
Constants are defined using the let
keyword and variables with the var
keyword. Always use let
instead of var
if the value of the variable will not change.
Tip: A good technique is to define everything using let
and only change it to var
if the compiler complains!
You can define constants on a type rather than on an instance of that type using type properties. To declare a type property as a constant simply use static let
. Type properties declared in this way are generally preferred over global constants because they are easier to distinguish from instance properties. Example:
Preferred:
enum Math {
static let e = 2.718281828459045235360287
static let root2 = 1.41421356237309504880168872
}
let hypotenuse = side * Math.root2
Note: The advantage of using a case-less enumeration is that it can't accidentally be instantiated and works as a pure namespace.
Not Preferred:
let e = 2.718281828459045235360287 // pollutes global namespace
let root2 = 1.41421356237309504880168872
let hypotenuse = side * root2 // what is root2?
Static methods and type properties work similarly to global functions and global variables and should be used sparingly. They are useful when functionality is scoped to a particular type or when Objective-C interoperability is required.
Declare variables and function return types as optional with ?
where a nil
value is acceptable.
Use implicitly unwrapped types declared with !
only for instance variables that you know will be initialized later before use, such as subviews that will be set up in viewDidLoad()
. Prefer optional binding to implicitly unwrapped optionals in most other cases.
When accessing an optional value, use optional chaining if the value is only accessed once or if there are many optionals in the chain:
textContainer?.textLabel?.setNeedsDisplay()
Use optional binding when it's more convenient to unwrap once and perform multiple operations:
if let textContainer = textContainer {
// do many things with textContainer
}
When naming optional variables and properties, avoid naming them like optionalString
or maybeView
since their optional-ness is already in the type declaration.
For optional binding, shadow the original name whenever possible rather than using names like unwrappedView
or actualLabel
.
Preferred:
var subview: UIView?
var volume: Double?
// later on...
if let subview = subview, let volume = volume {
// do something with unwrapped subview and volume
}
// another example
resource.request().onComplete { [weak self] response in
guard let self = self else { return }
let model = self.updateModel(response)
self.updateUI(model)
}
Not Preferred:
var optionalSubview: UIView?
var volume: Double?
if let unwrappedSubview = optionalSubview {
if let realVolume = volume {
// do something with unwrappedSubview and realVolume
}
}
// another example
UIView.animate(withDuration: 2.0) { [weak self] in
guard let strongSelf = self else { return }
strongSelf.alpha = 1.0
}
Consider using lazy initialization for finer grained control over object lifetime. This is especially true for UIViewController
that loads views lazily. You can either use a closure that is immediately called { }()
or call a private factory method. Example:
lazy var locationManager = makeLocationManager()
private func makeLocationManager() -> CLLocationManager {
let manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.delegate = self
manager.requestAlwaysAuthorization()
return manager
}
Notes:
[unowned self]
is not required here. A retain cycle is not created.Prefer compact code and let the compiler infer the type for constants or variables of single instances. Type inference is also appropriate for small, non-empty arrays and dictionaries. When required, specify the specific type such as CGFloat
or Int16
.
Preferred:
let message = "Click the button"
let currentBounds = computeViewBounds()
var names = ["Mic", "Sam", "Christine"]
let maximumWidth: CGFloat = 106.5
Not Preferred:
let message: String = "Click the button"
let currentBounds: CGRect = computeViewBounds()
var names = [String]()
For empty arrays and dictionaries, use type annotation. (For an array or dictionary assigned to a large, multi-line literal, use type annotation.)
Preferred:
var names: [String] = []
var lookup: [String: Int] = [:]
Not Preferred:
var names = [String]()
var lookup = [String: Int]()
NOTE: Following this guideline means picking descriptive names is even more important than before.
Prefer the shortcut versions of type declarations over the full generics syntax.
Preferred:
var deviceModels: [String]
var employees: [Int: String]
var faxNumber: Int?
Not Preferred:
var deviceModels: Array<String>
var employees: Dictionary<Int, String>
var faxNumber: Optional<Int>
Free functions, which aren't attached to a class or type, should be used sparingly. When possible, prefer to use a method instead of a free function. This aids in readability and discoverability.
Free functions are most appropriate when they aren't associated with any particular type or instance.
Preferred
let sorted = items.mergeSorted() // easily discoverable
rocket.launch() // acts on the model
Not Preferred
let sorted = mergeSort(items) // hard to discover
launch(&rocket)
Free Function Exceptions
let tuples = zip(a, b) // feels natural as a free function (symmetry)
let value = max(x, y, z) // another free function that feels natural
Code (even non-production, tutorial demo code) should not create reference cycles. Analyze your object graph and prevent strong cycles with weak
and unowned
references. Alternatively, use value types (struct
, enum
) to prevent cycles altogether.
Extend object lifetime using the [weak self]
and guard let self = self else { return }
idiom. [weak self]
is preferred to [unowned self]
where it is not immediately obvious that self
outlives the closure. Explicitly extending lifetime is preferred to optional chaining.
Preferred
resource.request().onComplete { [weak self] response in
guard let self = self else {
return
}
let model = self.updateModel(response)
self.updateUI(model)
}
Not Preferred
// might crash if self is released before response returns
resource.request().onComplete { [unowned self] response in
let model = self.updateModel(response)
self.updateUI(model)
}
Not Preferred
// deallocate could happen between updating the model and updating UI
resource.request().onComplete { [weak self] response in
let model = self?.updateModel(response)
self?.updateUI(model)
}
Full access control annotation in tutorials can distract from the main topic and is not required. Using private
and fileprivate
appropriately, however, adds clarity and promotes encapsulation. Prefer private
to fileprivate
; use fileprivate
only when the compiler insists.
Only explicitly use open
, public
, and internal
when you require a full access control specification.
Use access control as the leading property specifier. The only things that should come before access control are the static
specifier or attributes such as @IBAction
, @IBOutlet
and @discardableResult
.
Preferred:
private let message = "Great Scott!"
class TimeMachine {
private dynamic lazy var fluxCapacitor = FluxCapacitor()
}
Not Preferred:
fileprivate let message = "Great Scott!"
class TimeMachine {
lazy dynamic private var fluxCapacitor = FluxCapacitor()
}
Prefer the for-in
style of for
loop over the while-condition-increment
style.
Preferred:
for _ in 0..<3 {
print("Hello three times")
}
for (index, person) in attendeeList.enumerated() {
print("\(person) is at position #\(index)")
}
for index in stride(from: 0, to: items.count, by: 2) {
print(index)
}
for index in (0...3).reversed() {
print(index)
}
Not Preferred:
var i = 0
while i < 3 {
print("Hello three times")
i += 1
}
var i = 0
while i < attendeeList.count {
let person = attendeeList[i]
print("\(person) is at position #\(i)")
i += 1
}
The Ternary operator, ?:
, should only be used when it increases clarity or code neatness. A single condition is usually all that should be evaluated. Evaluating multiple conditions is usually more understandable as an if
statement or refactored into instance variables. In general, the best use of the ternary operator is during assignment of a variable and deciding which value to use.
Preferred:
let value = 5
result = value != 0 ? x : y
let isHorizontal = true
result = isHorizontal ? x : y
Not Preferred:
result = a > b ? x = c > d ? c : d : y
When coding with conditionals, the left-hand margin of the code should be the "golden" or "happy" path. That is, don't nest if
statements. Multiple return statements are OK. The guard
statement is built for this.
Preferred:
func computeFFT(context: Context?, inputData: InputData?) throws -> Frequencies {
guard let context = context else {
throw FFTError.noContext
}
guard let inputData = inputData else {
throw FFTError.noInputData
}
// use context and input to compute the frequencies
return frequencies
}
Not Preferred:
func computeFFT(context: Context?, inputData: InputData?) throws -> Frequencies {
if let context = context {
if let inputData = inputData {
// use context and input to compute the frequencies
return frequencies
} else {
throw FFTError.noInputData
}
} else {
throw FFTError.noContext
}
}
When multiple optionals are unwrapped either with guard
or if let
, minimize nesting by using the compound version when possible. In the compound version, place the guard
on its own line, then indent each condition on its own line. The else
clause is indented to match the guard
itself, as shown below. Example:
Preferred:
guard
let number1 = number1,
let number2 = number2,
let number3 = number3
else {
fatalError("impossible")
}
// do something with numbers
Not Preferred:
if let number1 = number1 {
if let number2 = number2 {
if let number3 = number3 {
// do something with numbers
} else {
fatalError("impossible")
}
} else {
fatalError("impossible")
}
} else {
fatalError("impossible")
}
Guard statements are required to exit in some way. Generally, this should be simple one line statement such as return
, throw
, break
, continue
, and fatalError()
. Large code blocks should be avoided. If cleanup code is required for multiple exit points, consider using a defer
block to avoid cleanup code duplication.
Swift does not require a semicolon after each statement in your code. They are only required if you wish to combine multiple statements on a single line.
Do not write multiple statements on a single line separated with semicolons.
Preferred:
let swift = "not a scripting language"
Not Preferred:
let swift = "not a scripting language";
NOTE: Swift is very different from JavaScript, where omitting semicolons is generally considered unsafe
Parentheses around conditionals are not required and should be omitted.
Preferred:
if name == "Hello" {
print("World")
}
Not Preferred:
if (name == "Hello") {
print("World")
}
In larger expressions, optional parentheses can sometimes make code read more clearly.
Preferred:
let playerMark = (player == current ? "X" : "O")
When building a long string literal, you're encouraged to use the multi-line string literal syntax. Open the literal on the same line as the assignment but do not include text on that line. Indent the text block one additional level.
Preferred:
let message = """
You cannot charge the flux \
capacitor with a 9V battery.
You must use a super-charger \
which costs 10 credits. You currently \
have \(credits) credits available.
"""
Not Preferred:
let message = """You cannot charge the flux \
capacitor with a 9V battery.
You must use a super-charger \
which costs 10 credits. You currently \
have \(credits) credits available.
"""
Not Preferred:
let message = "You cannot charge the flux " +
"capacitor with a 9V battery.\n" +
"You must use a super-charger " +
"which costs 10 credits. You currently " +
"have \(credits) credits available."
Do not use emoji in your projects. For those readers who actually type in their code, it's an unnecessary source of friction. While it may be cute, it doesn't add to the learning and it interrupts the coding flow for these readers.
Likewise, do not use Xcode's ability to drag a color or an image into a source statement. These turn into #colorLiteral and #imageLiteral, respectively, and present unpleasant challenges for a reader trying to enter them based on tutorial text. Instead, use UIColor(red:green:blue)
and UIImage(imageLiteralResourceName:)
.
Where an Xcode project is involved, the organization should be set to Ray Wenderlich
and the Bundle Identifier set to com.raywenderlich.TutorialName
where TutorialName
is the name of the tutorial project.
The following copyright statement should be included at the top of every source file:
/// Copyright (c) 2022 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
Smiley faces are a very prominent style feature of the raywenderlich.com site! It is very important to have the correct smile signifying the immense amount of happiness and excitement for the coding topic. The closing square bracket ]
is used because it represents the largest smile able to be captured using ASCII art. A closing parenthesis )
creates a half-hearted smile, and thus is not preferred.
Preferred:
:]
Not Preferred:
:)
Author: raywenderlich
Source code: https://github.com/raywenderlich/swift-style-guide
License: View license
#swift