Coder Social home page Coder Social logo

hackingwithswift's Introduction

Hacking with Swift

This is the source code to accompany Hacking with Swift, a free tutorial series that teaches Swift coding for iOS. There is one folder for the classic Hacking with Swift course, which teaches UIKit and SpriteKit, and another folder for the SwiftUI edition.

All SwiftUI projects should be compatible with Xcode 15 and iOS 17. Where appropriate, separate project files have been provided so that you can follow the tutorial from scratch without having to dig around in the completed project folder.

If you have questions, you can find me on Twitter @twostraws.

Recommended links

The Hacking with Swift book contains over 1300 pages of tutorials and example code, and makes a great addition to any developer's collection. Thank you to everyone who bought the book – your purchase helps me create more great Swift content in the future!

Pro Swift is the sequel to Hacking with Swift, and includes a 250-page guide to helping you write faster, more efficient Swift, accompanied by over 70 videos demonstrating each technique. If you want to dive into functional programming, learn more about MVVM, get to grips with @autoclosure and @escaping, or try your hand at protocol-oriented development, Pro Swift is for you.

Swift Coding Challenges is an all-new book written from the ground up to put your Swift skills to the test. I've written a variety of coding challenges that start off simple but slowly get harder, and it's down to you to solve them. I outline each problem, provide you with sample input and output, add in some hints in case you hit problems, then provide a sample solution and explain how it works.

Swift

iOS

Example Code

hackingwithswift's People

Contributors

atrinh0 avatar gerrior avatar hudzilla avatar ishtiaq156 avatar john-mueller avatar machinemxy avatar michalsrutek avatar mohadel92 avatar pgudivadadiligent avatar schwalbe10 avatar tomorr avatar twostraws avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hackingwithswift's Issues

Project 1 classic assisted view moved

Assisted view is now in the editor menu under:
Editor > Assisted
and to change view type of assisted view i.e. assisted on bottom is now under:
Editor > view
This is more of an issue with the day 2 blog page for project 1

There are some deprecated objects in IOS 12

200: unarchiveObject(with:)' was deprecated in iOS 12.0: Use +unarchivedObjectOfClass:fromData:error: instead
286: let data = NSKeyedArchiver.archivedData(withRootObject: value) 'archivedData(withRootObject:)' was deprecated in iOS 12.0: Use +archivedDataWithRootObject:requiringSecureCoding:error: instead

Project 13

Calling the following line of code generates a memory warning and the application is terminated:

let cgimg = context.createCGImage(currentFilter.outputImage!, fromRect: currentFilter.outputImage!.extent)

You can test it by moving the filter slider a couple of times. The memory of the App itself remains stable. I have not been able to detect any leak using Instruments.

As It doesn't happen in iOS8.4.1 with Swift 1.2, I do believe that the issue is in iOS9, but not 100% sure.

Just in case, I've opened a radar 22844426.

Cheers,
Pablo.

Project 26 Contribution

I would like to share my Idea with you. I have enjoyed your teachings and videos over the years. I am a hobby programmer at best. I am going to work with your code to reverse the walls and vortex's and replace them with landing spots, multiple balls, and a shake motion to free/restart/reset the balls. (there is a slight ledge on the wall that will hold the ball, a slight shake is needed to release it from the wall. Too much and you disturb the rest that are already set). Here is an example of what I am talking about. Maybe you can do it better and use it as an add-on to this project. Thanks again for all your knowledge and sharing. It has been a great learning site.
IMG_1998
IMG_1999

Project 25: MultiPeerConnectivity under iOS 14

Project 25 gets this error under iOS 14:
2020-11-24 17:48:03.324768+0100 Project25[11326:3107644] [MCNearbyServiceBrowser] NSNetServiceBrowser did not search with error dict [{
NSNetServicesErrorCode = "-72008";
NSNetServicesErrorDomain = 10;
}]

Chapter 9

Looks like Chapter 7 files are in the Chapter 9 folder

Instructions could be a bit clearer

First of all, thank you so much for putting this together!

FWIW, I'm following along with the first project found here: https://www.hackingwithswift.com/read/1/1/setting-up

I came here to clone the repository, but it wasn't clear that I needed to look under the Classic folder. There's also a project1 folder in SwiftUI, but no project1-files folder.

I'm not complaining, I just thought you might find the feedback useful.

Thanks again,
-Doug

How its work ? missing methods

note: project1
how its work without this func

override func numberOfSections(in tableView: UITableView) -> Int { return 1 }

Tutorial without Storyboard

Great tutorials!

You should add one tutorial without using Storyboard.
Only defining views using code or maybe using Cartography or other framework to simplify this

Learning

Hello there wanna learn hacking can u tell me how to start pls

Project 30 timer code not matching with book text

Code in project file:

animTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { timer in

Code in book text:

self.animTimer = Timer.scheduledTimerWithTimeInterval(5, target: self, selector: #selector(animateImage), userInfo: nil, repeats: true)

Looks like the book text needs updated since scheduledTimer(withTimeInterval:repeats:block) is the current syntax.

Project 2

When setting auto constraints I see "vertical spacing" and i see "centre horizontally" but not "centre horizontally in container" so i selected centre horizontally and my flags are all over the place! Again any ideas please thanks in advance

Access UI properties from background thread in project 9

Hi All,

I thought you are not supposed to access/change UI. However I've noticed in this sample, fetchJSON is executed in the background thread but is reading UI property navigationController?.tabBarItem.tag. Am I missing something?

@objc func fetchJSON() {
let urlString: String
if navigationController?.tabBarItem.tag == 0 {
urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100"
} else {
urlString = "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100"
}
if let url = URL(string: urlString) {
if let data = try? Data(contentsOf: url) {
parse(json: data)
return
}
}
performSelector(onMainThread: #selector(showError), with: nil, waitUntilDone: false)
}

No folder called content

"You'll see another folder in there called project1 and inside that folder called content." there is not folder called Content i will down load the image files individually but it does lead to confusion for novice users. Like myself
Hope you don't mind the feedback

Project 1 files

I've reviewed the link sent by message receiver but the files for project 1 cannot be downloaded? Please advise....

Typo in Chapter 9 of book

When enumerating the four QoS levels, the second, User Initiated, contains a typo.

User Initiated: (...) i.e., if the user taps on buttons to do other stuff, that could should be executed (...)

"Could" should be removed from this line.

Classic - Project 22: locationManager(_ didChangeAuthorization status: CLAuthorizationStatus) was deprecated in iOS 14.0

Classic - Project 22: Detect a Beacon.
I see alerts:

  • locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) was deprecated in iOS 14.0

  • locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) was deprecated in iOS 13.0

Maybe need to update below functions in HackingWithSwift/Classic/project22/Project22/ViewController.swift

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
  if status == .authorizedAlways {
	  if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
		  if CLLocationManager.isRangingAvailable() {
			  startScanning()
		  }
	  }
  }
}


func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
    if beacons.count > 0 {
	    let beacon = beacons[0]
	    update(distance: beacon.proximity)
    } else {
	    update(distance: .unknown)
    }
}

to

func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
    if manager.authorizationStatus == .authorizedAlways {
        if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
		if CLLocationManager.isRangingAvailable() {
			startScanning()
		}
	}
    }
}

func locationManager(_ manager: CLLocationManager, didRange beacons: [CLBeacon], satisfying beaconConstraint: CLBeaconIdentityConstraint) {
    if beacons.count > 0 {
        let beacon = beacons[0]
        update(distance: beacon.proximity)
    } else {
        update(distance: .unknown)
    }
}

Project 1

Xcode Version 7.0 (7A220) ios 9 SDK

let object = objects[indexPath.row]
cell.textLabel!.text = object as! String
return cell

hv to write as! String to compile.

random levels for project 8

Hello,

I found your tutorial amazing and was wondering if theres a way to have random levels instead of going through the levels numerically, for project 8. I can't seem to find the solution.

Thanks in advance.

We Split: Picker view for works only once and then crshes.

Picker("Number of people", selection: $numberOfPeople) {
ForEach(2 ..< 100) {
Text("($0) people")
}
}

Issue:
2020-03-26 11:04:18.389974+0530 WeSplit[4297:62153] [TableView] Warning once only: UITableView was told to layout its visible cells and other contents without being in the view hierarchy (the table view or one of its superviews has not been added to a window). This may cause bugs by forcing views inside the table view to load and perform layout without accurate information (e.g. table view bounds, trait collection, layout margins, safe area insets, etc), and will also cause unnecessary performance overhead due to extra layout passes. Make a symbolic breakpoint at UITableViewAlertForLayoutOutsideViewHierarchy to catch this in the debugger and see what caused this to occur, so you can avoid this action altogether if possible, or defer it until the table view has been added to a window. Table view: <TtC7SwiftUIP33_BFB370BA5F1BADDC9D83021565761A4925UpdateCoalescingTableView: 0x7fe76b00d800; baseClass = UITableView; frame = (0 0; 414 896); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x600003e51530>; layer = <CALayer: 0x60000307c800>; contentOffset: {0, -140}; contentSize: {414, 4390.3333333333276}; adjustedContentInset: {140, 0, 34, 0}; dataSource: <TtGC7SwiftUIP13$7fff2c69da4419ListCoreCoordinatorGVS_20SystemListDataSourceOs5Never_GOS_19SelectionManagerBoxS2_: 0x7fe77144adc0>>

Project 36 PhysicsBody: Could not create physics body on createPlayer()

iOS 13.7 (SE 2nd simulator)
Xcode Version 11.7 (11E801a)
Swift: Apple Swift version 5.2.4 (swiftlang-1103.0.32.9 clang-1103.0.32.53)

