teleren/devto huggingface dataset:
self, Self, and Self.self in Swift
Tags: swift, self
Published: 2024-04-23 15:06:08

---
title: self, Self, and Self.self in Swift
published: true
date: 2024-04-01 15:23:09 UTC
tags: Swift,self
canonical_url: https://wesleydegroot.nl/blog/self-Self-Self.self-in-Swift
---

Let's dive into the fascinating world of `self`, `Self`, and `Self.self` in Swift.  
These seemingly similar constructs have distinct meanings and use cases.

## What is `self` (lowercase)?

When you're inside an instance method or property of a class, `self` refers to the **current instance** of that class.  
It's like saying, "Hey, I'm talking about myself!"

```swift
class Pokemon {
    var name: String

    init(name: String) {
        self.name = name
    }

    func introduce() {
        print("Hello, my name is \(self.name).")
    }
}

let dragonite = Pokemon(name: "Dragonite")
dragonite.introduce() // Prints: "Hello, my name is Dragonite."
```

## What is `Self` (capital 'S')?

When you're working with protocols and protocol extensions, `Self` (with a capital 'S') refers to the **type that conforms to the protocol**.  
It's like saying, "Whoever adopts this protocol, listen up!"

```swift
protocol Duplicatable {
    func duplicate() -> Self
}
```

In the Duplicatable protocol, Self is used to specify that the duplicate() method should return an instance of the conforming type.  
The exact type is not specified in the protocol itself, but will be determined by the type that conforms to the protocol.  
It allows each conforming type to have a clear contract: if you conform to Duplicatable, you must implement a duplicate() method that returns an instance of your own type.

## What is `Self.self`?

When you use `Self.self`, you're referring to the **type itself** (not an instance).  
It's like saying, "I want to talk about the blueprint, not the actual house."

```swift
class Animal {
    static func describe() {
        print("This is an animal.")
    }
}

class Dog: Animal {
    override class func describe() {
        print("This is a dog.")
    }
}

let someAnimalType = Animal.self
someAnimalType.describe() // Prints: "This is an animal."

let someDogType = Dog.self
someDogType.describe() // Prints: "This is a dog."
```

## Practical Use Cases

- **`self`** :

- **`Self`** :

- **`Self.self`** :

## Wrapping Up

- `self` is for instances.
- `Self` is for protocols and protocol extensions.
- `Self.self` is for talking about types themselves.

## Conclusion

Understanding the differences between `self`, `Self`, and `Self.self` is crucial for writing clean and maintainable Swift code.

Resources:

- [https://docs.swift.org/swift-book/documentation/the-swift-programming-language/methods/](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/methods/)
- [https://nilcoalescing.com/blog/UseCasesForSelfInSwift](https://nilcoalescing.com/blog/UseCasesForSelfInSwift)
Intro to Git & GitHub: add files into your repository
Tags: git, github, githubactions
Published: 2024-04-01 15:23:00

**Hi everyone, I'm Mahfuz Hossain, a student of Information and Communication Engineering from Bangladesh.**

> Git is a popular distributed version control system
 that provides a robust framework for managing and organizing code repositories, while GitHub, a web-based hosting service, offers a platform for hosting Git repositories. It's a popular choice among developers for code hosting and collaboration.

**In this article, I'm going to show you step by step how to create, add and push files to your project in GitHub.** 


### Prerequisites
To initialize the repo and push it to GitHub, you’ll need:

1. [A free GitHub Account](https://github.com/)
2. [git installed on your local machine](https://git-scm.com/downloads)

## Step 1 — Create a new GitHub Repo

Sign in to your GitHub account and create a [new repository](https://github.com/new).Give your project name into the repository name.


![adding new repository](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s1mg08htjmjqir7zzey6.png)

## Step 2 - Initialize the Git Repo
Open terminal, go to the folder you would like to add.Make sure you are in the root directory of the project you want to push to GitHub and run: 

_Note: If you already have an initialized Git repository, you can skip this command._

```
 git init
```
This will create a hidden .git directory in your project folder

## Step 3 - Add the files to the Git index for commit

```
git add <filename>
```
replace _filename_ with your file 
The git add command will tell git which files to include in a commit. A commit is a basically check-point that captures the changes you have made to the files in your repository.

Instead of this, you can also run `git add .` if you want to add all the files at once.

## Step 4 - Commit Added Files

```
git commit -m 'added myproject'
```
This git commit command creates a commit, and the _-m_ flag allows you to provide a _commit message_ that describes the purpose or context of the changes made in the commit.

## Step 5 -Add a new remote origin

```
git remote add origin git@github.com:username/myProject.git
```

This command establishes a connection between your local Git repository(your PC) and a remote repository(the server) hosted on GitHub.

## Step 6 - Push to GitHub

```
git push -u origin main
```

-  It sends the local commits(from your pc) and changes to the remote repository(github server).
-  _-u_ sets the upstream branch, linking the local "main" branch to the remote "main" branch. This allows you to simply use `git push` in the future without specifying the branch and remote.

## All together

```
git init
git add <filename>
git commit -m 'added myproject'
git remote add origin git@github.com:username/myProject.git
git push -u origin main
```
Congratulations! Now you are all set to track your file, code changes remotely in GitHub!
You can take additional help from the official [Git resources.](https://git-scm.com/docs/gittutorial)

**That's all from me. Good luck with your Git journey!**
Kicking Off My Journey on dev.to: Celebrating a great Full-Stack React Tutorial
Tags: webdev, react, node, fullstack
Published: 2024-04-01 15:13:53

Hi everyone! I'm a software developer from Germany. Today, I'm excited to highlight how an exceptional article has reshaped my understanding of full-stack development. Among the myriad of resources available, the "Full Stack Project Tutorial: Create a Notes App using React and Node.js" on FreeCodeCamp.org stood out remarkably.

[Read the inspiring article here](https://www.freecodecamp.org/news/full-stack-project-tutorial-create-a-notes-app-using-react-and-node-js/)

[Watch the tutorial as video](https://www.youtube.com/watch?v=2MoSzSlAuNk)

![How to app looks like](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d35fhxzczok8cp1m3xbj.png)

## Why This Article?

This tutorial shines for its comprehensive, accessible, and hands-on methodology, guiding learners through the creation of a practical notes application. It delves deep into using React for the frontend and Node.js for the backend, showcasing a powerful synergy crucial for modern web development.

## Key Takeaways:

<u>- Practical Application:
</u> A step-by-step journey through a real-world project, demystifying the full-stack development process.

<u>- Technology Stack Insight:
</u> Offers in-depth understanding of React and Node.js, vital for today's web development. While the tutorial's use of ElephantSQL may not be future-proof, it remains a valuable educational resource.

<u>- Learning by Doing:
</u> Stresses the importance of applying theory in practice, enriching the comprehension of integrating frontend and backend seamlessly.

## Conclusion:

I wholeheartedly recommend this tutorial to anyone eager to enhance their full-stack capabilities. It's a treasure trove of knowledge for both novices and seasoned developers alike. A big thank you to the author for compiling such a thorough and instructive guide. Sharing knowledge and experiences is a cornerstone of our growth as developers. May this article inspire you to expand your skills and contribute to our community.

Don't be too hard on me for my first article :)
Ibuprofeno.py💊| #68: Explica este código Python
Tags: python, spanish, programming, learning
Published: 2024-04-01 15:09:15

## **<center>Explica este código Python</center>**
#### <center>**Dificultad:** <mark>Intermedio</mark></center>

```py
## Reto #68
my_dict = {"a":1, "b":2}
copy_my_dict = my_dict
my_dict["c"] = 3
print(copy_my_dict)
```

👉 **A.** `TypeError`
👉 **B.** `{'a': 1, 'b': 2, 'c': 3}`
👉 **C.** `{'a': 1, 'b': 2}`
👉 **D.** `Ninguna de las anteriores`

---

Respuesta en el primer comentario.
ExpressibleByStringLiteral URL
Tags: swift, expressiblebystringl
Published: 2024-04-11 08:41:42

---
title: ExpressibleByStringLiteral URL
published: true
date: 2024-04-01 15:01:18 UTC
tags: Swift,ExpressibleByStringL
canonical_url: https://wesleydegroot.nl/blog/ExpressibleByStringLiteral-URL
---

The `ExpressibleByStringLiteral` protocol is a powerful feature in Swift that allows us to create custom types directly from string literals. Essentially, it enables us to initialize instances of our custom types using string values. This can be incredibly useful for scenarios where we want to represent certain data types more intuitively or avoid force unwrapping when dealing with known valid strings.

## Writing the extension `ExpressibleByStringLiteral`

```swift
/// Lets URLs be expressed conveniently with literal strings:
/// # Example:
/// let baseUrl: URL = "https://wesleydegroot.nl/blog"
extension URL: ExpressibleByStringLiteral {
    public init(stringLiteral string: StaticString) {
        guard let url = URL(string: "\(string)") else {
            preconditionFailure("Invalid literal URL string: \(string)")
        }
        self = url
    }
}
```

## Use Case: `ExpressibleByStringLiteral` for URLs

```swift
let baseUrl: URL = "https://wesleydegroot.nl/blog"
print(baseUrl.absoluteString) // Output: "https://wesleydegroot.nl/blog"
```

## Conclusion

In summary, `ExpressibleByStringLiteral` empowers us to make our custom types more expressive and convenient to work with. By conforming to this protocol, we can simplify our code and enhance readability.

Remember to explore other use cases and experiment with different types to harness the full potential of `ExpressibleByStringLiteral` in your Swift projects!

Resources:

- [Apple Documentation](https://developer.apple.com/documentation/swift/expressiblebystringliteral)
Moving "server-only" to the top of the imports
Tags: typescript, react, prettier, frontend
Published: 2024-04-03 13:19:14

---
title: Moving "server-only" to the top of the imports
published: true
date: 2024-04-01 15:00:45 UTC
tags: typescript, react, prettier, frontend
canonical_url: https://richdevelops.dev/moving-server-only-to-the-top-of-the-imports
cover_image: https://cdn.hashnode.com/res/hashnode/image/upload/v1711700851192/c11c2306-2539-43f8-871a-65e1c546d5b9.png?w=1600&h=840&fit=crop&crop=entropy&auto=compress,format&format=webp
---

Like many developers I use Prettier to keep my code base looking consistent. One of the plugins we use is @trivago/prettier-plugin-sort-imports which automatically sorts the order of our imports.

While converting an old Gatsby website to NextJS we wanted to use the server-only package to prevent leaking secrets. By positioning it at the top of the file it would also allow us to quickly identify server only code. Of course the sort imports plugin had very different ideas and diligently moved it further down the list.

```
import { type ClientPerspective, type QueryParams, createClient } from "next-sanity";import "server-only";
```

Fixing this should just require adding `^server-only$` to the start of the `importOrder` setting but the plugin keeping putting it last.

```
{ "plugins": ["@trivago/prettier-plugin-sort-imports"], "importOrder": ["^server-only$", "^[./]"], "importOrderSeparation": true, "importOrderSortSpecifiers": true}
```

After a little mucking around I realised that it was sorting the modules correctly and putting server-only first but the sorted import list always appeared after the third party modules. This made it look like the plugin wasn't working. Luckily fixing this was trivial thanks to the `<THIRD_PARTY_MODULES>` placeholder that could be used to sort where they appeared.

```
{ "plugins": ["@trivago/prettier-plugin-sort-imports"], "importOrder": ["^server-only$", "<THIRD_PARTY_MODULES>", "^[./]"], "importOrderSeparation": true, "importOrderSortSpecifiers": true}
```

With done that all my server-only imports moved to the top of their files.

```
import "server-only";import { type ClientPerspective, type QueryParams, createClient } from "next-sanity";
```
Embracing the Fun: Share Your Favorite Tech April Fools'!
Tags: watercooler, discuss
Published: 2024-04-01 15:00:00

Ah, April Fools' Day—a time when the tech world unleashes its creativity, blending humour with innovation to concoct some of the most memorable pranks and gags. From fake product launches to tongue-in-cheek announcements, the tech industry never fails to entertain on April 1st.

My favourite is probably Google's ambitious "Project Virgle" prank, where they collaborated with Virgin Group to humorously announce plans for colonising Mars. The elaborate hoax, complete with a dedicated website and recruitment videos, captured the imagination of many, blending science fiction with April Fools' whimsy.

Share your favourites below; it's great to reminisce on the jokes of yesteryear.
Taxi To Gatwick Airport & Gatwick Taxi Transfers
Tags: taxi, to, gatwick
Published: 2024-04-01 14:49:44

We at UK Airport Taxi aim to provide the most reliable, safe and affordable London Airport Transfers. We have extensive experience in pre-booked Airports pick-up and drop-off at Heathrow Airport, Gatwick Airport, Luton Airport, London City Airport and Stansted Airport. Our prices are up to 40% cheaper than the metered taxis that you hire at the airports and up to 20% cheaper than Uber.
We are proud to provide the best, reliable and affordable services to our customers with highest customer satisfaction. We have invested in state-of-the-art booking system and we have various fleet of vehicles drove by the experienced licensed drivers, so whenever you need a professional Taxi Service, Choose UK Airport Taxi.
https://www.ukairporttaxi.co.uk/gatwick-taxi.aspx
What are your goals for week 14 of 2024?
Tags: discuss, motivation
Published: 2024-04-01 14:44:16

It's April, today is the first, trust no one. It's week 14 of 2024. 

## What are your goals for this week? 

- What are you building? 
- What will be a good result by week's end?
- What events are happening this week? 
  * any suggestions for in person or virtual events?
- Any special goals for the quarter?


### Last Week's Goals
 

- [:white_check_mark:] Continue Job Search. got a rejection Saturday on a holiday weekend. 
  * Lesson 1 bad company if they're working on a holiday.
  * Lesson 2 don't check email on a holiday weekend.
- [:x:] Project work 
   * Got an idea to revive an old inventory project. Need to make progress.
- [:x:] Blog 
- Events 
  * [:white_check_mark:] Wednesday DevRel Meetup with Ciare Carey & Bekah Hawrot Weigel.
  * Thursday Virtual Coffee 
- [:white_check_mark:] Need to track online events, just write them down. Signed up for events later in the month.
- [:x:] Work on The DEV Frontend Challenges.
- [:white_check_mark:] This is Virtual Coffee's month of get job ready. I'll run a goal setting thread on Slack. 

 
### This Week's Goals

 

- Continue Job Search. 
- Project work 
   * Got an idea to revive an old inventory project. Need to make progress.
   * Update content on a site.
- Blog 
- Events 
  * Wednesday Nashville Data Nerds. Right at commute time.
  * Thursday Virtual Coffee 
- Need to track online events, just write them down.
- I'll run a goal setting thread on Virtual Coffee Slack. 
- Work on The new DEV Challenges that will be announced later in the week. 



### Your Goals for the week 

Your turn what do you plan to do this week? 

- What are you building? 
- What will be a good result by week's end?
- What events are happening any week? 
  * in person or virtual?


```html
-$JarvisScript  git commit -m "Time for accountability"
```
Mastering GraphQL Integration with React and Node: Key Considerations
Published: 2024-04-01 14:31:03

1.Schema Design: Define a well-structured GraphQL schema that accurately represents your data model and the relationships between different entities.
2.Resolvers: Implement resolver functions on the Node server to fetch and manipulate data from various data sources (e.g., databases, APIs) based on the incoming GraphQL queries and mutations.
3.Query and Mutation Operations: Write GraphQL queries and mutations on the client-side (React) to request and modify data from the server. Ensure that the queries and mutations are optimized and only request the necessary data to minimize network traffic.
4.Data Fetching and Caching: Efficiently fetch data from the server using GraphQL query hooks or libraries like Apollo Client. Implement caching strategies to avoid redundant network requests and provide a smooth user experience.

5.Error Handling: Handle errors gracefully on both the server and client sides. Catch and handle exceptions in the resolver functions, and display appropriate error messages to the user in the React components.

6.Authentication and Authorization: Implement secure authentication and authorization mechanisms to protect sensitive data and control access to certain GraphQL operations or data fields.

7.Performance Optimization: Optimize the performance of your GraphQL API by implementing features such as data batching, caching, and pagination. Use tools like DataLoader to reduce the number of database queries and improve response times.

8.Testing: Write unit tests and integration tests for your server-side resolves and client-side components to ensure the correctness and robustness of your GraphQL implementation.
Want to be part of the digital future? Join Hyperledger Iroha!
Published: 2024-04-01 14:18:41

Ready to participate in the next digital revolution, the Internet of Ownership known as Web3?  
Take the first step and gain practical experience working with Hyperledger Iroha, the blockchain technology underpinning advanced CBDCs, identity solutions, and telecom providers.  
Connect here: [Join Now!](https://www.iroha.tech/contribute)
How to Create Moment JS Calendar in React Native
Tags: reactnative, react, momentjs, calendar
Published: 2024-04-01 14:11:50

Hey there, fellow developers! Today, we're diving into the world of React Native and Moment.js to create a dynamic and user-friendly calendar for your Expo projects. 

Whether you're building a scheduling app or just want to display dates with finesse, this step-by-step guide has got you covered.

In this tutorial, We'll see how to create a Moment JS calendar react native with a step-by-step guide. And how to import Moment JS in the React Native Application.

Let's get started on crafting a sleek and functional calendar that'll elevate your React Native skills!

Creating a calendar using Moment.js in React Native with Expo involves a few steps. Here's a step-by-step guide for you:

> Step 1: Set Up Your Expo Project

Ensure you have Expo CLI installed. If not, install it using:

```
npm install -g expo-cli
```

Create a new Expo project:

```
expo init MomentJSCalendar
cd MomentJSCalendar
``` 

> Step 2: Install Moment.js


Install Moment.js using:

```
npm install moment
``` 

> Step 3: Create Calendar Component

Create a new component for your calendar (e.g., CalendarComponent.js):

```
import React from 'react';
import { View, Text } from 'react-native';
import moment from 'moment';

const CalendarComponent = () => {
  return (
    <View style={styles.container}>
        <Text style={styles.date}>{moment().calendar() }</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 16,
    backgroundColor: '#fff',
    borderRadius: 8,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 2,
    elevation: 4,
  },
});

export default CalendarComponent;
``` 

> Step 4: Use Calendar Component

Use the CalendarComponent in your main file (e.g., App.js):

```
import React from 'react';
import { StyleSheet, View } from 'react-native';
import CalendarComponent from './CalendarComponent';

export default function App() {
  return (
    <View style={styles.container}>
      <CalendarComponent />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
``` 

> Step 5: Run Your Expo App

Run your Expo app using:

```
expo start
``` 

> Conclusion:

And that's a wrap, folks! We've journeyed through integrating Moment.js into React Native with Expo to fashion a calendar that suits your app's needs. 

From the basics of setup to displaying the current month.

Now, you learn how to import moment in react native, and how to create a calendar in react native using moment js.

Happy coding!

---

You might also like:

#### **[Read Also: How To Validate Form in React JS](https://vidvatek.com/post/how-to-validate-form-in-react-js)**

#### **[Read Also: How to Create Autocomplete Search in React](https://vidvatek.com/post/how-to-create-autocomplete-search-in-react)**
Day 1/366
Tags: 1percentplusplus, 100daysofcode
Published: 2024-04-01 14:02:45

🚀 Today's Learning:

🌟 DSA

- Static vs Dynamic Arrays
- Memory Allocation and Management

🌟 DEV

- HTML - Elements and Semantic Tags
- CSS - Selectors, Box Model, Pseudo Classes 

🔍 Some Key Highlights:

- Static arrays have a fixed size set at compile time, stored in either the stack or data segment. Access is super fast (O(1)) due to direct memory address calculation.

- Dynamic arrays offer flexibility with size adjustment during runtime, managed via pointers and memory allocation functions like `malloc()` and `new`. But beware of memory leaks and undefined behavior!

- While dynamic arrays are powerful, they require careful memory management. Luckily, C++ provides safer alternatives like **`std::vector`** for automatic memory management and resizing.

- HTML is like the backbone of web pages, providing the structure and content.

- There are various HTML elements like **`<div>`**, **`<a>`**, **`<form>`**, and **`<meta>`**, each serving a unique purpose in creating web content.

- Understanding the **`DOCTYPE`** declaration ensures browsers render HTML correctly, like a passport guiding them through the document.

- The `semantic` HTML tags **help the search engines and other user devices to determine the importance and context of web pages**. The pages made with semantic elements are much easier to read.

- Examples of **non-semantic** elements: `<div>` and `<span>` - Tells nothing about its content.

- Examples of **semantic** elements: `<form>`, `<table>`, and `<article>` - Clearly defines its content.

- CSS is like the stylist of the web, adding colors, layouts, and animations to HTML elements.

- Selectors act like detectives, targeting specific elements for styling based on their tags, classes, or IDs.

- The box model concept clarified how padding, margin, border, and content interact to define an element's appearance.

- Pseudo-classes provide dynamic styling, allowing elements to change appearance based on user interaction. (e.g. a:hover)

Let's keep exploring and learning together! 🚀 Feel free to share your thoughts and experiences in the comments below. 📝

 #1PercentPlusPlus #100DaysOfCode #LearningEveryday #LearnInPublic #Programming #Coding #DSA #SoftwareDevelopment