Console output:

2020-09-08 23:05:24.019709+0200 Project36[66680:2549632] Metal GPU Frame Capture Enabled
2020-09-08 23:05:24.020347+0200 Project36[66680:2549632] Metal API Validation Enabled
2020-09-08 23:05:24.153016+0200 Project36[66680:2549632] PhysicsBody: Could not create physics body.

error on unwrapping nil on line 86:

		player.physicsBody!.contactTestBitMask = player.physicsBody!.collisionBitMask

player.phisicsBody is nil

SwiftUI Project 11

while i delete book in DetailView and then i tap the edit button in the navigationBar can't into the edit mode and the lists of books jump to show

+ add contact leftBarButtonItem never loads

The build succeeds, but the bar never loads so I can never add a contact.

The master Project10 obviously works fine. Is there anything else I can check other than the "initial view controller" box being checked.

I was a little confused by my Collection View PersonCell only having the label Person even after I had typed PersonCell and hit enter as prescribed. I have restarted the project once and gone back half way once so any tips would be much appreciated. Apologies if this is the wrong place to add a query.

Project 25—issue connecting with projects created in Xcode 11.1

How to reproduce:

  1. Create a new project in Xcode 11.1
  2. Follow the instructions in project 25 (you can also just copy the ViewController.swift file from this repo).
  3. Run the app on two devices and try to join a session. It won't ever connect.

Now, if you delete SceneDelegate.swift, remove the two UISceneSession lifecycle methods in AppDelegate.swift and then remove the scene related dictionary item in Info.plist and re-run the apps, you'll see it works as expected.

Project 2: Asset Files Flags

Very important! The flagfiles from Github are all writen in lowercase (If you add them by copy paste). But in the array on the SwiftUI-Tutorial every country starts with uppercase and then lowercase. So once you are coding and building, the asset files cant be found(---> case-sensitive). You need to rename the files or easier rename the country names in the array. Hope this helped.

Working though project 4 have error

Use of unresolved identifier 'navigationAction' tied exactly as our code? really confused
ok i am fool worked it out !!!! sorry which you could delete these !

Where is the content folder?

In the tutorial it says there is a Content Folder inside the Project 1 folder, but I do not see a content folder.

Project5: app accepts empty string.

I made a test case in which I submitted an empty string.
Result: The app accepted it and added it two a new table row.
Expected: Empty string should be rejected because not only is it an anagram but also it is not even an English word.

header '/usr/include/gd.h' not found in project5

OP: MacOS Sierra
Env: Docker using ibmcom/swift-ubuntu:latest

Hello, all the previous projects worked as intended but when in comes to project five after
swift package init --type executable and modifying the Package.swift when I tried to build the project I got the following:

root@bb33f543917b:/projects/project5# swift build
Compile Swift Module 'SwiftGD' (1 sources)
Compile CHTTPParser utils.c
Compile Swift Module 'KituraStencil' (1 sources)
Compile CHTTPParser http_parser.c
/projects/project5/.build/checkouts/Cgd.git--1390626494485699789/module.modulemap:2:9: error: header '/usr/include/gd.h' not found
header "/usr/include/gd.h"
^
/projects/project5/.build/checkouts/SwiftGD.git-1170172309405307774/Sources/SwiftGD.swift:3:9: error: could not build Objective-C module 'Cgdlinux'
import Cgdlinux
^
:0: error: build had 1 command failures
error: exit(1): /usr/bin/swift-build-tool -f /projects/project5/.build/debug.yaml

Project 34

Will the source code for this project be made available?

Project 7 issue with Xcode 11.1

The following code does not work in new project created in Xcode 11.1 due to the changes to SceneKit.

if let tabBarController = window?.rootViewController as? UITabBarController {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "NavController")
    vc.tabBarItem = UITabBarItem(tabBarSystemItem: .topRated, tag: 1)
    tabBarController.viewControllers?.append(vc)
}

I was able to get it working by doing the following in a new project:

  1. Delete SceneDelegate.swift
  2. Delete Application Scene Manifest in Info.plist
  3. In AppDelegate.swift, do the following:
    1. Add var window: UIWindow?
    2. Delete application(_ :, configurationForConnecting:, options:) and application(_:, sceneSessions:)

Project 4 SwiftUI deprecation warning

FYI:

When instantiating the mlmodel class in calculateBedtime via:

let model = SleepCalculator()

Gives the following deprecation warning (Xcode 12.4 - 12D4e):

'init()' is deprecated: Use init(configuration:) instead and handle errors appropriately.

Xcode 7.2

Prompted to change project settings and convert to Swift 2 syntax.
Example:

In MasterViewController

let items = try? fm.contentsOfDirectoryAtPath(path)

items is then optional and needs checking/unwrapping

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.