blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
6
116
path
stringlengths
5
872
src_encoding
stringclasses
7 values
length_bytes
int64
10
4.68M
score
float64
2.52
5.63
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
7
4.81M
download_success
bool
1 class
e86f5f140e369bf31f78b59f8aa4c1d28794e424
Swift
averello/fizzbuzz
/fizzbuzz.playground/Sources/direct.swift
UTF-8
1,919
3.234375
3
[ "MIT" ]
permissive
// // direct.swift // fizzbuzz3 // // Created by Georges Boumis on 19/2/20. // Copyright © 2020 Georges Boumis. All rights reserved. // import Foundation public struct Direct { enum Command { /// Nop. case skip /// Stops the execution of the current program. case halt /// Prints the given argument. case print(String) } typealias Program = [Command] typealias Context = (Program) -> Program static func interpret(_ p: Program) -> String { func foldr<A : Sequence, B>(xs: A, y: B, f: @escaping (A.Iterator.Element, () -> B) -> B) -> B { var g = xs.makeIterator() var next: () -> B = {y} next = { return g.next().map {x in f(x, next)} ?? y } return next() } func step(_ c: Command, _ r: () -> String) -> String { switch c { case .skip: return r() case .halt: return "" case .print(let s): return s + r() } } return foldr(xs: p, y: "", f: step) } static let fizz = { (n: Int) -> Context in return n % 3 == 0 ? { x in [Command.print("fizz")] + x + [Command.halt] } : { x in x } } static let buzz = { (n: Int) -> Context in return n % 5 == 0 ? { x in [Command.print("buzz")] + x + [Command.halt] } : { x in x } } static let base = { (n: Int) -> Context in return { x in x + [Command.print("\(n)")] } } static let fb = { (n: Int) -> Program in return (base(n) ◦ fizz(n) ◦ buzz(n))([Command.skip]) // return base(n)(fizz(n)(buzz(n)([Command.skip]))) } public static let fizzbuzz = { (n: Int) -> String in interpret(fb(n)) } }
true
82693bba3fc46ca5505591dbe69f227f38eae4ca
Swift
yugandh/TextFieldNavigationFromKeyboard
/TextFieldNavigationFromKeyboard/ViewController.swift
UTF-8
3,103
2.59375
3
[]
no_license
// // ViewController.swift // TextFieldNavigationFromKeyboard // // Created by Yugandhar Kommineni on 12/2/18. // Copyright © 2018 Yugandhar Kommineni. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var firstTextfield: UITextField! @IBOutlet weak var secondTextfield: UITextField! @IBOutlet weak var thirdTextfield: UITextField! @IBOutlet weak var fourthTextfield: UITextField! @IBOutlet weak var fifthTextfield: UITextField! @IBOutlet weak var sixthTextfield: UITextField! var textFieldNavigator: TextFieldNavigation? var currentTextField: UITextField? override func viewDidLoad() { super.viewDidLoad() currentTextField?.delegate = self firstTextfield.delegate = self secondTextfield.delegate = self thirdTextfield.delegate = self fourthTextfield.delegate = self fifthTextfield.delegate = self sixthTextfield.delegate = self textFieldNavigator = TextFieldNavigation() textFieldNavigator?.textFields = [firstTextfield,secondTextfield,thirdTextfield,fourthTextfield,fifthTextfield,sixthTextfield] } @objc func keyboardDidShow(notification: NSNotification) { let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let keyboardSize:CGSize = keyboardFrame.size let contentInsets:UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) scrollView.contentInset = contentInsets scrollView.scrollIndicatorInsets = contentInsets var aRect:CGRect = self.view.frame aRect.size.height -= keyboardSize.height if currentTextField != nil { if !(aRect.contains(currentTextField!.frame.origin)) { scrollView.scrollRectToVisible(currentTextField!.frame, animated: true) } } } @objc func keyboardWillHide(notification: NSNotification) { let contentInsents:UIEdgeInsets = UIEdgeInsets.zero scrollView.contentInset = contentInsents scrollView.scrollIndicatorInsets = contentInsents } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.view.backgroundColor = .red NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } } extension ViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { currentTextField = textField } private func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) { currentTextField = nil } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
true
a44818bd2599cde746c9b965c087db6c86fa16cf
Swift
letopeasbro/fakeTimeline
/homework/Widgets/AvatarView.swift
UTF-8
1,504
2.78125
3
[]
no_license
// // AvatarView.swift // homework // // Created by 刘奕成 on 2019/6/13. // Copyright © 2019 Eason. All rights reserved. // import UIKit class AvatarView: UIImageView { let cornerRadius: CGFloat init(cornerRadius v1: CGFloat = 0.0) { cornerRadius = v1 super.init(frame: .zero) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Public extension AvatarView { /// 设置头像 /// NOTE: 在确定AutoLayout布局完成后调用, 或传入sideLength以保证圆角能正确设置 /// /// - Parameters: /// - url: 头像地址 /// - sideLength: 头像视图边长, 传入nil则使用bounds.height func setAvatar(_ url: URL?, sideLength: CGFloat? = nil) { let cornerRatio = cornerRadius / (sideLength ?? bounds.height) setImage(url, placeholder: nil, transform: { (image) -> UIImage? in let frame = CGRect(origin: .zero, size: image.size) UIGraphicsBeginImageContextWithOptions(frame.size, false, image.scale) let path = UIBezierPath(roundedRect: frame, cornerRadius: image.size.height * cornerRatio) path.addClip() image.draw(in: frame) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result }) { (image, _, fromType, state) in self.image = image } } }
true
20cd19471235c0972ae1830785054bce5b488934
Swift
krajabi/MentisFuel
/RKitBase/TabBarController.swift
UTF-8
1,365
2.703125
3
[]
no_license
// // TabBarController.swift // RKitBase // // Created by Admin on 8/30/16. // Copyright © 2016 Neil Lakin. All rights reserved. // import UIKit class TabBarController: UITabBarController { override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // No need for semicolon //set the appearance of the TabBar self.tabBar.translucent = false self.tabBar.clipsToBounds = true self.tabBar.backgroundImage = Constants.Images.BACKGROUND } override func viewDidLoad() { super.viewDidLoad() } } extension UIImage { func imageWithColor(tintColor: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let context = UIGraphicsGetCurrentContext()! as CGContextRef CGContextTranslateCTM(context, 0, self.size.height) CGContextScaleCTM(context, 1.0, -1.0); CGContextSetBlendMode(context, .Normal) let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect CGContextClipToMask(context, rect, self.CGImage!) tintColor.setFill() CGContextFillRect(context, rect) let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage UIGraphicsEndImageContext() return newImage } }
true
608bb5067456b5720eed65c45fa08e224bee5901
Swift
rezakuwux/TestProofn
/TetProofn/ViewController.swift
UTF-8
869
2.546875
3
[]
no_license
// // ViewController.swift // TetProofn // // Created by Reza on 11/04/19. // Copyright © 2019 Kuwux. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // var string = "hefg" // let originStr = string // var biggerGreater = "" // repeat{ // Must start at lowest permutation // if biggerGreater == "" && string != originStr{ // biggerGreater = string // } // else if string > originStr && biggerGreater > string{ // biggerGreater = string // } // } while (TestProofn.biggerIsGreater(string: &string, originStr: originStr)); // // Do any additional setup after loading the view, typically from a nib. // print(biggerGreater) } }
true
7c7fd15639ae1bf4bd7589eaaf10d12fa115ec5a
Swift
mokacoding/biblio
/biblio/BookViewController.swift
UTF-8
1,133
2.671875
3
[]
no_license
import UIKit class BookViewController: UIViewController { @IBOutlet var coverImageView: UIImageView! @IBOutlet var titleLabel: UILabel! var book: [String: Any]? var googleBook: [String: Any]? override func viewWillAppear(_ animated: Bool) { titleLabel.text = book?["title"] as? String if let googleBook = googleBook { if let bookInfo = (googleBook["items"] as? [[String: Any]])?.first?["volumeInfo"] as? [String: Any], let imageLinks = bookInfo["imageLinks"] as? [String: Any], let thumbnailURLString = (imageLinks["thumbnail"] as? String)?.replacingOccurrences(of: "http://", with: "https://"), let thumbnailURL = URL(string: thumbnailURLString) { ImageCache.shared.image(for: thumbnailURL) { image in if let image = image { DispatchQueue.main.async { [weak self] in self?.coverImageView.image = image } } } } } } @IBAction func save(sender: UIButton) { if var book = self.book { book["googleBook"] = googleBook LocalBooksManager.shared.save(book) } } }
true
66259e3d88e95f4f4ff72b83191473b7629e6f85
Swift
cgranthovey/provEve
/ProvoEvents/EventArrayExtension.swift
UTF-8
2,284
3.109375
3
[]
no_license
// // EventArrayExtension.swift // Ibento // // Created by Chris Hovey on 11/5/16. // Copyright © 2016 Chris Hovey. All rights reserved. // import Foundation // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } extension Array where Element: Event{ func NewDictWithTimeCategories() -> Dictionary<Int, [Event]>{ var eventsToday = [Event]() var eventsTomorrow = [Event]() var eventsInTheNextWeek = [Event]() var eventsFuture = [Event]() var totalDict = Dictionary<Int, [Event]>() for event in self{ if event.timeStampOfEvent < getTodaysEndTime(){ eventsToday.append(event) totalDict[0] = eventsToday } else if event.timeStampOfEvent < getTomorrowsEndTime(){ eventsTomorrow.append(event) totalDict[1] = eventsTomorrow } else if event.timeStampOfEvent < getEventsInNextWeekEndTime(){ eventsInTheNextWeek.append(event) totalDict[2] = eventsInTheNextWeek } else{ eventsFuture.append(event) totalDict[3] = eventsFuture } } return totalDict } func getTodaysEndTime() -> Int{ let currentDate = Date() let calendar = Calendar.current let currentHour = (calendar as NSCalendar).component(.hour, from: currentDate) let currentMinute = (calendar as NSCalendar).component(.minute, from: currentDate) let secondsInToday = (currentHour * 60 * 60 + currentMinute * 60) let nowInSeconds = Int(currentDate.timeIntervalSince1970) let todayStartInSeconds = nowInSeconds - secondsInToday return todayStartInSeconds + 86400 //86400 is seconds in a day } func getTomorrowsEndTime() -> Int{ return getTodaysEndTime() + 86400 } func getEventsInNextWeekEndTime() -> Int{ return getTodaysEndTime() + 86400 * 6 } }
true
160d0618d92827871843bee8663aeef7172b0a3d
Swift
sbooth/SFBAudioEngine
/Device/AudioSubdevice.swift
UTF-8
6,062
2.984375
3
[ "LGPL-2.0-or-later", "MIT" ]
permissive
// // Copyright (c) 2020 - 2022 Stephen F. Booth <me@sbooth.org> // Part of https://github.com/sbooth/SFBAudioEngine // MIT license // import Foundation import CoreAudio /// A HAL audio subdevice /// - remark: This class correponds to objects with base class `kAudioSubDeviceClassID` public class AudioSubdevice: AudioDevice { } extension AudioSubdevice { /// Returns the extra latency /// - remark: This corresponds to the property `kAudioSubDevicePropertyExtraLatency` public func extraLatency() throws -> Double { return try getProperty(PropertyAddress(kAudioSubDevicePropertyExtraLatency), type: Double.self) } /// Returns the drift compensation /// - remark: This corresponds to the property `kAudioSubDevicePropertyDriftCompensation` public func driftCompensation() throws -> Bool { return try getProperty(PropertyAddress(kAudioSubDevicePropertyDriftCompensation), type: UInt32.self) != 0 } /// Sets the drift compensation /// - remark: This corresponds to the property `kAudioSubDevicePropertyDriftCompensation` public func setDriftCompensation(_ value: Bool) throws { try setProperty(PropertyAddress(kAudioSubDevicePropertyDriftCompensation), to: UInt32(value ? 1 : 0)) } /// Returns the drift compensation quality /// - remark: This corresponds to the property `kAudioSubDevicePropertyDriftCompensationQuality` public func driftCompensationQuality() throws -> UInt32 { return try getProperty(PropertyAddress(kAudioSubDevicePropertyDriftCompensationQuality), type: UInt32.self) } /// Sets the drift compensation quality /// - remark: This corresponds to the property `kAudioSubDevicePropertyDriftCompensationQuality` public func setDriftCompensationQuality(_ value: UInt32) throws { try setProperty(PropertyAddress(kAudioSubDevicePropertyDriftCompensationQuality), to: value) } } extension AudioSubdevice { /// A thin wrapper around a HAL audio subdevice drift compensation quality setting public struct DriftCompensationQuality: RawRepresentable, ExpressibleByIntegerLiteral, ExpressibleByStringLiteral { /// Minimum quality public static let min = DriftCompensationQuality(rawValue: kAudioSubDeviceDriftCompensationMinQuality) /// Low quality public static let low = DriftCompensationQuality(rawValue: kAudioSubDeviceDriftCompensationLowQuality) /// Medium quality public static let medium = DriftCompensationQuality(rawValue: kAudioSubDeviceDriftCompensationMediumQuality) /// High quality public static let high = DriftCompensationQuality(rawValue: kAudioSubDeviceDriftCompensationHighQuality) /// Maximum quality public static let max = DriftCompensationQuality(rawValue: kAudioSubDeviceDriftCompensationMaxQuality) public let rawValue: UInt32 public init(rawValue: UInt32) { self.rawValue = rawValue } public init(integerLiteral value: UInt32) { self.rawValue = value } public init(stringLiteral value: StringLiteralType) { self.rawValue = value.fourCC } } } extension AudioSubdevice.DriftCompensationQuality: CustomDebugStringConvertible { // A textual representation of this instance, suitable for debugging. public var debugDescription: String { switch self.rawValue { case kAudioSubDeviceDriftCompensationMinQuality: return "Minimum" case kAudioSubDeviceDriftCompensationLowQuality: return "Low" case kAudioSubDeviceDriftCompensationMediumQuality: return "Medium" case kAudioSubDeviceDriftCompensationHighQuality: return "High" case kAudioSubDeviceDriftCompensationMaxQuality: return "Maximum" default: return "\(self.rawValue)" } } } extension AudioSubdevice { /// Returns `true` if `self` has `selector` in `scope` on `element` /// - parameter selector: The selector of the desired property /// - parameter scope: The desired scope /// - parameter element: The desired element public func hasSelector(_ selector: AudioObjectSelector<AudioSubdevice>, inScope scope: PropertyScope = .global, onElement element: PropertyElement = .master) -> Bool { return hasProperty(PropertyAddress(PropertySelector(selector.rawValue), scope: scope, element: element)) } /// Returns `true` if `selector` in `scope` on `element` is settable /// - parameter selector: The selector of the desired property /// - parameter scope: The desired scope /// - parameter element: The desired element /// - throws: An error if `self` does not have the requested property public func isSelectorSettable(_ selector: AudioObjectSelector<AudioSubdevice>, inScope scope: PropertyScope = .global, onElement element: PropertyElement = .master) throws -> Bool { return try isPropertySettable(PropertyAddress(PropertySelector(selector.rawValue), scope: scope, element: element)) } /// Registers `block` to be performed when `selector` in `scope` on `element` changes /// - parameter selector: The selector of the desired property /// - parameter scope: The desired scope /// - parameter element: The desired element /// - parameter block: A closure to invoke when the property changes or `nil` to remove the previous value /// - throws: An error if the property listener could not be registered public func whenSelectorChanges(_ selector: AudioObjectSelector<AudioSubdevice>, inScope scope: PropertyScope = .global, onElement element: PropertyElement = .master, perform block: PropertyChangeNotificationBlock?) throws { try whenPropertyChanges(PropertyAddress(PropertySelector(selector.rawValue), scope: scope, element: element), perform: block) } } extension AudioObjectSelector where T == AudioSubdevice { /// The property selector `kAudioSubDevicePropertyExtraLatency` public static let extraLatency = AudioObjectSelector(kAudioSubDevicePropertyExtraLatency) /// The property selector `kAudioSubDevicePropertyDriftCompensation` public static let driftCompensation = AudioObjectSelector(kAudioSubDevicePropertyDriftCompensation) /// The property selector `kAudioSubDevicePropertyDriftCompensationQuality` public static let driftCompensationQuality = AudioObjectSelector(kAudioSubDevicePropertyDriftCompensationQuality) }
true
40e9edb4882448911640ae73798711873162220a
Swift
rugaru/SwiftUI
/SwiftUIApp/Models/Place.swift
UTF-8
255
2.53125
3
[]
no_license
// // Place.swift // SwiftUIApp // // Created by Alina on 03.03.2020. // Copyright © 2020 rugarusik. All rights reserved. // import SwiftUI struct Place: Codable, Identifiable { var id: Int var name: String var imageName: String }
true
f9c227c0e8fb7f4423f8cb3a5d9d5e1f89d42c24
Swift
augustius/stGeofence
/stGeofence/Model/Geofence+Extension.swift
UTF-8
2,814
3.125
3
[]
no_license
// // Geofence+Extension.swift // stGeofence // // Created by Augustius on 24/11/2019. // Copyright © 2019 august. All rights reserved. // import Foundation import CoreLocation import MapKit import CoreData struct GeofenceParam { var coordinate: CLLocationCoordinate2D var locationName: String var radius: Double var wifiName: String } enum GeoState { case inside(CLRegion), outside(CLRegion) } extension GeoState { func readableStatus() -> String { switch self { case .inside(let region): return "INSIDE \(region.identifier)" case .outside(let region): return "OUTSIDE \(region.identifier)" } } } extension Geofence: MKAnnotation { public var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } public var title: String? { return locationName } public var subtitle: String? { return "Radius : \(radius)" } func toCLCircularRegion() -> CLCircularRegion { return CLCircularRegion(center: coordinate, radius: radius, identifier: locationName ?? "") } func getDistanceFrom(_ location: CLLocation) -> CLLocationDistance { return location.distance(from: coordinate.toCLLocation()) } } extension Array where Element: Geofence { func sortByClosest(_ location: CLLocation) -> [Geofence] { return self.sorted { (firstGeo, secondGeo) -> Bool in return firstGeo.coordinate.toCLLocation().distance(from: location) < secondGeo.coordinate.toCLLocation().distance(from: location) } } } extension Set where Element: CLRegion { func sortByFurthest(_ location: CLLocation) -> [CLRegion] { return self.sorted { (firstGeo, secondGeo) -> Bool in guard let firstGeoCircle = firstGeo as? CLCircularRegion, let secondGeoCircle = secondGeo as? CLCircularRegion else { return false } return firstGeoCircle.center.toCLLocation().distance(from: location) > secondGeoCircle.center.toCLLocation().distance(from: location) } } } extension CLLocationCoordinate2D: Equatable { public static func == (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool { return (lhs.latitude == rhs.latitude) && (lhs.longitude == rhs.longitude) } func toCLLocation() -> CLLocation { return CLLocation(latitude: latitude, longitude: longitude) } } extension MKMapView { func zoomToUserLocation() { guard let coordinate = userLocation.location?.coordinate else { return } let region = MKCoordinateRegion(center: coordinate, latitudinalMeters: 10000, longitudinalMeters: 10000) setRegion(region, animated: true) } }
true
3cc1bf0e54966019d375531017cd5f5dbac54846
Swift
elizabethsiegle/pennapps2015REALFLOOPINGONE
/pennapps2015/messageViewController.swift
UTF-8
2,744
2.796875
3
[]
no_license
// // messageViewController.swift // pennapps2015 // // Created by Elizabeth Siegle on 9/5/15. // Copyright (c) 2015 Elizabeth Siegle. All rights reserved. // import UIKit class messageViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var messageTableView: UITableView! @IBAction func sendButtonClicked(sender: AnyObject) { firstMessage1.text = textMessage.text textMessage.text = "" firstMessage1.hidden = false let delay = 4.5 * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue()) { self.firstMessage.hidden=false self.firstMessage.text="Is it home life?" } } @IBOutlet weak var firstMessage1: UILabel! @IBOutlet weak var firstMessage: UILabel! var messagesArray:[String] = ["Message 1", "Message 2", "Message 3"] @IBOutlet weak var textMessage: UITextField! override func viewDidLoad() { super.viewDidLoad() firstMessage1.hidden = true firstMessage.hidden = true // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView:UITableView!, numberOfRowsInSection section:Int) -> Int { return 20 } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "mycell") cell.textLabel!.text="row#\(indexPath.row)" cell.detailTextLabel!.text="subtitle#\(indexPath.row)" return cell } } // override func viewDidLoad() { // super.viewDidLoad() // self.messagesArray.append("Message 4") // // self.messageTableView.delegate = self // self.messageTableView.dataSource = self // // // } // // override func didReceiveMemoryWarning() { // super.didReceiveMemoryWarning() // } // // func tableView(tableView:UITableView, cellforRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // let cell = self.messageTableView.dequeueReusableCellWithIdentifier("MessageCell") as! UITableViewCell // // cell.textLabel?.text = self.messagesArray[indexPath.row] // // return cell // // } // // func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return messagesArray.count // } //}
true
a3d1688d494e003841179876c54e1ed13b7cf547
Swift
jhonatn/JSONManipulation
/Sources/JSONManipulation/Steps/UniqueKeyCommand.swift
UTF-8
573
2.65625
3
[]
no_license
import Foundation import JSONKit enum UniqueKeyError: Error { case notAnArray } struct UniqueKey: StepParams {} extension UniqueKey: SingleInputParameters { func process(json: JSONNode) throws -> JSONNode { guard case .array(let array) = json else { throw UniqueKeyError.notAnArray } var addedDict = [JSONNode: Bool]() return .array ( array .compactMap { $0 } .filter { addedDict.updateValue(true, forKey: $0) == nil } ) } }
true
f2f5941f1c64c78ed8329aadf879139bf8687c12
Swift
chrisdn/chrisdn
/Lonpos3D/GameViewController.swift
UTF-8
24,835
2.515625
3
[]
no_license
// // GameViewController.swift // Lonpos3D // // Created by Wei Dong on 2021-08-22. // import SceneKit import SpriteKit import QuartzCore class GameViewController: NSViewController { private var sceneList = [] as [SCNView] @IBOutlet var inputTextField: NSTextView! @IBOutlet var button: NSButton! @IBOutlet var comboBox: NSComboBox! let queue = DispatchQueue(label: "lonpos_queue") private func showGame(game: IGame) { guard sceneList.count < 18 else {return} let scnView = SCNView() let scene = createScene(scnView: scnView) scnView.scene = scene let pyramiad = SCNNode() for index in 0...54 { let p = game.point3d(from: index) let char = game.space[index] guard let piece = Game.pieceCandidates.first(where: {$0.identifier == char}) else {abort()} let ball = SCNSphere(radius: 0.5) ball.firstMaterial?.diffuse.contents = piece.color let node = SCNNode(geometry: ball) let pos = SCNVector3(Float(p.z) / 2 + Float(p.x) - 2, Float(p.z) * sqrtf(2) / 2, Float(p.z) / 2 + Float(p.y) - 2) node.position = pos pyramiad.addChildNode(node) // let action = SCNAction.moveBy(x: pos.x, y: pos.y, z: pos.z, duration: 5) // let a = SCNAction.sequence([action, action.reversed()]) // node.runAction(SCNAction.repeatForever(a)) } scene.rootNode.addChildNode(pyramiad) // pyramiad.runAction(SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 2, z: 0, duration: 3))) sceneList.forEach {$0.removeFromSuperview()} scnView.translatesAutoresizingMaskIntoConstraints = false sceneList.append(scnView) sceneList.forEach {self.view.addSubview($0)} var constraints = [NSLayoutConstraint]() var lastSceneView: SCNView? let cols = sceneList.count >= 6 ? 6 : sceneList.count let rows = sceneList.count <= cols ? 1 : CGFloat(ceilf(Float(sceneList.count) / Float(cols))) for i in 0..<sceneList.count { let v = sceneList[i] if i % cols == 0 { lastSceneView = nil } if let lastView = lastSceneView { constraints.append(v.leftAnchor.constraint(equalTo: lastView.rightAnchor)) lastSceneView = v } else { constraints.append(v.leftAnchor.constraint(equalTo: self.view.leftAnchor)) lastSceneView = v } constraints.append(v.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 1 / CGFloat(cols))) if i / cols > 0 { constraints.append(v.topAnchor.constraint(equalTo: sceneList[i - cols].bottomAnchor)) } else { constraints.append(v.topAnchor.constraint(equalTo: self.view.topAnchor)) } constraints.append(v.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 1 / rows)) } NSLayoutConstraint.activate(constraints) } private func createScene(scnView: SCNView) -> SCNScene { // create a new scene let scene = SCNScene() // create and add a camera to the scene let cameraNode = SCNNode() cameraNode.camera = SCNCamera() scene.rootNode.addChildNode(cameraNode) // place the camera cameraNode.position = SCNVector3(x: 0, y: 15, z: 5) cameraNode.look(at: SCNVector3(0, 0, 0)) // create and add a light to the scene let lightNode = SCNNode() lightNode.light = SCNLight() lightNode.light!.type = .omni lightNode.position = SCNVector3(x: 0, y: 10, z: 8) scene.rootNode.addChildNode(lightNode) // create and add an ambient light to the scene let ambientLightNode = SCNNode() ambientLightNode.light = SCNLight() ambientLightNode.light!.type = .ambient ambientLightNode.light!.color = NSColor.darkGray scene.rootNode.addChildNode(ambientLightNode) // allows the user to manipulate the camera scnView.allowsCameraControl = true // show statistics such as fps and timing information scnView.showsStatistics = true // configure the view scnView.backgroundColor = NSColor.black // Add a click gesture recognizer let clickGesture = NSClickGestureRecognizer(target: self, action: #selector(handleClick(_:))) var gestureRecognizers = scnView.gestureRecognizers gestureRecognizers.insert(clickGesture, at: 0) scnView.gestureRecognizers = gestureRecognizers return scene } @IBAction func startGame(sender: NSControl) { let str = inputTextField.string /* "BBFFFBBWSFBWWSFWWYSSYYYYS" "UU SU SU SSU S" "FFFY FYYYYF" "Y YX X,Y X,YX X,Y" "Y YX X,Y X,YX X,Y" "B CBC CCC,B B,B" */ do { switch comboBox.stringValue { case "Lonpos 2D": UserDefaults.standard.setValue(2, forKey: "last_game_type") let game = try Game2d(str.uppercased().replacingOccurrences(of: ".", with: " ")) button.isEnabled = false UserDefaults.standard.setValue(str, forKey: "last_input") queue.async { game.start() } case "Lonpos 3D": UserDefaults.standard.setValue(1, forKey: "last_game_type") let strList = str.uppercased().replacingOccurrences(of: ".", with: " ").split(separator: ",", omittingEmptySubsequences: false).map {String($0)} let game = strList.count > 1 ? try Game3d(strList) : try Game3d(str.uppercased().replacingOccurrences(of: ".", with: " ")) button.isEnabled = false UserDefaults.standard.setValue(str, forKey: "last_input") queue.async { game.start() } case "Klotski": UserDefaults.standard.setValue(3, forKey: "last_game_type") let game = Klotski(str.replacingOccurrences(of: ".", with: " ")) UserDefaults.standard.setValue(str, forKey: "last_input") queue.async { game.start() } case "Woodoku": UserDefaults.standard.setValue(4, forKey: "last_game_type") showWoodoku() default: GameViewController.showAlert(message: "Please select a game type") } } catch LonposError.inputError(let msg){ GameViewController.showAlert(message: msg) } catch { print(error) } UserDefaults.standard.synchronize() } fileprivate static func showAlert(message: String, information: String = "") { let alert = NSAlert() if !information.isEmpty { alert.informativeText = information } alert.messageText = message alert.alertStyle = .informational alert.addButton(withTitle: "OK") alert.runModal() } private func showWoodoku() { inputTextField.isHidden = true let skView = SKView() skView.ignoresSiblingOrder = true let scene = MySKScene(size: view.bounds.size) skView.presentScene(scene) skView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(skView) NSLayoutConstraint.activate([ skView.leftAnchor.constraint(equalTo: view.leftAnchor), skView.rightAnchor.constraint(equalTo: view.rightAnchor), skView.topAnchor.constraint(equalTo: view.topAnchor), skView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } override func viewDidLoad() { super.viewDidLoad() if let input = UserDefaults.standard.string(forKey: "last_input") { inputTextField.string = input } let type = UserDefaults.standard.integer(forKey: "last_game_type") switch type { case 1: comboBox.stringValue = "Lonpos 3D" case 2: comboBox.stringValue = "Lonpos 2D" case 3: comboBox.stringValue = "Klotski" case 4: comboBox.stringValue = "Woodoku" default: break } NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "lonpos"), object: nil, queue: OperationQueue.main) { note in guard let game = note.object else { self.button.isEnabled = true return } switch game { case let g as IGame: self.showGame(game: g) case let g as Klotski: var str = "" for step in g.steps { str += step.description + " | " } self.inputTextField.string = str default: break } } } override func viewDidAppear() { super.viewDidAppear() if let size = view.window?.frame.size { if size.width < 100 || size.height < 100 { view.window?.setContentSize(NSSize(width: 640, height: 480)) } } } @objc func handleClick(_ gestureRecognizer: NSGestureRecognizer) { // retrieve the SCNView guard let scnView = gestureRecognizer.view as? SCNView else {return} // check what nodes are clicked let p = gestureRecognizer.location(in: scnView) let hitResults = scnView.hitTest(p, options: [:]) // check that we clicked on at least one object if hitResults.count > 0 { // retrieved the first clicked object let result = hitResults[0] // get its material let material = result.node.geometry!.firstMaterial! // highlight it SCNTransaction.begin() SCNTransaction.animationDuration = 0.5 // on completion - unhighlight SCNTransaction.completionBlock = { SCNTransaction.begin() SCNTransaction.animationDuration = 0.5 material.emission.contents = NSColor.black SCNTransaction.commit() } material.emission.contents = NSColor.red SCNTransaction.commit() } } } class MySKScene: SKScene { private var game: Woodoku private let radius: Double = 25 private let smallRadius = 5 as Double private var isCalculating = false private var selectedPieces: [Woodoku.Piece] = [] let startButtonNode = SKLabelNode(text: "Start") let scoreNode = SKLabelNode(text: "0") var pieceSelectionMap = [Woodoku.Piece: Int]() override init(size: CGSize) { if let list = UserDefaults.standard.object(forKey: "Woodoku") as? [[Bool]] { game = Woodoku(board: list) } else { game = Woodoku() } super.init(size: size) addChild(startButtonNode) startButtonNode.name = "Start" startButtonNode.position = CGPoint(x: Double(1 + 4 * 6) * 2 * smallRadius, y: 9 * radius * 2 + radius) addChild(scoreNode) scoreNode.name = "score" scoreNode.position = CGPoint(x: size.width / 2, y: 10 * radius * 2 + radius) scaleMode = .resizeFill let board = SKNode() addChild(board) //draw board for x in 0...8 { for y in 0...8 { let node = SKShapeNode(circleOfRadius: radius) node.position = CGPoint(x: Double(x) * radius * 2 + radius, y: Double(8 - y) * radius * 2 + radius) node.fillColor = game.board[y][x] ? .red : .clear node.strokeColor = NSColor(white: 0.4, alpha: 1) node.name = "\(x),\(y)" + (game.board[y][x] ? "red" : "") board.addChild(node) } } //draw pieces var yoffset = smallRadius var xoffset = radius * 2 * 10 for type in Woodoku.PieceType.allCases { let piece = type.piece let node = createNode(for: piece) node.name = "piece:" + type.rawValue self.addChild(node) node.position = CGPoint(x: xoffset, y: yoffset) yoffset += smallRadius * 2 * Double(piece.pattern.count + 1) if yoffset >= radius * 2 * 9 { yoffset = smallRadius xoffset += radius * 3 } } let clearAllNode = SKLabelNode(text: "Clear Board") clearAllNode.fontSize = 12 clearAllNode.name = "clear" clearAllNode.position = CGPoint(x: xoffset, y: yoffset) addChild(clearAllNode) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func createNode(for piece: Woodoku.Piece) -> SKNode { let node = SKNode() for y in 0..<piece.pattern.count { for x in 0..<piece.pattern[y].count where piece.pattern[y][x] { let ball = SKShapeNode(circleOfRadius: smallRadius) ball.fillColor = .yellow ball.strokeColor = .black ball.position = CGPoint(x: Double(x) * smallRadius * 2, y: Double(piece.pattern.count - 1 - y) * smallRadius * 2) node.addChild(ball) } } return node } private func updateBoard() { for x in 0...8 { for y in 0...8 { guard let node = (childNode(withName: "//\(x),\(y)") ?? childNode(withName: "//\(x),\(y)red")) as? SKShapeNode else { print("cannot find node with name begins with \(x),\(y)") abort() } node.fillColor = game.board[y][x] ? .red : .clear node.name = "\(x),\(y)" + (game.board[y][x] ? "red" : "") } } } override func mouseUp(with event: NSEvent) { guard !isCalculating else {return} var node = atPoint(event.location(in: self)) if node.name == nil, let parent = node.parent { node = parent } guard let name = node.name, name.count >= 3 else {return} guard let snode = node as? SKShapeNode else { if let name = node.name, name.hasPrefix("piece:") { let list = self["selected[0-2]"].compactMap {$0.name?.last}.compactMap {Int(String($0))} let set = Set<Int>(list) let candidates: Set<Int> = [0, 1, 2] let index = candidates.subtracting(set).min() ?? 0 let rawValue = name[name.index(name.startIndex, offsetBy: 6)...] if let pieceType = Woodoku.PieceType(rawValue: String(rawValue)) { let piece = pieceType.piece addNewSelectedPiece(piece, index: index) } if selectedPieces.count == 3 { isCalculating = true startButtonNode.text = "Calculating..." Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in self.calculate() } } } else if name.hasPrefix("selected") { //deselect a previously selected node if let ch = Array(name).last, let index = Int(String(ch)) { selectedPieces.remove(at: index) node.removeFromParent() print(selectedPieces) } } else if name == "clear" { game = Woodoku() score = 0 saveGame() self.enumerateChildNodes(withName: "//[0-8],[0-8]*") { node, _ in (node as? SKShapeNode)?.fillColor = .clear if let name = node.name, name.hasSuffix("red") { let newName = name[..<name.index(name.startIndex, offsetBy: 3)] node.name = String(newName) } } } else if name.lowercased() == "start" { if selectedPieces.count > 0 { isCalculating = true startButtonNode.text = "Calculating..." Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in self.calculate() } } else { //do auto play score = 0 autoPlayOnce() isCalculating = true } } return } let charArray = Array(name) guard let x = Int(String(charArray[0])), let y = Int(String(charArray[2])) else {return} if name.hasSuffix("red") { snode.fillColor = .clear game.board[y][x] = false var newName = name newName.removeLast(3) snode.name = newName } else { snode.fillColor = .red game.board[y][x] = true snode.name = (snode.name ?? "") + "red" } saveGame() } private func addNewSelectedPiece(_ piece: Woodoku.Piece, index: Int) { let node = createNode(for: piece) node.name = "selected\(index)" node.position = CGPoint(x: Double(1 + index * 6) * 2 * smallRadius, y: 9 * radius * 2 + radius) addChild(node) selectedPieces.append(piece) } private var score = 0 { didSet { self.scoreNode.text = "\(self.score)" } } private func autoPlayOnce() { self.removeAllSelectedPieceNodes() selectedPieces.removeAll() for i in 0...2 { let index = Int.random(in: 0...207) let piece = Woodoku.PieceType.allCases.compactMap { type -> Woodoku.Piece? in if let delimiter = type.rawValue.firstIndex(of: "|") { let str = type.rawValue[type.rawValue.index(after: delimiter)...] if let dash = str.firstIndex(of: "-"), let min = Int(str[..<dash]), let max = Int(str[str.index(after: dash)...]), min >= 0, max > min, index >= min, index <= max { return type.piece } } return nil }.first if let piece = piece { score += piece.ballCount addNewSelectedPiece(piece, index: i) } else {abort()} } DispatchQueue.global(qos: .background).async { let solution = self.game.place(pieces: self.selectedPieces) DispatchQueue.main.async { if let newGame = solution.1 { self.game = newGame self.updateBoard() self.score += solution.2 self.autoPlayOnce() } else { self.selectedPieces.removeAll() self.removeAllSelectedPieceNodes() self.startButtonNode.text = "Start" self.isCalculating = false } } } } private func showSteps(bestPiecePositions: [Woodoku.PieceWithPosition], colorValue: CGFloat) { guard let piecePosition = bestPiecePositions.first else { //remove all selected pieces removeAllSelectedPieceNodes() saveGame() return } let piece = piecePosition.piece let pos = piecePosition.pos for y in 0..<piece.pattern.count { for x in 0..<piece.pattern[y].count where piece.pattern[y][x] { guard let node = self.childNode(withName: "//\(x + pos.x),\(y + pos.y)") as? SKShapeNode else { print("cannot find node with name begins with \(x + pos.x),\(y + pos.y)") abort() } node.fillColor = NSColor(hue: colorValue, saturation: 1, brightness: 1, alpha: 1) } } Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false) { _ in self.showTrimmedBoardWithAnimation(pieceWithPlace: piecePosition) Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false) { _ in GameViewController.showAlert(message: "Next") self.showSteps(bestPiecePositions: Array(bestPiecePositions.dropFirst()), colorValue: 0.2 + colorValue) } } } private func saveGame() { UserDefaults.standard.set(game.board, forKey: "Woodoku") UserDefaults.standard.synchronize() } private func showTrimmedBoardWithAnimation(pieceWithPlace: Woodoku.PieceWithPosition) { let unTrimmedGame = game if let g = game.place(piece: pieceWithPlace.piece, at: pieceWithPlace.pos) { game = g } else { abort() } _ = game.trim() for x in 0...8 { for y in 0...8 { if unTrimmedGame.board[y][x] && !game.board[y][x] { guard let node = childNode(withName: "//\(x),\(y)*") as? SKShapeNode else { print("cannot find node with name begins with \(x),\(y)") abort() } node.run(node.getFillColorFadeOutAction()) } } } Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false) { _ in self.updateBoard() } } private func calculate() { // for piece in selectedPieces { // if let count = pieceSelectionMap[piece] { // pieceSelectionMap[piece] = count + 1 // } else { // pieceSelectionMap[piece] = 1 // } // } // for (key, value) in pieceSelectionMap.sorted(by: {$0.1 > $1.1}) { // print(key, value) // } DispatchQueue.global(qos: .background).async { let bestPiecePositions = self.game.place(pieces: self.selectedPieces) DispatchQueue.main.async { self.isCalculating = false self.startButtonNode.text = "Start" let totalBallCount = self.selectedPieces.reduce(0) { total, piece in total + piece.ballCount } self.selectedPieces.removeAll() let solution = bestPiecePositions if let pieceWithPosition = solution.0 { GameViewController.showAlert(message: "Solution found", information: "\(solution.2)") self.showSteps(bestPiecePositions: pieceWithPosition, colorValue: 0.2) self.score += solution.2 + totalBallCount } else { GameViewController.showAlert(message: "Solution not found", information: "\(solution.2)") self.selectedPieces.removeAll() self.removeAllSelectedPieceNodes() } } } } private func removeAllSelectedPieceNodes() { self.enumerateChildNodes(withName: "selected[0-2]") { node, _ in node.removeFromParent() } } override func didChangeSize(_ oldSize: CGSize) { var pos = scoreNode.position pos.x = size.width / 2 scoreNode.position = pos } } extension SKShapeNode { func getFillColorFadeOutAction() -> SKAction { func lerp(_ a: Double, _ b: Double, _ fraction: Double) -> Double { return (b-a) * fraction + a } // get the Color components of col1 and col2 var r:CGFloat = 0.0, g:CGFloat = 0.0, b:CGFloat = 0.0, a1:CGFloat = 0.0; fillColor.getRed(&r, green: &g, blue: &b, alpha: &a1) let a2:CGFloat = 0.0; // return a color fading on the fill color let timeToRun: CGFloat = 0.3; let action = SKAction.customAction(withDuration: 0.3) { node, elapsedTime in let fraction = elapsedTime / timeToRun let col3 = SKColor(red: r, green: g, blue: b, alpha: lerp(a1,a2,fraction)) (node as? SKShapeNode)?.fillColor = col3 } return action } }
true
5b58d53fa9e98e01b461cd11c2217652dfb9e64d
Swift
JoseSPS/LearningSwift
/poo/poo/ViewController.swift
UTF-8
1,593
2.703125
3
[]
no_license
// // ViewController.swift // poo // // Created by Jose Luis Espiritu on 28/12/20. // import UIKit class ViewController: UIViewController { @IBOutlet weak var labelTitulo: UILabel! var objetoMazda3Mini:Mazda3Mini? override func viewDidLoad() { super.viewDidLoad() labelTitulo.text = "Fábrica de Automóviles" } @IBAction func crearObjeto(_ sender: UIButton) { print("Objeto creado") objetoMazda3Mini = Mazda3Mini() } @IBAction func mostrarPropiedades(_ sender: UIButton) { if objetoMazda3Mini != nil{ print("El carro Mazd 3 es de tamaño \(objetoMazda3Mini!.tamaño), tiene \(objetoMazda3Mini!.numeroPuertas) puertas, su color es \(objetoMazda3Mini!.color) su precio es de \(objetoMazda3Mini!.precio) y su porcentaje de carga es \(objetoMazda3Mini!.porcentajeCarga)") } else { print("No se ha creado el objeto") } } @IBAction func encender(_ sender: UIButton) { if objetoMazda3Mini != nil{ objetoMazda3Mini!.encender() } else { print("No se ha creado el objeto") } } @IBAction func acelerar(_ sender: UIButton) { if objetoMazda3Mini != nil{ objetoMazda3Mini!.acelerar() } else { print("No se ha creado el objeto") } } @IBAction func recargar(_ sender: UIButton) { if objetoMazda3Mini != nil{ objetoMazda3Mini!.recargar() } else { print("No se ha creado el objeto") } } }
true
593d09cc6343a022f6f15a8174a5c112b9f1daaf
Swift
zzyhappyzzy/swiftDemo
/SwiftDemo/playground/AppDevelopment/EnumsAndSwitch.playground/Contents.swift
UTF-8
1,869
4.65625
5
[ "MIT" ]
permissive
//: Playground - noun: a place where people can play import UIKit //枚举 enum LunchChoice { case pasta case burger case soup } let choice = LunchChoice.burger //简写 enum Fruit { case apple, orange, banana, pear } //调用时,如果确定枚举类型,可以直接.调用 var fruit : Fruit fruit = .pear //switch必须全面,考虑各种条件 //为避免以后往enum新增类型时,case忘记修改,建议不要使用default,写全case,多个相同的case可以逗号隔开 //enum和switch enum Quality { case bad, poor, acceptable, good, great } var quality = Quality.good switch quality { case .bad: print("That really won't do") case .poor: print("That's not good enough") default: print("OK, I'll take it") } quality = .great switch quality { case .bad: print("That really won't do") case .poor: print("That's not good enough") case .acceptable, .good, .great: print("OK, I'll take it") } //switch还可以和string/number等类型搭配 let animal = "cat" func soundFor(animal: String) -> String { switch animal { case "cat": return "Meow" case "dog": return "Woof" case "cow": return "Moo" case "chicken": return "Cluck" default: return "I don't know that animal" } } soundFor(animal: animal) //和structure一样,enum里也可以定义属性properties和函数functions enum Symbol { case laugh, cry, shy var emoji: String { switch self { case .laugh: return "😀" case .cry: return "😢" case .shy: return "😅" } } func join(_ otherSymbol: Symbol) -> String { return self.emoji + otherSymbol.emoji } } let laugh = Symbol.laugh let shy = Symbol.shy laugh.emoji shy.emoji laugh.join(shy)
true
ef6e3d455e51895aea3d77c025ec7effa57f1415
Swift
TaylorDay11/HershbergerTaylor_AdvMAD
/Project1/MoneyOrganizer/MoneyOrganizer/TripViewController.swift
UTF-8
6,079
2.65625
3
[]
no_license
// // TripViewController.swift // MoneyOrganizer // // Created by Taylor Hershberger on 3/12/18. // Copyright © 2018 Taylor Hershberger. All rights reserved. // import UIKit class TripViewController: UITableViewController { var itemList = [Item]() //Totals @IBOutlet weak var total: UILabel! var calcTotal = 0 @IBOutlet weak var paid: UILabel! var calcPaid = 0 @IBOutlet weak var percent: UILabel! @IBAction func unwindToThisView(sender: UIStoryboardSegue) { self.tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() total.text = "$0" paid.text = "$0" percent.text = "" // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } override func viewDidAppear(_ animated: Bool){ // let nav = self.navigationController?.navigationBar navigationController?.navigationBar.barTintColor = UIColor(red:119/255, green: 179/255, blue: 0/255, alpha: 1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source 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 itemList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) // Configure the cell... let item = itemList[indexPath.row] cell.textLabel!.text = item.name let costString = String(item.cost) cell.detailTextLabel!.text = "$" + costString if(itemList.count > 0){ if(itemList[indexPath.row].paid){ cell.detailTextLabel!.textColor = UIColor.green } else{ cell.detailTextLabel!.textColor = UIColor.red } } return cell } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source self.itemList.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) if (itemList.count > 0){ for i in 0...itemList.count-1{ calcTotal = calcTotal + itemList[i].cost if (itemList[i].paid){ calcPaid = calcPaid + itemList[i].cost } } } total.text = "$" + String(calcTotal) paid.text = "$" + String(calcPaid) if (calcPaid != 0){ let doublecalcPaid = Double(calcPaid) let doublecalcTotal = Double(calcTotal) var paidPercent = 0.0 paidPercent = round((doublecalcPaid/doublecalcTotal)*100) print("percent") print(paidPercent) percent.text = String(paidPercent) + "%" } else{ percent.text = "0%" } } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. //if add button is clicked if segue.identifier == "addItem"{ //sets the data for the destination controller let itemVC = segue.destination as! ItemViewController //Pass Data itemVC.itemListDetail = itemList itemVC.addButton = true } //if cell is clicked if segue.identifier == "editItem"{ let indexPath = tableView.indexPath(for: sender as! UITableViewCell)! //sets the data for the destination controller let itemVC = segue.destination as! ItemViewController //Pass Data itemVC.itemListDetail = itemList itemVC.selectedItem = indexPath.row itemVC.addButton = false } } }
true
22809c3ae829e2f60cf29dec092f28339fd63a5c
Swift
dvoineu/LastFM
/LastFM/ViewControllers/ViewController.swift
UTF-8
4,480
2.6875
3
[ "MIT" ]
permissive
// // ViewController.swift // LastFM // // Created by Durga Prasad, Sidde (623-Extern) on 05/09/20. // Copyright © 2020 SDP. All rights reserved. // import UIKit class ViewController: UIViewController { //MARK:- Properties var viewModel: VCViewModel? { didSet { guard let viewModel = viewModel else { return } // Setup View Model setupViewModel(with: viewModel) } } @IBOutlet weak var albumsTableView: UITableView! private var searchController: UISearchController! private enum AlertType { case noAlbumDataAvailable } //MARK:- View lifecycle override func viewDidLoad() { super.viewDidLoad() //Configuring search controller configureSearchController() } //MARK:- Custom Methods private func setupViewModel(with viewModel: VCViewModel) { // Configure View Model viewModel.didFetchData = { [weak self] (searchData, error) in if let _ = error { // Notify User DispatchQueue.main.async { self?.presentAlert(of: .noAlbumDataAvailable) } } else if let searchData = searchData { debugPrint(searchData) //Updating table with search result DispatchQueue.main.async { self?.albumsTableView.reloadData() } } else { // Notify User DispatchQueue.main.async { self?.presentAlert(of: .noAlbumDataAvailable) } } } } private func presentAlert(of alertType: AlertType) { // Helpers let title: String let message: String switch alertType { case .noAlbumDataAvailable: title = "Unable to Fetch Data" message = "The application is unable to fetch ablum data. Please make sure your device is connected Internet" } // Initialize Alert Controller let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) // Add Cancel Action let cancelAction = UIAlertAction(title: "Got It", style: .cancel, handler: nil) alertController.addAction(cancelAction) // Present Alert Controller present(alertController, animated: true) } } extension ViewController: UISearchBarDelegate, UISearchResultsUpdating { private func configureSearchController() { // Initialize and perform a minimum configuration to the search controller. searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.obscuresBackgroundDuringPresentation = false searchController.searchBar.placeholder = "Search album <taylor>" searchController.searchBar.delegate = self searchController.searchBar.sizeToFit() // Placeing the search bar to the tableview headerview. albumsTableView.tableHeaderView = searchController.searchBar } //MARK:- UISearchResultsUpdating methods func updateSearchResults(for searchController: UISearchController) { guard let searchString = searchController.searchBar.text else { return } //Setting up min string length if searchString.count > 2 { self.viewModel?.searchAlbums(with: searchString) } } } //MARK:- UITableViewDataSource & UITableViewDelegate extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel?.numberOfAlbums ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //Creating Table Cell guard let cell = tableView.dequeueReusableCell(withIdentifier: AlbumTableViewCell.reuseIdentifier, for: indexPath) as? AlbumTableViewCell else { fatalError("Unable to DequeueTable View Cell") } guard let viewModel = viewModel else { fatalError("No View Model Present") } // Configure Cell cell.configure(with: viewModel.cellViewModel(for: indexPath.row)) return cell } }
true
77f148be4a03f382d71c491bc2f23defd26dfe69
Swift
BlakeRxxk/esoft-ios-tuition
/libraries/KeychainKit/Sources/Bridge/KeychainBridgeString.swift
UTF-8
671
2.765625
3
[ "MIT" ]
permissive
// // KeychainBridgeString.swift // KeychainKit // // Copyright © 2020 E-SOFT, OOO. All rights reserved. // import Foundation class KeychainBridgeString: KeychainBridge<String> { override public func set(_ value: String, forKey key: String, in keychain: Keychain) throws { guard let data = value.data(using: .utf8) else { throw KeychainError.conversionError } try persist(value: data, key: key, keychain: keychain) } override public func get(key: String, from keychain: Keychain) throws -> String? { guard let data = try find(key: key, keychain: keychain) else { return nil } return String(data: data, encoding: .utf8) } }
true
5f49a57d897c61d4ffc9628d14f0abc66189abe9
Swift
smarus/stepik-ios
/Stepic/Profile.swift
UTF-8
1,587
2.65625
3
[ "MIT" ]
permissive
// // Profile.swift // Stepic // // Created by Vladislav Kiryukhin on 24.07.2017. // Copyright © 2017 Alex Karpov. All rights reserved. // import Foundation import CoreData import SwiftyJSON class Profile: NSManagedObject, JSONSerializable { typealias IdType = Int convenience required init(json: JSON) { self.init() initialize(json) } func initialize(_ json: JSON) { id = json["id"].intValue firstName = json["first_name"].stringValue lastName = json["last_name"].stringValue subscribedForMail = json["subscribed_for_mail"].boolValue isStaff = json["is_staff"].boolValue shortBio = json["short_bio"].stringValue details = json["details"].stringValue } func update(json: JSON) { initialize(json) } var json: JSON { return [ "id": id as AnyObject, "first_name": firstName as AnyObject, "last_name": lastName as AnyObject, "subscribed_for_mail": subscribedForMail as AnyObject, "short_bio": shortBio as AnyObject, "details": details as AnyObject ] } static func fetchById(_ id: Int) -> [Profile]? { let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Profile") let predicate = NSPredicate(format: "managedId== %@", id as NSNumber) request.predicate = predicate do { let results = try CoreDataHelper.instance.context.fetch(request) return results as? [Profile] } catch { return nil } } }
true
f340005a8f63993f8769129e6ec6d3b5da673c27
Swift
fluidsonic/JetPack
/Sources/Measures/Temperature.swift
UTF-8
1,722
3.328125
3
[ "MIT" ]
permissive
public struct Temperature: Measure { public static let name = MeasuresStrings.Measure.temperature public static let rawUnit = TemperatureUnit.degreesCelsius public var rawValue: Double public init(_ value: Double, unit: TemperatureUnit) { precondition(!value.isNaN, "Value must not be NaN.") switch unit { case .degreesCelsius: rawValue = value case .degreesFahrenheit: rawValue = (5.0 / 9.0) * (value - 32.0) } } public init(degreesCelsius: Double) { self.init(degreesCelsius, unit: .degreesCelsius) } public init(degreesFahrenheit: Double) { self.init(degreesFahrenheit, unit: .degreesFahrenheit) } public init(rawValue: Double) { self.rawValue = rawValue } public var degreesCelsius: Double { return rawValue } public var degreesFahrenheit: Double { return (1.8 * degreesCelsius) + 32 } public func valueInUnit(_ unit: TemperatureUnit) -> Double { switch unit { case .degreesCelsius: return degreesCelsius case .degreesFahrenheit: return degreesFahrenheit } } } public enum TemperatureUnit: Unit { case degreesCelsius case degreesFahrenheit } extension TemperatureUnit { public var abbreviation: String { switch self { case .degreesCelsius: return MeasuresStrings.Unit.DegreeCelsius.abbreviation case .degreesFahrenheit: return MeasuresStrings.Unit.DegreeFahrenheit.abbreviation } } public var name: PluralizedString { switch self { case .degreesCelsius: return MeasuresStrings.Unit.DegreeCelsius.name case .degreesFahrenheit: return MeasuresStrings.Unit.DegreeFahrenheit.name } } public var symbol: String? { switch self { case .degreesCelsius: return nil case .degreesFahrenheit: return nil } } }
true
d59fb3c09720f862fc27ac96b6a93369f1f7e59a
Swift
mmusupp/TrycariOS
/TrycariOS/TrycariOS/Modules/Posts/ViewModel/PostsDetailViewModel.swift
UTF-8
929
2.75
3
[]
no_license
// // PostsDetailViewModel.swift // TrycariOS // // Created by Musthafa on 11/05/21. // import Foundation //import RealmSwift import RxSwift import RxCocoa protocol PostsDetailViewModelProtocol { var reloadTableView: (()->())? { get set } var post: PostDBModel? { get set } func fetchPostComments(post: PostDBModel) var items: Observable <[CommentsDBModel]>? { get set } func updateAsFavorite() } class PostsDetailViewModel: NSObject, PostsDetailViewModelProtocol { var post: PostDBModel? var reloadTableView: (() -> ())? var items: Observable<[CommentsDBModel]>? func fetchPostComments(post: PostDBModel) { self.post = post if let comments = CommentsDBModel.getAllComments(post) { items = Observable.just(comments) } self.reloadTableView?() } func updateAsFavorite() { self.post?.updateAsFavorite() } }
true
73ce55540f602f9a0dac3226971b0ac8ff04fda6
Swift
grd888/ScrollingMenu
/ScrollingMenu/Services/ImageDataLoaderService.swift
UTF-8
869
3
3
[]
no_license
// // ImageDataLoaderService.swift // ScrollingMenu // // Created by GD on 9/14/21. // import Foundation final class ImageDataLoaderService: ImageDataLoader { typealias Result = ImageDataLoader.Result func loadImageData(from url: URL, completion: @escaping (Result) -> Void) -> ImageDataLoaderTask { let task = URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { completion(.failure(error)) } else if let data = data { completion(.success(data)) } } task.resume() return URLDataLoaderTask(task) } } final class URLDataLoaderTask: ImageDataLoaderTask { var task: URLSessionDataTask init(_ task: URLSessionDataTask) { self.task = task } func cancel() { task.cancel() } }
true
27f1a0dc10f8fce70935d7cb118b42d2545a2f0a
Swift
FrancoMiguelli/metas-do-dia
/Metas_do_dia/AddTasksViewController.swift
UTF-8
558
2.625
3
[]
no_license
import UIKit class AddTasksViewController: UIViewController { @IBOutlet weak var tfAddTask: UITextField! @IBAction func btnAddTask(_ sender: Any) { if let addText = tfAddTask.text { let task = TasksUserDefaults() task.save(task: addText) tfAddTask.text = "" let data = task.toList() print (data) } } override func viewDidLoad() { super.viewDidLoad() } }
true
2b24e7fe6aa7ca11af1b9f219b16725f935b7222
Swift
q334530870/swift
/source/iOSGameDevCookbook2ndEd-master/sound/MultiplePlayers/MultiplePlayers/ViewController.swift
UTF-8
994
2.515625
3
[ "MIT" ]
permissive
// // ViewController.swift // MultiplePlayers // // Created by Jon Manning on 3/02/2015. // Copyright (c) 2015 Secret Lab. All rights reserved. // import UIKit class ViewController: UIViewController { @IBAction func playSound1(sender : AnyObject) { // BEGIN usage if let url = NSBundle.mainBundle().URLForResource("TestSound", withExtension: "wav") { let player = AVAudioPlayerPool.playerWithURL(url) player?.play() } // END usage } @IBAction func playSound2(sender : AnyObject) { if let url = NSBundle.mainBundle().URLForResource("ReceiveMessage", withExtension: "aif") { let player = AVAudioPlayerPool.playerWithURL(url) player?.play() } } @IBAction func playSound3(sender : AnyObject) { if let url = NSBundle.mainBundle().URLForResource("SendMessage", withExtension: "aif") { let player = AVAudioPlayerPool.playerWithURL(url) player?.play() } } }
true
195eea1fb99ab41b27098fd3d411ca33feba970d
Swift
cheskapac/lifted-view
/LiftedView/Scenes/Biometry/BiometryViewModel.swift
UTF-8
1,368
2.5625
3
[]
no_license
import Combine extension BiometryViewModel { enum VMEvent { case appear case login } } class BiometryViewModel: ObservableObject { private let evaluateBiometricsInteractor: EvaluateBiometricsInteracting private var cancelBag = Set<AnyCancellable>() private var username: String = "" private var code: String = "" init(evaluateBiometricsInteractor: EvaluateBiometricsInteracting = EvaluateBiometricsInteractor()) { self.evaluateBiometricsInteractor = evaluateBiometricsInteractor } func send(event: VMEvent) { switch event { case .appear: handleAppearEvent(event) case .login: handleLoginEvent(event) } } private func handleAppearEvent(_ event: VMEvent) { guard case .appear = event else { return } evaluateBiometricsInteractor.request(reason: "Login to app") .sink(receiveValue: { (success) in guard success else { return } AppRootViewModel.shared.rootContent = .dashboard }) .store(in: &cancelBag) } private func handleLoginEvent(_ event: VMEvent) { guard case .login = event else { return } AppRootViewModel.shared.rootContent = .login } }
true
b497c0066fe7ff388091f1b0ae6d369ca5a5ef89
Swift
GlennAustin/NetNewsWire
/iOS/Settings/FeedbinAccountViewController.swift
UTF-8
2,927
2.5625
3
[ "MIT" ]
permissive
// // AddFeedbinAccountViewController.swift // NetNewsWire-iOS // // Created by Maurice Parker on 5/19/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import UIKit import Account import RSWeb class FeedbinAccountViewController: UIViewController { @IBOutlet weak var cancelBarButtonItem: UIBarButtonItem! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var doneBarButtonItem: UIBarButtonItem! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var errorMessageLabel: UILabel! weak var account: Account? weak var delegate: AddAccountDismissDelegate? override func viewDidLoad() { super.viewDidLoad() activityIndicator.isHidden = true if let account = account, let credentials = try? account.retrieveBasicCredentials() { if case .basic(let username, let password) = credentials { emailTextField.text = username passwordTextField.text = password } } } @IBAction func cancel(_ sender: Any) { dismiss(animated: true) } @IBAction func done(_ sender: Any) { self.errorMessageLabel.text = nil guard emailTextField.text != nil && passwordTextField.text != nil else { self.errorMessageLabel.text = NSLocalizedString("Username & password required.", comment: "Credentials Error") return } cancelBarButtonItem.isEnabled = false doneBarButtonItem.isEnabled = false activityIndicator.isHidden = false activityIndicator.startAnimating() let credentials = Credentials.basic(username: emailTextField.text ?? "", password: passwordTextField.text ?? "") Account.validateCredentials(type: .feedbin, credentials: credentials) { [weak self] result in guard let self = self else { return } self.cancelBarButtonItem.isEnabled = true self.doneBarButtonItem.isEnabled = true self.activityIndicator.isHidden = true self.activityIndicator.stopAnimating() switch result { case .success(let authenticated): if authenticated { var newAccount = false if self.account == nil { self.account = AccountManager.shared.createAccount(type: .feedbin) newAccount = true } do { try self.account?.removeBasicCredentials() try self.account?.storeCredentials(credentials) if newAccount { self.account?.refreshAll() } self.dismiss(animated: true) self.delegate?.dismiss() } catch { self.errorMessageLabel.text = NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error") } } else { self.errorMessageLabel.text = NSLocalizedString("Invalid email/password combination.", comment: "Credentials Error") } case .failure: self.errorMessageLabel.text = NSLocalizedString("Network error. Try again later.", comment: "Credentials Error") } } } }
true
f5c59c629d2841f6a15c178963cf2ab801231aa2
Swift
TuyenTranTrung93/url-shortener
/Tuyen_URL_ShortenerTests/Extensions/DictionaryExtensionsTest.swift
UTF-8
999
2.84375
3
[]
no_license
// // DictionaryExtensionsTest.swift // Tuyen_URL_ShortenerTests // // Created by Tuyen Tran on 1/12/21. // import XCTest @testable import Tuyen_URL_Shortener class DictionaryExtensionTest: XCTestCase { func test_toGetMethodParameters() { let testDictionary = [ "url": "http://www.google.com" ] let value = testDictionary.toGetMethodParameters() XCTAssertEqual(value, "url=http://www.google.com") } func test_toGetMethodParameters_space() { let testDictionary = [ "url": "http://www.google. com" ] let value = testDictionary.toGetMethodParameters() XCTAssertEqual(value, "url=http://www.google.%20com") } func test_toGetMethodParameters_specialCharacter() { let testDictionary = [ "url": "http://www.google.*com" ] let value = testDictionary.toGetMethodParameters() XCTAssertEqual(value, "url=http://www.google.*com") } }
true
dd74fd6d0c7ddf8a2fda8e2165137e9af9061578
Swift
aristeidys/Note-Tracker
/NoteTracker/Store/noteStore/NoteWorker.swift
UTF-8
652
2.859375
3
[ "MIT" ]
permissive
import UIKit import RealmSwift protocol NoteRepositoryLogic { func createNote(_ note: NoteModel) func getAll() -> Results<NoteModel>? } class NoteWorker: AbstractRepository, NoteRepositoryLogic { func createNote(_ note: NoteModel) { note.editedDate = Date() save(entity: note) print("💾 Title: \(note.title) text: \(note.text)") } func deleteNote(_ note: NoteModel?) { delete(entity: note) } func deleteNotes(_ notes: [NoteModel]?) { delete(entities: notes) } func getAll() -> Results<NoteModel>? { return realm.objects(NoteModel.self) } }
true
031a16c4a695f34f448fc6adce078bb1b98959b5
Swift
Sushobhitbuiltbyblank/CurrencyCalulator
/CurrencyConvertor/AppModule/CurrencyExchangeModule/view/CustomDropDrownView.swift
UTF-8
3,605
2.546875
3
[]
no_license
// // CustomDropDrownView.swift // CurrencyConvertor // // Created by Sushobhit.Jain on 24/12/20. // import Foundation import UIKit class CustomDropDrownView: UIView { private let tableView = UITableView() private var dataSource: [CurrencyModel]? private var selectedButton:UIButton? private var providedFrame:CGRect? private unowned var viewController:UIViewController? var completion:(_ value:String)-> Void = {_ in } override init(frame: CGRect) { super.init(frame: frame) // set a dropdown to select country from list tableView.delegate = self tableView.dataSource = self tableView.register(DropDownCell.self, forCellReuseIdentifier: DropDownCell.identifier) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addTransparentView(frame: CGRect, presentOn viewController:UIViewController,with dataSource:[CurrencyModel]?,button:UIButton) { self.providedFrame = frame self.dataSource = dataSource self.selectedButton = button self.viewController = viewController let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first self.frame = window?.frame ?? viewController.view.frame viewController.view.addSubview(self) tableView.frame = CGRect(x: frame.origin.x, y: frame.origin.y + frame.height, width: frame.width, height: 0) viewController.view.addSubview(tableView) tableView.layer.cornerRadius = 5 self.backgroundColor = UIColor.black.withAlphaComponent(0.9) tableView.reloadData() self.alpha = 0 UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: { self.alpha = 0.5 let height = ((dataSource?.count ?? 1) < 5) ? dataSource?.count ?? 1 : 5 self.tableView.frame = CGRect(x: frame.origin.x, y: frame.origin.y + frame.height + 5, width: frame.width, height: CGFloat(height * 50)) }, completion: nil) } func removeTransparentView() { let frame = self.providedFrame ?? CGRect.zero UIView.animate(withDuration: 0.4, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: { self.alpha = 0 self.tableView.frame = CGRect(x: frame.origin.x, y: frame.origin.y + frame.height, width: frame.width, height: 0) }, completion: nil) } } extension CustomDropDrownView : UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSource?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: DropDownCell.identifier, for: indexPath) cell.textLabel?.text = self.dataSource?[indexPath.row].name ?? "" return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } } extension CustomDropDrownView : UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedCountryModelName = self.dataSource?[indexPath.row].name ?? "" selectedButton?.setTitle(selectedCountryModelName, for: .normal) self.completion(selectedCountryModelName) self.removeTransparentView() } }
true
96990bcb66b7b1babe8e5bc5e191d605a192aae6
Swift
sojideveloper/FlickrImageViewer
/FlickrImageViewer/ImageViewerViewController.swift
UTF-8
1,405
2.625
3
[]
no_license
// // ImageViewerViewController.swift // FlickrImageViewer // // Created by iwritecode on 4/17/17. // Copyright © 2017 iwritecode. All rights reserved. // import UIKit // MARK: - ImageViewerViewController class ImageViewerViewController: UIViewController { @IBOutlet weak var recentPhotosButton: UIButton! @IBOutlet weak var searchPhotosButton: UIButton! @IBOutlet weak var showImageButton: UIButton! @IBOutlet weak var keywordField: UITextField! var selectedMethod: FlickrMethod? // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() } // MARK: Layout override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateLayout() } // Custom UI function(s) func updateLayout() { showImageButton.layer.cornerRadius = showImageButton.bounds.height / 2.0 } // MARK: IBActions @IBAction func methodButtonPressed(_ sender: UIButton) { switch sender.tag { case 0: selectedMethod = .GetRecentPhotos case 1: selectedMethod = .GetPhotos default: break } } @IBAction func showImageButtonPressed(_ sender: UIButton) { print("Show imaeg button pressed") } }
true
8be7fd1b7e81cdebd11023f219f12eaa7658acdb
Swift
Mehhhhhhhh/ElementarySorts
/AShellSort.swift
UTF-8
494
3.046875
3
[]
no_license
// // AShellSort.swift // ElementarySorts // // Created by Alex Blanchard on 3/27/17. // Copyright © 2017 ForeCyte. All rights reserved. // import Foundation func aShellSort(a: [Int], h: Int = 1) -> [Int] { var a = a for i in stride(from: h, to: a.count, by: 1) { for j in stride(from: i - h, to: 0, by: -h) { if a[j] < a[j - 1] { let tmpMinus = a[j-1] let tmpJ = a[j] a[j] = tmpMinus a[j-1] = tmpJ } else { break } } } return a }
true
fc110db0bc17d6f6e73a71919fcceae27d0a1232
Swift
Mishania13/Scroll-View-project-presentation.
/UI Programmaticly/ViewController.swift
UTF-8
1,170
2.953125
3
[]
no_license
// // ViewController.swift // UI Programmaticly // // Created by Mr. Bear on 11.05.2020. // Copyright © 2020 Mr. Bear. All rights reserved. // import UIKit class ViewController: UIViewController { let container: UIStackView = { let view = UIStackView() view.tintColor = #colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1) return view }() let button: UIButton = { let view = UIButton(type: .system) view.backgroundColor = .blue view.setTitle("sasa", for: .normal) view.addTarget(self, action: #selector(tapping), for: .touchUpInside) return view }() override func viewDidLoad() { view.backgroundColor = .red view.addSubview(container) container.addSubview(button) container.addSubview(button) container.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height/2) button.frame = CGRect(x: container.center.x, y: container.center.y, width: 100, height: 50) } @objc func tapping() { print("Tap tap tap") } }
true
28e9285e073a07aa6b175ab2b9953543a0bc6cbd
Swift
devahmedshendy/Photorama_UIKit
/Photorama_UIKit/View Controller/PhotosViewController.swift
UTF-8
2,801
2.921875
3
[]
no_license
// // ViewController.swift // Photorama // // Created by  Ahmed Shendy on 7/28/21. // import UIKit class PhotosViewController: UIViewController { //MARK: - Outlets @IBOutlet weak private var collectionView: UICollectionView! //MARK: - Properties var store: PhotoStore! var photoDataSource: PhotoDataSource! //MARK: - Lifecycles override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = photoDataSource collectionView.delegate = self fetchInterestingPhotos() } //MARK: - Methods func fetchInterestingPhotos() { store.fetchInterestingPhotos(completion: handleFetchPhotoCompletion(result:)) } func fetchRecentPhotos() { store.fetchRecentPhotos(completion: handleFetchPhotoCompletion(result:)) } private func handleFetchPhotoCompletion(result: Result<[Photo], Error>) { switch result { case let .success(photos): self.photoDataSource.photos = photos case let .failure(error): print("Error fetching interesting photos: \(error)") self.photoDataSource.photos.removeAll() } collectionView.reloadSections(IndexSet(integer: 0)) } //MARK: - Segue Methods override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier { case "showPhotoSegue": if let selectedIndexPath = self.collectionView.indexPathsForSelectedItems?.first { let photo = photoDataSource.photos[selectedIndexPath.row] let destinationVC = segue.destination as! PhotoInfoViewController destinationVC.store = store destinationVC.photo = photo } default: preconditionFailure("Unexpected segue identifier.") } } } //MARK: - Collection View Delegate extension PhotosViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let photo = photoDataSource.photos[indexPath.row] store.fetchImage(for: photo) { (result) in guard let photoIndex = self.photoDataSource.photos.firstIndex(of: photo), case let .success(image) = result else { return } let photoIndexPath = IndexPath(item: photoIndex, section: 0) if let cell = self.collectionView.cellForItem(at: photoIndexPath) as? PhotoCollectionViewCell { cell.update(displaying: image) } } } }
true
3036f4c283ffd5e8254007fabc9eeaf6bb17f22f
Swift
BironSu/Pursuit-Core-iOS-Unit3-Assignment1
/PeopleAndAppleStockPrices/PeopleAndAppleStockPrices/Controller/StockDetailController.swift
UTF-8
1,136
2.75
3
[ "MIT" ]
permissive
// // StockDetailViewController.swift // PeopleAndAppleStockPrices // // Created by Biron Su on 12/7/18. // Copyright © 2018 Pursuit. All rights reserved. // import UIKit class StockDetailController: UIViewController { var stockInfo: AppleStockInfo? @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var openLabel: UILabel! @IBOutlet weak var closeLabel: UILabel! @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() setUp() } private func setUp() { guard let stockInfo = stockInfo else {fatalError("stockInfo is nil")} dateLabel.text = stockInfo.date openLabel.text = "Open: $\(String(format: "%.2f", stockInfo.open))" closeLabel.text = "Close: $\(String(format: "%.2f", stockInfo.close))" if stockInfo.open < stockInfo.close { imageView.image = UIImage(named: "thumbsUp") view.backgroundColor = .green } else if stockInfo.open > stockInfo.close { imageView.image = UIImage(named: "thumbsDown") view.backgroundColor = .red } } }
true
425f97d74cb9a268ce35af867b2d792ad0383ea8
Swift
AtifCh/GithubSearchUser
/GithubSearchUser/Controllers/DetailViewController.swift
UTF-8
2,678
2.8125
3
[]
no_license
// // DetailViewController.swift // GithubSearchUser // // Created by Kaleem on 7/31/18. // Copyright © 2018 Kaleem. All rights reserved. // import UIKit //Custom Cell Class class UserTableViewCell: UITableViewCell { @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var userNameLabel: UILabel! } class DetailViewController: UIViewController { //Array of type GithubItems get from SearchViewController var githubItems:[GithubItem]? @IBOutlet var detailTableView : UITableView! override func viewDidLoad() { super.viewDidLoad() navigationItem.backBarButtonItem?.title = "Back" navigationItem.title = "Detail" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension DetailViewController : UITableViewDelegate , UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.githubItems?.count)! } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let imgUrl : String! imgUrl = self.githubItems![indexPath.row].avatarUrl _ = (cell as! UserTableViewCell).userImageView.downloadImageFrom(link: imgUrl, contentMode: UIViewContentMode.scaleAspectFill) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserTableViewCell let item = self.githubItems![indexPath.row] cell.userNameLabel.text = item.login return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let item = self.githubItems![indexPath.row] let followersVC = self.storyboard?.instantiateViewController(withIdentifier: "FollowersViewController") as! FollowersViewController followersVC.username = item.login self.navigationController?.pushViewController(followersVC, animated: true) } }
true
c08b07a4a1d8cb777c5af57ff6efd6e8a88e9b50
Swift
tmacka/Checklists
/Checklists/CheckListViewController.swift
UTF-8
4,118
2.875
3
[]
no_license
// // ViewController.swift // Checklists // // Created by Tom MacKay on 12/08/2019. // Copyright © 2019 Tom MacKay. All rights reserved. // import UIKit class CheckListViewController: UITableViewController, AddItemViewControllerDelegate { func addItemViewControllerDidCancel(_ controller: ItemDetailViewController) { navigationController?.popViewController(animated: true) } func addItemViewController(_ controller: ItemDetailViewController, didFinishAdding item: CheckListItem) { let newRowIndex = items.count items.append(item) let indexPath = IndexPath(row: newRowIndex, section: 0) let indexPaths = [indexPath] tableView.insertRows(at: indexPaths, with: .automatic) navigationController?.popViewController(animated: true) } func addItemViewController(_ controller: ItemDetailViewController, didFinishEditing item: CheckListItem) { if let index = items.index(of: item) { let indexPath = IndexPath(row: index, section: 0) if let cell = tableView.cellForRow(at: indexPath) { configureText(for: cell, with: item) } } navigationController?.popViewController(animated: true) } var items = [CheckListItem]() override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.prefersLargeTitles = true let item0 = CheckListItem() item0.text = "test1" item0.checked = true items.append(item0) let item1 = CheckListItem() item1.text = "test2" item1.checked = true items.append(item0) // Do any additional setup after loading the view. } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Checklistitem", for: indexPath) let item = items[indexPath.row] configureText(for: cell, with: item) configureCheckMark(for: cell, with: item) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) { let item = items[indexPath.row] item.toggleChecked() configureCheckMark(for: cell, with: item) } tableView.deselectRow(at: indexPath, animated: true) } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { items.remove(at: indexPath.row) let indexPaths = [indexPath] tableView.deleteRows(at: indexPaths, with: .automatic) } func configureCheckMark(for cell:UITableViewCell, with item: CheckListItem) { //var isChecked = false let label = cell.viewWithTag(1001) as! UILabel if item.checked { label.text = "√" } else { label.text = "" } } func configureText(for cell: UITableViewCell, with item: CheckListItem) { let label = cell.viewWithTag(1000) as! UILabel label.text = item.text } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "AddItem" { let controller = segue.destination as! ItemDetailViewController controller.delegate = self } else if segue.identifier == "EditItem" { let controller = segue.destination as! ItemDetailViewController controller.delegate = self if let indexPath = tableView.indexPath(for: sender as! UITableViewCell) { controller.itemToEdit = items[indexPath.row] } } } }
true
639b7eb3cfca34da41200efa716444f8f59d9d8c
Swift
fabfelici/MVVMDemo
/MVVMDemo/CounterViewModel.swift
UTF-8
718
2.78125
3
[]
no_license
import Foundation import RxCocoa final class CounterViewModel { struct Input { let increment: Driver<Void> let decrement: Driver<Void> } struct Output { let counter: Driver<String> } func transform(input: Input) -> Output { let initialState = CounterState() let counter = Driver.of( input.increment.map { CounterStateAction.increment }, input.decrement.map { CounterStateAction.decrement } ) .merge() .scan(initialState, accumulator: CounterState.reduce) .startWith(initialState) .map { String($0.counter) } return .init(counter: counter) } }
true
23e9b7db358caeee780132fc3edccb6e691acaa4
Swift
Mihir22/My-Day
/My Day/Controllers/MyDayListViewController.swift
UTF-8
4,550
2.9375
3
[]
no_license
// // ViewController.swift // My Day // // Created by Mihir Mesia on 03/11/18. // Copyright © 2018 Mihir Mesia. All rights reserved. // import UIKit import RealmSwift class MyDayListViewController: UITableViewController{ var MyDayItems : Results<Item>? let realm = try! Realm() var selectedCategory : Category?{ //didSet is a special keyword and between it gets triggerd as soon as selectedC sets a value didSet{ loadItems() } } override func viewDidLoad() { super.viewDidLoad() //loadItems() print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)) // Do any additional setup after loading the view, typically from a nib. // loadItems() } //MARK-TableViewDataSource Methods override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return MyDayItems?.count ?? 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MyDayItemCell", for: indexPath) if let item = MyDayItems?[indexPath.row]{ cell.textLabel?.text = item.title cell.accessoryType = item.done ? .checkmark : .none } else{ cell.textLabel?.text = "No Items Added" } return cell } //MARK - TableViewDelegate methods override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let item = MyDayItems?[indexPath.row]{ do{ try realm.write { item.done = !item.done } } catch{ print("Error saving done status\(error)") } } tableView.reloadData() tableView.deselectRow(at: indexPath, animated: true) } //MARK - Add New Items @IBAction func addButtonPressed(_ sender: UIBarButtonItem) { var textField = UITextField() let alert = UIAlertController(title: "Add New Item to MyDay", message: "", preferredStyle: .alert) let action = UIAlertAction(title: "Add Item", style: .default) { (action) in //used for adding new items and saving the items in current category if let currentCategory = self.selectedCategory{ do{ try self.realm.write { let newItem = Item() newItem.title = textField.text! newItem.dateCreated = Date() currentCategory.items.append(newItem) } } catch { print("Error saving new items\(error)") } } self.tableView.reloadData() } alert.addTextField { (alertTextField) in alertTextField.placeholder = "Create New Item" textField = alertTextField } alert.addAction(action) present(alert, animated: true, completion: nil) } //MARK Model Manipulation Method //with is external and request is internal parameter //nil used with NSPredicate to make load items usable without predicate func loadItems() { // let request: NSFetchRequest<Item> = Item.fetchRequest() MyDayItems = selectedCategory?.items.sorted(byKeyPath: "title", ascending: true) } } //MARK:- Search Bar Methods //Instead of using it in main class we created it here to make code much easy to handle and easy to understand. extension MyDayListViewController : UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar){ MyDayItems = MyDayItems?.filter("title CONTAINS[cd] %@", searchBar.text!).sorted(byKeyPath: "dateCreated", ascending: true) tableView.reloadData() } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchBar.text?.count == 0{ loadItems() //Takes back to main screen when we remove our search data //Dispatch makes that process to run in foreground so we get rid of keyb and cursor at main screen DispatchQueue.main.async { searchBar.resignFirstResponder() } } } }
true
f1816fa19fc90c23ca953ab5f4816a784c1c8d55
Swift
Joseph-Manas/WeatherApp
/WeatherApp/NetworkService.swift
UTF-8
2,092
3.4375
3
[]
no_license
// // NetworkService.swift // WeatherApp // // Created by Manas Aggarwal on 26/08/20. // Copyright © 2020 Joseph&Manas. All rights reserved. // import Foundation // **app-id** => 17f04e035b5c9326b10bb1c4c1dc9eda // API format - https://api.openweathermap.org/data/2.5/weather?q=<insert location name>&appid=<insert app-id> public class NetworkService { private let appID: String = "17f04e035b5c9326b10bb1c4c1dc9eda" private let baseURL: String = "https://api.openweathermap.org/data/2.5/weather" // Intialize as a singleton public static var shared: NetworkService = NetworkService() // -------------------------- // MARK:- Methods // -------------------------- /// Returns the weather information for the supplied location. /// - Parameters: /// - location: Name of the location for getting the weather report. /// - completion: Completion block for returning the fetched data. func getWeatherInfo(for location: String, _ completion: @escaping (WeatherResult) -> Void) { // Create params for the network call let params = "?q=\(location)&appid=\(appID)" // Create URL guard let url = URL(string: baseURL + params) else { print("ERROR!!::-> Invalid URL") return } // Network Call URLSession.shared.dataTask(with: url) { data, response, error in // Handle error if not nil if let error = error { print("ERROR!!::-> \(error.localizedDescription)") } // Handle result of network call if let data = data { do { let json = try JSONDecoder().decode(WeatherResult.self, from: data) // Create and return an object of WeatherResult completion(WeatherResult(id: json.id, name: json.name, weather: json.weather, main: json.main, wind: json.wind)) } catch { print("ERROR!!::-> Failed json serialization") } } }.resume() } }
true
72759afd8261ea033ab35925be1d6354125ce6b1
Swift
ggndpsingh-old/FlickrSpike
/FlickrSpike/MenuCell.swift
UTF-8
1,886
2.609375
3
[]
no_license
// // MenuCell.swift // FlickrImage // // Created by Gagandeep Singh on 11/7/16. // Copyright © 2016 Gagandeep Singh. All rights reserved. // import UIKit class MenuCell: BaseCollectionCell { //---------------------------------------------------------------------------------------- //MARK: //MARK: UI Elements //---------------------------------------------------------------------------------------- let imageView: UIImageView = { let iv = UIImageView() iv.translatesAutoresizingMaskIntoConstraints = false iv.image = Images.FeedIcon?.withRenderingMode(.alwaysTemplate) iv.tintColor = UIColor.lightGray() return iv }() //---------------------------------------------------------------------------------------- //MARK: //MARK: Behavior //---------------------------------------------------------------------------------------- override var isHighlighted: Bool { didSet { imageView.tintColor = isHighlighted ? .menuBarTint() : .lightGray() } } override var isSelected: Bool { didSet { imageView.tintColor = isSelected ? .menuBarTint() : .lightGray() } } //---------------------------------------------------------------------------------------- //MARK: //MARK: Setup Views //---------------------------------------------------------------------------------------- override func setupViews() { super.setupViews() addSubview(imageView) imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true imageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true imageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true } }
true
3d1b6a4a3cd5da09cd2f54aac56c827a5c11447b
Swift
SMR/programmableweb-vapor-mongo
/Sources/App/Models/Store.swift
UTF-8
1,118
2.953125
3
[ "MIT" ]
permissive
import Vapor import Fluent import Foundation final class Store: Model { var id: Node? // (1) var address: String var name: String // used by fluent internally var exists: Bool = false init(name: String, address:String){ self.id = nil self.name = name self.address = address } init(node: Node, in context: Context) throws { //(2) id = try node.extract("id") name = try node.extract("name") address = try node.extract("address") } func makeNode(context: Context) throws -> Node { //(3) return try Node(node: [ "id": id, "name": name, "address": address ]) } } extension Store: Preparation { // (4) static func prepare(_ database: Database) throws { // try database.create("stores") { stores in // stores.id() // stores.string("name") // stores.string("address") // } } static func revert(_ database: Database) throws { //(5) //try database.delete("stores") } }
true
89e09a3b7dfd236c1bec7e2e0b41709667d4a420
Swift
pitt500/Remainders
/Remainders/Remainders/NavigationManager.swift
UTF-8
1,085
2.546875
3
[]
no_license
// // NavigationManager.swift // Remainders // // Created by projas on 4/5/16. // Copyright © 2016 projas. All rights reserved. // import UIKit import RealmSwift class NavigationManager: NSObject { private static func goToStoryboard(storyboardName: String, viewControllerId: String) -> Void{ let app = UIApplication.sharedApplication().delegate! let storyboard: UIStoryboard = UIStoryboard(name: storyboardName, bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier(viewControllerId) app.window?!.rootViewController = vc UIView.transitionWithView(app.window!!, duration: 0.5, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { app.window?!.rootViewController = vc }, completion: nil) } static func goLogin() -> Void{ NavigationManager.goToStoryboard("Welcome", viewControllerId: "LoginViewController") } static func goMain(){ NavigationManager.goToStoryboard("Main", viewControllerId: "MainController") } }
true
71ea5990f53c1fd39e351722d4d7268dd2fa8983
Swift
MelvinTo/footprint
/Footprint/SecondViewController.swift
UTF-8
1,611
2.65625
3
[]
no_license
// // SecondViewController.swift // Footprint // // Created by Melvin Tu on 4/3/15. // Copyright (c) 2015 Melvin Tu. All rights reserved. // import UIKit class SecondViewController: UIViewController, PhotoLoaderDelegate { @IBOutlet weak var button: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func scanPhotos(sender: UIButton) { NSLog("scanning photos") button.setTitle("Scanning", forState: UIControlState.Normal) let qualityOfServiceClass = QOS_CLASS_BACKGROUND let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0) dispatch_async(backgroundQueue, { println("This is run on the background queue") var loader : PhotoLoader = PhotoLoader() loader.delegate = self loader.loadPhotos() }) } @IBAction func countPhotos(sender: UIButton) { var store = PhotoStore() NSLog("Photo count: \(store.countPhotos())") NSLog("Path count: \(store.countPaths())") } @IBAction func resetPhotos(sender: UIButton) { var store = PhotoStore() store.resetPhotos() } func loadPhotoComplete(loader: PhotoLoader) { button.setTitle("Complete", forState: UIControlState.Normal) NSLog("Scanning is complete") } }
true
c9668964859f0fbb42d3ecc62e439a559930da69
Swift
Evi1B/testTAsk
/test/Game/GameScene.swift
UTF-8
4,496
2.734375
3
[]
no_license
// // GameScene.swift // test // // Created by evilb on 02.10.2021. // import SpriteKit class GameScene: SKScene { let appDelegate = UIApplication.shared.delegate as! AppDelegate var bg = SKSpriteNode(imageNamed: "bgImage") var circle = SKSpriteNode(imageNamed: "circle_blue") var startButton = SKSpriteNode(imageNamed: "pressStart") var velocity = CGPoint.zero let playableRect: CGRect var score = 0 var timerLabel = SKLabelNode(fontNamed: "ArialMT") var timerValue: Int = 0 { didSet { timerLabel.text = "Time: \(timerValue)" } } override init(size: CGSize) { let maxAspectRatio:CGFloat = 9.0 / 15.0 let playableHeight = size.width / maxAspectRatio let playableMargin = (size.height-playableHeight) / 2.0 playableRect = CGRect(x: 0, y: playableMargin, width: size.width, height: playableHeight) super.init(size: size) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMove(to view: SKView) { super.didMove(to: view) startButton.position = CGPoint(x: size.width / 2 , y: size.height / 2) startButton.zPosition = 20 startButton.name = "startGame" bg.position = CGPoint(x: size.width / 2 , y: size.height / 2) bg.zPosition = -1 self.addChild(bg) self.addChild(startButton) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let location = touch.location(in: self) let touchesNode = self.nodes(at: location) for node in touchesNode { if node.name == "circle" { score += 1 randomCirclePosition() gameOver() print(score) } if node.name == "startGame" { startButton.isHidden = true circle.size.height = 64 circle.size.width = 64 circle.position = randomCirclePosition() circle.name = "circle" self.addChild(circle) timerLabel.fontColor = SKColor.white timerLabel.fontSize = 40 timerLabel.position = CGPoint(x: size.width/2, y: size.height/2 + 600) self.addChild(timerLabel) run(SKAction.repeatForever(SKAction.sequence([ SKAction.run { self.timerValue += 1 } , SKAction.wait(forDuration: 1) ]))) } } } } override func update(_ currentTime: TimeInterval) { boundsCheckCircle() } func gameOver() { if score == 10 { if timerValue <= 7 { appDelegate.isWin = true NotificationCenter.default.post(name: kWinNotification, object: nil) print("You WIN!!!🥳") } else { appDelegate.isWin = false NotificationCenter.default.post(name: kWinNotification, object: nil) print("You LOSE!!!📛") } } } func randomCirclePosition() -> CGPoint { circle.position = CGPoint( x: CGFloat.random( min: playableRect.minX, max: playableRect.maxX), y: CGFloat.random( min: playableRect.minY, max: playableRect.maxY)) return circle.position } func boundsCheckCircle() { let bottomLeft = CGPoint(x: 0, y: playableRect.minY) let topRight = CGPoint(x: size.width, y: playableRect.maxY) if circle.position.x <= bottomLeft.x { circle.position.x = bottomLeft.x velocity.x = -velocity.x } if circle.position.x >= topRight.x { circle.position.x = topRight.x velocity.x = -velocity.x } if circle.position.y <= bottomLeft.y { circle.position.y = bottomLeft.y velocity.y = -velocity.y } if circle.position.y >= topRight.y { circle.position.y = topRight.y velocity.y = -velocity.y } } }
true
8dbccc3d98b289c3d6cf1b62f2589ecbe78a02a6
Swift
julamot/ec008-swift-kickstart-2
/source/iPad/StartSwiftKickstart.playgroundbook/Contents/Chapters/Chapter7.playgroundchapter/Pages/Page10.playgroundpage/Contents.swift
UTF-8
546
3.421875
3
[]
no_license
class Attendee { let name: String init(name: String) { self.name = name } func nameBadge() -> String { "Hi, I'm \(name)." } } extension Attendee: CustomStringConvertible { var description: String { nameBadge() } } class TutorialAttendee: Attendee { let tutorial: String init(name: String, tutorial: String) { self.tutorial = tutorial super.init(name: name) } override func nameBadge() -> String { super.nameBadge() + " I'm taking \(tutorial)." } }
true
cf4bc6e1d3d865df5714af264dcff60a187545c1
Swift
Ognjenm90/FitApp
/BagService.swift
UTF-8
3,124
2.84375
3
[]
no_license
// // BagService.swift // FitApp // // Created by Ognjen Milovanovic on 11.05.19. // Copyright © 2019 Ognjen Milivanovic. All rights reserved. // import Foundation class BagService { static let notificationBagChanged = Notification.Name("NotificationBagChanged") typealias Bag = (mealID: Int, platesIDs: [Int]) typealias BagValue = (mealID: Int, plateID: Int) private let bagKey = "BagKey" private let separator = "|" func get(for meal: Meal) -> Bag? { guard let bagValues = UserDefaults.standard.value(forKey: bagKey) as? [String], !bagValues.isEmpty else { return nil } let platesIDs: [Int] = bagValues.compactMap { string -> Int? in guard let bagValue = generateBagValue(from: string), bagValue.mealID == meal.id else { return nil } return bagValue.plateID } return (meal.id, platesIDs) } func add(_ plate: Plate, for meal: Meal) { let bagValue = generateString(from: (meal.id, plate.id)) if var bag = UserDefaults.standard.value(forKey: bagKey) as? [String] { bag.append(bagValue) UserDefaults.standard.setValue(bag, forKey: bagKey) } else { UserDefaults.standard.setValue([bagValue], forKey: bagKey) } postNotification(bag: get(for: meal)) } func remove(_ plate: Plate, for meal: Meal) { let bagValue = generateString(from: (meal.id, plate.id)) guard var bag = UserDefaults.standard.value(forKey: bagKey) as? [String], let index = bag.firstIndex(of: bagValue) else { return } bag.remove(at: index) UserDefaults.standard.setValue(bag, forKey: bagKey) postNotification(bag: get(for: meal)) } func removeAll(for meal: Meal) { guard var strings = UserDefaults.standard.value(forKey: bagKey) as? [String] else { return } strings.removeAll { string -> Bool in if let value = generateBagValue(from: string), value.mealID == meal.id { return true } return false } UserDefaults.standard.setValue(strings, forKey: bagKey) postNotification(bag: get(for: meal)) } // MARK: Notificationen private func postNotification(bag: Bag? = nil) { NotificationCenter.default.post(name: BagService.notificationBagChanged, object: bag) } // MARK: Private hilfe für String private func generateString(from bagValue: BagValue) -> String { return "\(bagValue.mealID)\(separator)\(bagValue.plateID)" } private func generateBagValue(from string: String) -> BagValue? { let components = string.components(separatedBy: separator) guard components.count > 1, let mealID = Int(components[0]), let plateID = Int(components[1]) else { return nil } return (mealID, plateID) } }
true
7f269a1084f1dae90468c899243ec9f6ae984335
Swift
ringcentral-tutorials/calllog-analytics-swift-demo
/Carthage/Checkouts/ringcentral-swift/Source/Paths/TokenPath.swift
UTF-8
4,051
2.6875
3
[ "MIT" ]
permissive
import Foundation import ObjectMapper import Alamofire open class TokenPath: PathSegment { public override var pathSegment: String { get{ return "token" } } // OAuth2 Get Token open func post(callback: @escaping (_ t: TokenInfo?, _ error: HTTPError?) -> Void) { rc.post(self.endpoint()) { (t: TokenInfo?, error) in callback(t, error) } } // OAuth2 Get Token open func post(parameters: Parameters, callback: @escaping (_ t: TokenInfo?, _ error: HTTPError?) -> Void) { rc.post(self.endpoint(), parameters: parameters) { (t: TokenInfo?, error) in callback(t, error) } } // OAuth2 Get Token open func post(parameters: PostParameters, callback: @escaping (_ t: TokenInfo?, _ error: HTTPError?) -> Void) { post(parameters: parameters.toParameters(), callback: callback) } open class PostParameters: Mappable { // Must hold password value for Resource Owner Credentials flow. If client application is not authorized by the specified grant_type, response does not contain refresh_token and refresh_token_ttl attributes open var `grant_type`: String? // Optional. Access token lifetime in seconds; the possible values are from 600 sec (10 min) to 3600 sec (1 hour). The default value is 3600 sec. If the value specified exceeds the default one, the default value is set. If the value specified is less than 600 seconds, the minimum value (600 sec) is set open var `access_token_ttl`: Int? // Optional. Refresh token lifetime in seconds. The default value depends on the client application, but as usual it equals to 7 days. If the value specified exceeds the default one, the default value is applied. If client specifies refresh_token_ttl<=0, refresh token is not returned even if the corresponding grant type is supported open var `refresh_token_ttl`: Int? // Phone number linked to account or extension in account in E.164 format with or without leading "+" sign open var `username`: String? // Optional. Extension short number. If company number is specified as a username, and extension is not specified, the server will attempt to authenticate client as main company administrator open var `extension`: String? // User's password open var `password`: String? // Optional. List of API permissions to be used with access token (see Application Permissions). Can be omitted when requesting all permissions defined during the application registration phase open var `scope`: String? // Optional. Unique identifier of a client application. You can pass it in request according to pattern [a-zA-Z0-9_\-]{1,64}. Otherwise it is auto-generated by server. The value will be returned in response in both cases open var `endpoint_id`: String? public init() { } required public init?(map: Map) { } convenience public init(grant_type: String? = nil, access_token_ttl: Int? = nil, refresh_token_ttl: Int? = nil, username: String? = nil, extension: String? = nil, password: String? = nil, scope: String? = nil, endpoint_id: String? = nil) { self.init() self.grant_type = `grant_type` self.access_token_ttl = `access_token_ttl` self.refresh_token_ttl = `refresh_token_ttl` self.username = `username` self.extension = `extension` self.password = `password` self.scope = `scope` self.endpoint_id = `endpoint_id` } open func mapping(map: Map) { `grant_type` <- map["grant_type"] `access_token_ttl` <- map["access_token_ttl"] `refresh_token_ttl` <- map["refresh_token_ttl"] `username` <- map["username"] `extension` <- map["extension"] `password` <- map["password"] `scope` <- map["scope"] `endpoint_id` <- map["endpoint_id"] } } }
true
2a20f2d01f6505084fb787814c79ae3c6a7c1126
Swift
yveslym/CapProject__
/CapProject-11c4cd0ff0acdc0833c860c9e9fac3d858e76a8e/CapProject/Post.swift
UTF-8
1,004
2.578125
3
[]
no_license
// // Post.swift // CapProject // // Created by Yves Songolo on 8/8/17. // Copyright © 2017 Yveslym. All rights reserved. // import Foundation import UIKit import Firebase class Post: NSObject{ var teacherLastName : String? var postDescrition: String? var url: String? var teacherPicture: UIImage? var date: Date? var postID:String? override init (){ self.date = Date() self.postDescrition = "" self.url = "" self.teacherPicture = UIImage() self.teacherLastName = "" self.postID = "" } init?(snapshot: DataSnapshot) { guard let dict = snapshot.value as? [String: Any] else{return nil} let post = dict["info"] as? Post self.date = post?.date self.postDescrition = post?.postDescrition self.teacherLastName = post?.teacherLastName self.postID = post?.postID self.teacherPicture = UIImage() } }
true
055db97914e0e3f8fb263de2a3bb2d78a9cace88
Swift
cao903775389/FYDataStructureDemo
/FYDataStructureDemo/algorithm/BinarySearchTree.swift
UTF-8
4,561
3.515625
4
[]
no_license
// // BinarySearchTree.swift // FYDataStructureDemo // // Created by admin on 2019/12/26. // Copyright © 2019 fengyangcao. All rights reserved. // import Foundation ///二叉搜索树 class BinarySearchTree<T: Comparable> { var value: T var parent: BinarySearchTree? var left: BinarySearchTree? var right: BinarySearchTree? init(value: T) { self.value = value } //插入节点 public func insert(value: T) { if value < self.value { //当前值比根节点小 if let left = self.left { //存在左子树 left.insert(value: value) }else { //左子树不存在 直接插入 left = BinarySearchTree(value: value) left?.parent = self; } }else { //当前值比根节点大 if let right = self.right { //存在右子树 right.insert(value: value) }else { //右子树不存在 直接插入 right = BinarySearchTree(value: value) right?.parent = self; } } } //删除节点 //case1 当前节点的left tree最大的node //case2 当前节点的right tree最小的note @discardableResult public func remove() -> BinarySearchTree? { var replaceNode: BinarySearchTree? if let left = left { //找到左子树最大值的node replaceNode = left.maximum() }else if let right = right { //找到右子树最小的 replaceNode = right.minimum() }else { replaceNode = nil } //移除将要移动的节点 replaceNode?.remove() //将替换的节点移动到当前需要删除的节点位置 replaceNode?.left = left replaceNode?.right = right left?.parent = replaceNode right?.parent = replaceNode //将当前节点parent节点的字节点修改为要替换的 if let parent = parent { if self === parent.left { parent.left = replaceNode }else if self === parent.right { parent.right = replaceNode } } //清空当前节点 parent = nil left = nil right = nil return replaceNode } public func maximum() -> BinarySearchTree { var node = self if let right = node.right { node = right.maximum() } return node } public func minimum() -> BinarySearchTree { var node = self if let left = node.left { node = left.minimum() } return node } //遍历二叉搜索树 //中序遍历 public func traverseInOrder() { left?.traverseInOrder() print("中序遍历当前节点的值:\(value)") right?.traverseInOrder() } //前序遍历 public func traversePreOrder() { print("前序遍历当前节点的值\(value)") left?.traversePreOrder() right?.traversePreOrder() } //后序遍历 public func traversePostOrder() { left?.traversePostOrder() right?.traversePostOrder() print("后序遍历当前节点的值\(value)") } //搜索 public func search(value: T) -> BinarySearchTree? { if value < self.value { return left?.search(value: value) }else if value > self.value { return right?.search(value: value) }else { return self } } //返回树的高度(当前节点到最下方的字节点的需要的步数) public func height() -> Int { if let _ = parent { return 1 + max(left?.height() ?? 0, right?.height() ?? 0) }else { return 0 } } //返回树的深度(当前节点到根节点需要的步数) public func depth() -> Int { var depth = 0 var node = self while let parent = node.parent { node = parent depth += 1 } return depth } } extension BinarySearchTree: CustomStringConvertible { public var description: String { var s = "" if let left = left { s += "(\(left.description)) <- " } s += "\(value)" if let right = right { s += " -> (\(right.description))" } return s } }
true
23a9e2931333578c917cc4f828fcfaf6866f54bc
Swift
mrADVIRUS/SelectoTest
/SelectoTest/API/SelectoTranslateApi.swift
UTF-8
2,474
2.65625
3
[]
no_license
// // SelectoTranslateApi.swift // SelectoTest // // Created by Sergiy Lyahovchuk on 28.08.17. // Copyright © 2017 HardCode. All rights reserved. // import Foundation import Alamofire import SwiftyJSON final class SelectoTranslateApi { static let sharedInstance = SelectoTranslateApi() private init() { } func reguestTranslate(params: [String: String], success:@escaping TranslatedText, failure:@escaping FailureBlock ) { guard API_KEY != "" else { let userInfo: [AnyHashable : Any] = [ NSLocalizedDescriptionKey : NSLocalizedString("Unauthorized", value: "Warning: You should set the api key before calling the translate method.", comment: "") , NSLocalizedFailureReasonErrorKey : NSLocalizedString("Unauthorized", value: "Absent API_KEY", comment: "") ] let error = NSError(domain: "", code: 400, userInfo: userInfo) as Error failure(error) return } // let strUrl = URL(string: "https://translation.googleapis.com/language/translate/v2?key=\(API_KEY)&q=Hello&source=en&target=uk&format=text") if let urlEncodedText = params["text"]?.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { let source = params["source"]! let target = params["target"]! let strTranslateUrl = "\(BASE_URL)\(METHOD_TRANSLATE)?key=\(API_KEY)&q=\(urlEncodedText)&source=\(source)&target=\(target)&format=text" let translateUrl = URL(string: strTranslateUrl)! Alamofire.request(translateUrl, method: .post, parameters: params, encoding: JSONEncoding.default, headers: ["Content-Type": "application/json"]).responseJSON { response in guard response.result.isSuccess else { print("Error : \(String(describing: response.result.error))") failure(response.result.error!) return } let resJson = JSON(response.result.value!) if let translations = resJson["data"]["translations"].array { if let translatedText = translations.first?["translatedText"].stringValue { success(translatedText) } } } } } }
true
79d7e45f7eda6b5903b56a1c68d8d38c41ca3c8c
Swift
JoshuaKaden/NavControllerAsDelegate
/NavControllerAsDelegate/AppManager.swift
UTF-8
1,233
3.03125
3
[]
no_license
// // AppManager.swift // NavControllerAsDelegate // // Created by Kaden, Joshua on 1/13/16. // Copyright © 2016 NYC DoITT App Dev. All rights reserved. // import Foundation /** Waits a number of seconds, and then performs a closure on the main thread. Hats off to Matt Neuburg: http://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift/24318861#24318861 */ func delay(delay:Double, closure:()->()) { if delay == 0 { closure() return } dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } protocol AppManagerDelegate { func showMessage(message: String) } class AppManager { var delegate : AppManagerDelegate? func triggerMessageFromBackground() { let qualityOfServiceClass = QOS_CLASS_BACKGROUND let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0) dispatch_async(backgroundQueue, { print("This is run on the background queue.") delay(3) { self.delegate?.showMessage("This was invoked from the background queue.") } }) } }
true
bbfb246db7229a71bdc40f1e5aa1ee369e30fa5f
Swift
Takeru-chan/mkpass
/Condition/Condition.swift
UTF-8
3,492
2.953125
3
[ "MIT" ]
permissive
class Condition { private var length: Int // Condition class returns length of password from options. private var returnCode: Int32 // Condition class returns return code. Success:0, Version:1, Help:2, Failure:9 private var member: [Character] // Condition class returns character set of password from options. init(length: Int = 0, returnCode: Int32 = 0, member: [Character] = []) { self.length = length self.returnCode = returnCode self.member = member } func get(arguments: [String]) -> ([Character], Int, Int32) { enum ArgsType { case unknown case option case length case error } var argType: ArgsType = ArgsType.unknown var option: String let upper: [String] = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ","ABCDEFGHJKLMNPQRSTUVWXYZ"] let lower: [String] = ["abcdefghijklmnopqrstuvwxyz","abcdefghijkmnopqrstuvwxyz"] let number: [String] = ["0123456789","23456789"] let symbol: [String] = ["!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~","!\"#$%&\'()*+,-./:;<=>?@[\\]^_`{}~"] var status: (upper: Int, lower: Int, number: Int, symbol: Int, exclude: Int) = (0, 0, 0, 0, 0) chk_opt: for n in 1..<arguments.count { option = arguments[n] for char in option.characters { if argType == ArgsType.unknown { switch char { case "-": argType = ArgsType.option case "1"..."9": argType = ArgsType.length default: argType = ArgsType.error returnCode = 9 break } } else if argType == ArgsType.option { switch char { case "a": status.upper |= 0b00000001 status.lower |= 0b00000001 status.number |= 0b00000001 status.symbol |= 0b00000001 case "u": status.upper |= 0b00000001 case "l": status.lower |= 0b00000001 case "n": status.number |= 0b00000001 case "s": status.symbol |= 0b00000001 case "x": status.exclude |= 0b00000001 case "v": argType = ArgsType.error returnCode = 1 break case "h": argType = ArgsType.error returnCode = 2 break default: argType = ArgsType.error returnCode = 9 break } } else if argType == ArgsType.length { switch char { case "0"..."9": argType = ArgsType.length default: argType = ArgsType.error returnCode = 9 break } } if returnCode != 0 { break chk_opt } } if argType == ArgsType.length { length = Int(option)! } argType = ArgsType.unknown } if status.upper != 0 { member += Array(upper[status.exclude].characters) } if status.lower != 0 { member += Array(lower[status.exclude].characters) } if status.number != 0 { member += Array(number[status.exclude].characters) } if status.symbol != 0 { member += Array(symbol[status.exclude].characters) } if (returnCode == 0 && member.count == 0) { member = Array(lower[status.exclude].characters) + Array(number[status.exclude].characters) } if (returnCode == 0 && length == 0) { length = 8 } return (member, length, returnCode) } }
true
3b034e99d1d79bda4e3aae61d0739cb80d007d9a
Swift
jshier/FlyIn
/FlyInNetworking/Responses/RawResponses.swift
UTF-8
564
2.53125
3
[]
no_license
// // RawResponses.swift // FlyInNetworking // // Created by Jon Shier on 7/16/17. // Copyright © 2017 Jon Shier. All rights reserved. // import Foundation struct RawLocation: Decodable { let lon: Double let lat: Double let iLName: String? } struct RawEvent: Decodable { let locs: [RawLocation] let sTime: Double? let eTime: Double? let title: String let html: String } struct RawEvents: Decodable { let items: [RawEvent] } struct RawResponse: Decodable { let result: RawEvents }
true
dfbbf1bbe1b164de57684d2810c8e8e7b45980fe
Swift
vaibhavaggarwal4/VAPeekPopGestureRecognizer
/VAPeekPopGestureRecogonizer/PeekPopRecogonizer.swift
UTF-8
6,133
3.125
3
[]
no_license
// // PeekPopRecogonizer.swift // VAPeekPopGestureRecogonizer // // Created by Vaibhav Aggarwal on 2/20/16. // Copyright © 2016 Vaibhav Aggarwal. All rights reserved. // /********* Abstract: This class allows to have Peek and Pop functionlality like the one enabled by Force Touch, but for devices that does not have the 3D touch hardware. It uses a UILongPressGestureRecognizer to achieve and simulate similar functionality **********/ import Foundation import UIKit /* * PeekPopGestureRecogonizerProtocol must be implemented by a ViewController that needs the functionality * */ protocol PeekPopGestureRecogonizerProtocol { /* return the view controller that needs to be peeked and popped */ func peekPopViewController() -> UIViewController /* * Dimisses the peeking view controller * The peeking view controller is not presented modally, but is added as a child view controller * the delagate view controller needs to implement this method and JUST needs to call PeekPopGestureRecogonizer instance's dismissPeekingController method */ func dismissPeekingViewController() } /* Defines animations for peek */ enum PeekAnimationType { case FadeIn // fade in using alpha case GrowIn // appear in by scaling CGAffineTransform } class PeekPopGestureRecogonizer { var delegate: PeekPopGestureRecogonizerProtocol? private var longPressGestureRecogonizer: UILongPressGestureRecognizer private var longPressTimer = NSTimer() private weak var peekingViewController: UIViewController? private var hasPopped = false private var peekAnimationType: PeekAnimationType = .GrowIn init(view: UIView, peekAnimation: PeekAnimationType?) { self.longPressGestureRecogonizer = UILongPressGestureRecognizer() self.longPressGestureRecogonizer.minimumPressDuration = 0.5 self.longPressGestureRecogonizer.addTarget(self, action: "longPressDetected:") view.addGestureRecognizer(self.longPressGestureRecogonizer) if peekAnimation != nil { self.peekAnimationType = peekAnimation! } } /* * Handles long press gesture and asks to peek, pop or dismiss the new view controller based on the gesture recogonizer state * The new vc is popped only if the user continues to touch after the state began is recieved else it is dismissed */ @objc func longPressDetected(recogonizer: UILongPressGestureRecognizer) { if recogonizer.state == UIGestureRecognizerState.Began { if let vc = self.delegate?.peekPopViewController() { self.peekViewController(vc) if self.longPressTimer.valid { self.longPressTimer.invalidate() } self.hasPopped = false self.longPressTimer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: "popViewController", userInfo: nil, repeats: false) } } else if recogonizer.state == .Ended || recogonizer.state == .Cancelled { self.longPressTimer.invalidate() if !self.hasPopped { self.dismissPeekingController() } } else if recogonizer.state == .Failed { self.longPressTimer.invalidate() self.dismissPeekingController() } } /* * Gives a peek of the viewController * Animation depends on the peekTypeAnimation variable */ func peekViewController(viewController: UIViewController) { if let delegateVC = self.delegate as? UIViewController { delegateVC.addChildViewController(viewController) viewController.didMoveToParentViewController(delegateVC) viewController.view.alpha = 0.0 viewController.view.frame = delegateVC.view.frame if self.peekAnimationType == .FadeIn { self.fadeInAnimation(viewController) } else { self.growInAnimation(viewController) } } } private func growInAnimation(viewController: UIViewController) { if let delegateVC = self.delegate as? UIViewController { viewController.view.transform = CGAffineTransformMakeScale(0, 0) delegateVC.view.addSubview(viewController.view) self.peekingViewController = viewController UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in viewController.view.transform = CGAffineTransformMakeScale(0.8, 0.6) viewController.view.alpha = 1.0 }, completion: { (finished: Bool) -> Void in }) } } private func fadeInAnimation(viewController: UIViewController){ if let delegateVC = self.delegate as? UIViewController { viewController.view.transform = CGAffineTransformMakeScale(0.8, 0.6) delegateVC.view.addSubview(viewController.view) self.peekingViewController = viewController UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in viewController.view.alpha = 1.0 }, completion: { (finished: Bool) -> Void in }) } } /* * Pops the viewController * */ @objc private func popViewController() { if let vc = self.peekingViewController { UIView.animateWithDuration(0.2, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.6, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in vc.view.transform = CGAffineTransformIdentity }, completion: { [weak self] (finished: Bool) -> Void in self?.hasPopped = true }) } } /* * Dismisses the viewController * */ func dismissPeekingController() { if let vc = self.peekingViewController { UIView.animateWithDuration(0.2, animations: { () -> Void in if self.hasPopped { vc.view.transform = CGAffineTransformMakeTranslation(0, vc.view.frame.size.height) vc.view.alpha = 0.4 } else { vc.view.alpha = 0.0 } }) { (finish: Bool) -> Void in vc.view.removeFromSuperview() vc.willMoveToParentViewController(nil) vc.removeFromParentViewController() } } } }
true
f3177bc48f24f19561e017d8d71d67d00671e738
Swift
buscarini/sio
/Sources/Sio/Either.swift
UTF-8
2,806
3.171875
3
[ "MIT" ]
permissive
// // Either.swift // sio-iOS Tests // // Created by José Manuel Sánchez Peñarroja on 02/06/2019. // Copyright © 2019 sio. All rights reserved. // import Foundation public enum Either<A, B> { case left(A) case right(B) public var left: A? { switch self { case let .left(left): return left case .right: return nil } } public var right: B? { switch self { case .left: return nil case let .right(right): return right } } public var isLeft: Bool { switch self { case .left: return true case .right: return false } } @inlinable public var isRight: Bool { switch self { case .left: return false case .right: return true } } @inlinable public func left(default value: A) -> A { left ?? value } @inlinable public func right(default value: B) -> B { right ?? value } @inlinable public func fold<C>(_ left: (A) -> C, _ right: (B) -> C) -> C { switch self { case .left(let l): return left(l) case .right(let r): return right(r) } } } extension Either: Equatable where A: Equatable, B: Equatable { @inlinable public static func == (lhs: Either<A, B>, rhs: Either<A, B>) -> Bool { switch (lhs, rhs) { case let (.left(l1), .left(l2)): return l1 == l2 case let (.right(r1), .right(r2)): return r1 == r2 default: return false } } } extension Either: Hashable where A: Hashable, B: Hashable { public func hash(into hasher: inout Hasher) { switch self { case let .left(left): hasher.combine("left") hasher.combine(left) case let .right(right): hasher.combine("right") hasher.combine(right) } } } extension Either { @inlinable public func map<V>(_ f: (B) -> V) -> Either<A, V> { mapRight(f) } @inlinable public func const<V>(_ v: V) -> Either<A, V> { mapRight { _ in v } } @inlinable public static func mapLeft<A, B, C>( _ transform: @escaping (A) -> C ) -> (Either<A, B>) -> Either<C, B> { { $0.mapLeft(transform) } } @inlinable public static func mapRight<A, B, C>( _ transform: @escaping (B) -> C ) -> (Either<A, B>) -> Either<A, C> { { $0.mapRight(transform) } } @inlinable public func mapLeft<V>(_ f: (A) -> V) -> Either<V, B> { bimap(f, id) } @inlinable public func mapRight<V>(_ f: (B) -> V) -> Either<A, V> { bimap(id, f) } @inlinable public func bimap<V, W>(_ f: (A) -> V, _ g: (B) -> W) -> Either<V, W> { switch self { case let .left(left): return .left(f(left)) case let .right(right): return .right(g(right)) } } @inlinable public var swapped: Either<B, A> { switch self { case let .left(left): return .right(left) case let .right(right): return .left(right) } } } extension Either where A == B { @inlinable public func mapAll<V>(_ f: (A) -> V) -> Either<V, V> { bimap(f, f) } }
true
85f22d6b84fa5259188106f1233900a0501a82bb
Swift
dpavlek/StormViewer
/HackingWithSwiftPlayground.playground/Contents.swift
UTF-8
1,261
3.875
4
[]
no_license
//: Playground - noun: a place where people can play import UIKit var name = "Tim McGraw" "Your name is \(name)" "Your name is " + name var songs = ["Shake it Off", "You Belong with Me", "Back to December"] func albumReleased(year: Int) -> String? { switch year { case 2006: return "Taylor Swift" case 2008: return "Fearless" case 2010: return "Speak Now" case 2012: return "Red" case 2014: return "1989" default: return nil } } let album = albumReleased(year: 2006)?.uppercased() print("The album is \(album)") enum WeatherType { case sun case cloud case rain case wind(speed: Int) case snow } func getHaterStatus(weather: WeatherType) -> String? { switch weather { case .sun: return nil case .wind(let speed) where speed < 10: return "meh" case .cloud, .wind: return "dislike" case .rain, .snow: return "hate" } } getHaterStatus(weather: WeatherType.wind(speed: 5)) struct Person { var clothes: String var shoes: String } let taylor = Person(clothes: "T-shirts", shoes: "sneakers") let other = Person(clothes: "short skirts", shoes: "high heels") var taylorCopy = taylor taylorCopy.shoes = "flip flops" print(taylor) print(taylorCopy)
true
2e75b165a3cac769e0d85a2837baaad24c034635
Swift
sjaindl/TravelCompanion
/native/Travel Companion/BaseUI/Form/Cells/MessageCell.swift
UTF-8
1,282
2.734375
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
// Travel Companion // // Created by Stefan Jaindl on 27.07.22. // Copyright © 2022 Stefan Jaindl. All rights reserved. // import UIKit public final class MessageCell: FormCell, XibLoadable { public static let xibName = "MessageCell" @IBOutlet private var messageLabel: UILabel! @IBOutlet private var messageLabelBottomConstraint: NSLayoutConstraint! @IBOutlet private var messageLabelTopConstraint: NSLayoutConstraint! public var message: String? { get { messageLabel.text } set { messageLabel.text = newValue } } public var messageColor: UIColor? { get { messageLabel.textColor } set { messageLabel.textColor = newValue } } override public func isValid() -> Bool { false } override public func awakeFromNib() { super.awakeFromNib() selectionStyle = .none } public func heightToFitMessage() -> CGFloat { let height = messageLabel.sizeThatFits(CGSize( width: frame.size.width, height: 50 )).height return height + messageLabelVerticalMargin } // MARK: Private private var messageLabelVerticalMargin: CGFloat { messageLabelTopConstraint.constant + messageLabelBottomConstraint.constant } }
true
9b32202b99b9bed1d1e322a7c55c6ed08a8943f2
Swift
rishab85/Mobile-App-Dev-Assignment-1
/assignment2_1.playground/Contents.swift
UTF-8
863
3.515625
4
[]
no_license
import Cocoa let playground = "Hello, playground" var mutablePlayground = "Hello, mutable playground" mutablePlayground += "!" for c: Character in mutablePlayground.characters { print("\(c)") } let oneCoolDude = "\u{1F60E}" let aAcute = "\u{0061}\u{0301}" for scalar in playground.unicodeScalars { print("\(scalar.value)") } let aAcutePrecomposed = "\u{00E1}" let b = (aAcute == aAcutePrecomposed) print("aAcute: \(aAcute.characters.count)") print("aAcutePrecomposed: \(aAcutePrecomposed.characters.count)") let fromStart: String.Index = playground.startIndex let toPosition: Int = 4 let end : String.Index = fromStart.advancedBy(toPosition) let fifthCharacter = playground[end] // result is "o" let range = fromStart...end let firstFive = playground[range] // result is "Hello" let unicodeFirstFive = "\u{0048}\u{0065}\u{006C}\u{006C}\u{006F}"
true
1e7b4358a9c612458da4f59fb79ae778e53efe68
Swift
90dhjeong/Swift-study
/Study/StudyString.swift
UTF-8
19,936
4.1875
4
[]
no_license
// // StudyString.swift // Study // // Created by Dahye on 2021/03/08. // import Foundation func tuples() { // Scalar Type - 12 // Compund Type - (12, 34) // 튜플에 저장되는 멤버의 수는 생성될 때 고정 // 멤버의 값 변경은 가능함 // 값형식 let data = ("<html>", 200, "OK", 12.34) // Unnamed Tuple print(data.0) // index 접근 // data.1 var mutableTuple = data mutableTuple.1 = 404 // Named Tuples // let named = (body: "<html>", statusCode: 200, statusMessage: "OK", dataSize: 12.34) named.1 named.statusCode // Tuple Decomposition // /* let(name1, name2, ...) = tupleExpr var(name1, name2, ...) = tupleExpr */ // let body = data.0 // let code = data.1 // let message = data.2 // let size = data.3 let (body, code, message, size) = data // 단일값으로 분해되어서 저장됨 // wildcard pattern으로 생략 가능 // Tuple Matching // let resolution = (3840.0, 2160.0) if resolution.0 == 3840 && resolution.1 == 2160 { print("4K") } switch resolution { case (3840, 2160): print("4K") case (3840...4096, 2160): print("4K") case (_, 1080): print("1080p") case let (w, h) where w / h == 16.0 / 9.0: print("16:9") default: break } // 여기에서 함수를 구현해 주세요. func convertToTuple(name: String, age: Int, address: String) -> (name: String, age: Int, address: String) { return (name, age, address) } let name = "John doe" let age = 34 let address = "Seoul" let t = convertToTuple(name: name, age: age, address: address) // 여기에서 튜플에 저장된 이름, 나이, 주소를 순서대로 출력해 주세요. print(t.name, t.age, t.address) } func stringsAndCharacters() { let s = "String" // let c = "C" let c: Character = "C" let emptyChar: Character = " " // 빈문자 저장은 공백 추가 let emptyString = " " emptyString.count // 1 let emptyString2 = String() // StringTypes // String -> Swift String // 값 // NSString -> Foundation String // 참조 var nsstr: NSString = "str" let swiftStr: String = nsstr as String // Type Casting nsstr = swiftStr as NSString // 유니코드가 달라 주의 let imuutableStr = "str" var mutableStr = "str" mutableStr = "mutable" // Unicode - String 레퍼 체크 let str = "Swift String" str.utf8 str.utf16 var thumbUp = "👍" // unicode Scalar thumbUp = "\u{1F44d}" } func multilineStringLiterals() { // 기존 String은 singleline // 명시적 줄바꿈 가능 (엔터) // 내용 시작위치는 반드시 새로운 라인에서 // 마지막 따움표는 한 줄에 단독으로, 첫번째 줄과 동일선상이거나 마지막에 (들여쓰기 기준) let interstellar = "Interstellar is a 2014 epic science fiction film directed and produced by Christopher Nolan. It stars Matthew McConaughey, Anne Hathaway, Jessica Chastain, Bill Irwin, Ellen Burstyn, John Lithgow, Michael Caine, and Matt Damon. Set in a dystopian future where humanity is struggling to survive, the film follows a group of astronauts who travel through a wormhole near Saturn in search of a new home for mankind." let multiline = """ Interstellar is a 2014 epic science fiction film directed and produced by Christopher Nolan. It stars Matthew McConaughey, Anne Hathaway, Jessica Chastain, Bill Irwin, Ellen Burstyn, John Lithgow, Michael Caine, and Matt Damon. Set in a dystopian future where humanity is struggling to survive, the film follows a group of astronauts who travel through a wormhole near Saturn in search of a new home for mankind. """ } func stringInterpolation() { /* \(expr) */ // 직관적 구성 가능, 포맷 지정이 불가능 (소수점 자릿수 등) var str = "12.34KB" let size = 12.34 // str = size + "KB" Double을 문자열로 변경해야 함 str = String(size) + "KB" // 자주 사용하지 않음 str = "\(size)" + "KB" // Format Specifier /* String Format Specifiers https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1 */ // %char str = String(format: "%.1fKB", size) // 12.3KB String(format: "Hello, %@", "Swift") String(format: "%d", 12) String(format: "%d", 12.34) // 0 출력됨 String(format: "%f", 12.34) // 12.340000 출력됨 String(format: "%.3f", 12.34) // 12.340 출력됨 String(format: "%10.3f", 12.34) // [ 12.340] 전체문자열을 10자리로, 소수점은 아래는 3자리 String(format: "%010.3f", 12.34) // [000012.340] 전체문자열을 10자리로, 소수점은 3자리 String(format: "[%d]", 123) // [123] String(format: "[%10d]", 123) // [ 123] -> 10자리 출력후 오른쪽 정렬 String(format: "[%-10d]", 123) // [123 ]] -> 10자리 출력 후 왼쪽 정렬 let firstname = "Dahye" let lastName = "Jeong" let korFormat = "그녀의 이름은 %@ %@ 입니다." let korFormat2 = "그녀의 이름은 %2$@ %1$@ 입니다." // 첫번째 포맷지정자는 두번째 파라미터로 교체 ... let engFormat = "Her name is %1$@ %2$@" String(format: korFormat2, firstname, lastName) String(format: engFormat, firstname, lastName) // \ -> \\ // \t- > tab // \n -> newline // \" -> " // \' -> ' } func stringIndices() { // 반드시 올바른 index를 사용해야 한다(runtime error 발생) let str = "Swift" let firstCh = str[str.startIndex] // S let lastCh = str[str.endIndex] // error - past the end let lastCharIndex = str.index(before: str.endIndex) let lastCh2 = str[lastCharIndex] let secondCharIndex = str.index(after: str.startIndex) let secondCh = str[secondCharIndex] // w // var thirdCharIndex = str.index(a fter:secondCharIndex) var thirdCharIndex = str.index(str.startIndex, offsetBy: 2) var thirdCh = str[thirdCharIndex] // i thirdCharIndex = str.index(str.endIndex, offsetBy: -3) thirdCh = str[thirdCharIndex] if thirdCharIndex < str.endIndex && thirdCharIndex >= str.startIndex { } } func rangeOperator() { // 1 ~ 5 // Closed Range Operator // 이항 a ... b // 단항 a... / ...a // upperBound가 범위에 포함된다 var sum = 0 for num in 1 ... 10 { sum += num } // 55 let list = ["A", "B", "C", "D", "E"] list[2...] list[...2] // 범위 고정시 사용 가능 // Half-Open Range Operator // 이항 a ..< b // 단항 ..<a // upperBound가 범위에 포함되지 않는다 sum = 0 for num in 1 ..< 10 { sum += num } // 45 list[..<2] let range = 0 ... 5 range.contains(7) range.contains(1) let range2 = ...5 range2.contains(7) range2.contains(1) range2.contains(-1) // true -> lowerBound가 무한대가 됨 } func stringBasic() { // 문자열은 시퀀스라 for 가능 var str = "Hello, Swift String" var emptyStr = "" emptyStr = String() let a = String(true) // "true" let b = String(12) // "12" let c = String(12.34) let d = String(str) let hex = String(123, radix: 16) // "7b" let octal = String(123, radix: 8) // 173 let binary = String(123, radix: 2) // 1111011 // let repeatStr = "✌️" let repeatStr = String(repeating: "✌️", count: 10) // ✌️✌️✌️✌️✌️✌️✌️✌️✌️✌️ let e = "\(a) \(b)" let f = a + " " + b str += "!!" // Hello, Swift String!! str.count // 21 str.count == 0 str.isEmpty // false str == "Apple" // false "apple" != "Apple" // true "apple" < "Apple" // false (아스키 코드 크기 비교) str.lowercased() // 소문자 변환(ed는 새로운 값을 리턴, 원본은 건드리지 않음) str.uppercased() // 대문자 변환 str.capitalized // UpperCamelCase 변환 for char in "Hello" { print(char) } let num = "1234567890" num.randomElement() // 랜덤한 문자 하나 추출 num.shuffled() // 문자열을 셔플한 뒤 배열로 반환 } func subString() { // 하나의 문자열에서 특정 범위의 문자열 // 읽을 땐 원본 문자열의 메모리를 공유한다 // 변경할 땐 새로운 문자열을 생성한다(컴파일러 자동처리) // 메모리 절약을 위해 사용 let str = "Hello, Swift" let l = str.lowercased() // 별도의 메모리로 저장됨 var first = str.prefix(1) // 원본 메모리를 공유함 // first는 String.SubSequence (SubString의 typealias) first.insert("!", at: first.endIndex) // 별도의 메모리로 저장됨 print(str) // "Hello, Swift" print(first) // "Hi!" // Copy-on-write Optimization let newStr = String(str.prefix(1)) // 별도의 메모리 공간에 저장됨 let s = str[str.startIndex ..< str.index(str.startIndex, offsetBy: 2)] // He let s2 = str[..<str.index(str.startIndex, offsetBy: 2)] let s3 = str[str.index(str.startIndex, offsetBy: 2)...] let lower = str.index(str.startIndex, offsetBy: 2) let upper = str.index(str.startIndex, offsetBy: 5) let s4 = str[lower ... upper] // s는 subString } func stringEditing1() { // 문자열 추가, 사이에 넣기 var str = "Hello" str.append(", ") let s = str.appending("Swift") print(str) // append - 대상 문자열을 직접 변경 print(s) // appending - 원본을 변경하지 않고 새로운 값을 리턴함 "File size is ".appendingFormat("%.1f", 12.3456) // 새로운 문자열 리턴 var str2 = "Hello Swift" str2.insert(",", at: str.index(str.startIndex, offsetBy: 5)) if let sIndex = str2.firstIndex(of: "S") { str2.insert(contentsOf: "Awesome", at: sIndex) } } func stringEditing2() { // 교체, 삭제 // 문자열 비교는 기본적으로 대소문자를 구별한다 var str = "Hello, Obejctive-C" if let range = str.range(of: "Objective-C") { str.replaceSubrange(range, with: "Swift") } if let range = str.range(of: "Hello") { let s = str.replacingCharacters(in: range, with: "Hi") } // 원본변경 X var s = str.replacingOccurrences(of: "Swift", with: "Awesome Swift") // 새로운 문자열 리턴 s = str.replacingOccurrences(of: "swift", with: "Awesome Swift") // 대소문자를 구분하므로 원본문자열을 리턴함 s = str.replacingOccurrences(of: "swift", with: "Awesome Swift", options: .caseInsensitive) // 대소문자 구분 없이 진행 //Removing SubString var str2 = "Hello, Awesom Swift!!!" let lastCharIndex = str2.index(before: str.endIndex) var removed = str2.remove(at: lastCharIndex) // 원본 삭제, Character를 리턴함, 잘못된 인덱스는 에러 발생 removed = str2.removeFirst() // 삭제된 문자를 리턴함, 원본 삭제 str2.removeFirst(2) // 2개의 문자를 삭제함, 리턴해주진 않음 str2.removeLast() str2.removeLast(2) if let range = str.range(of: "Awesome") { str2.removeSubrange(range) // 범위 삭제시 사용 } str.removeAll() // 메모리공간도 함께 삭제함 str2.removeAll(keepingCapacity: true) // 메모리 공간은 유지함 str2 = "Hello, Awesom Swift!!!" var substr = str.dropLast() // 원본 문자열과 메모리를 공유함, 마지막!을 삭제한 뒤 새로운 문자열을 리턴함 substr = str2.dropLast(3) // 3개를 제외한 나머지 문자열과 메모리를 공유함 substr.drop(while: { (ch) -> Bool in return ch != "," }) // true가 리턴되는 동안 삭제, false리턴 시 종료하고 남은 문자열을 리턴함 print(substr) // ",Awusome Swift!!!" } func stringComparison() { // 문자열 비교 let largeA = "Apple" let smallA = "apple" let b = "Banana" largeA == smallA // false largeA != smallA // true // 문자열에 할당된 코드의 크기 비교 largeA < smallA // true, ascii code largeA < b // true smallA < b // false // 메소드로 비교 largeA.compare(smallA) // NSComparisonResult가 반환 largeA.compare(smallA) == .orderedSame // 같은지 비교할 때(대소문자 구분) - false largeA.caseInsensitiveCompare(smallA) == .orderedSame // 같은지 비교할 때(대소문자 구분 없이) - true largeA.compare(smallA, options: [.caseInsensitive]) == .orderedSame // 위와 같음. 문자열 옵션을 지정할 때 사용 let str = "Hello, Swift Programming!" let prefix = "Hello" let suffix = "Programming" str.hasPrefix(prefix) // true str.hasSuffix(suffix) // false str.lowercased().hasPrefix(prefix.lowercased()) // 대소문자 구별 없이 접두어 비교 } func stringSearching() { // 단어 검색 let str = "Hello, Swift" str.contains("Swift") // 포함여부를 Bool로 반환 str.contains("swift") // false str.lowercased().contains("swift") // true // 범위 검색 if let range = str.range(of: "Swift") { } str.range(of: "swift", options: [.caseInsensitive]) let str2 = "Hello, Programming" let str3 = str2.lowercased() // 별도의 메모리, subString이 아님. var common = str.commonPrefix(with: str2) // 공통 접두어만 새로운 문자열로 리턴 common = str.commonPrefix(with: str3) common = str.commonPrefix(with: str3, options: .caseInsensitive) } func stringOptions1() { // 9가지의 문자열 옵션 제공 //Case Insensitive Option "A" == "a" // false "A".caseInsensitiveCompare("a") == .orderedSame "A".compare("a", options: .caseInsensitive) == .orderedSame //Literal Option let a = "\u{D55C}" // 완성형 한 let b = "\u{1112}\u{1161}\u{11AB}" // 조합형 한 a == b // true a.compare(b) == .orderedSame // true, 유닛을 합친 후 최종 문자가 같기 때문 a.compare(b, options: [.literal]) == .orderedSame // 이 옵션을 사용하는게 빠름, 코드유닛을 비교함 //Backward Option - 문자 읽는 방향 leading -> Trailng let korean = "행복하세요" let english = "Be happy" let arabic = "어랍아" if let range = english.range(of: "p") { english.distance(from: english.startIndex, to: range.lowerBound) // 5 } if let range = english.range(of: "p", options: .backwards) { english.distance(from: english.startIndex, to: range.lowerBound) // 6 (y앞의 p) } //Anchored Option - 검색 범위 지정 let str = "Swift Programming" if let result = str.range(of: "Swift") { print(str.distance(from: str.startIndex, to: result.lowerBound)) } else { print("not found") } // 0 if let result = str.range(of: "Swift", options: .backwards) { print(str.distance(from: str.startIndex, to: result.lowerBound)) } else { print("not found") } // 0 if let result = str.range(of: "Swift", options: .anchored) { print(str.distance(from: str.startIndex, to: result.lowerBound)) } else { print("not found") } // 0 if let result = str.range(of: "Swift", options: [.anchored, .backwards]) { print(str.distance(from: str.startIndex, to: result.lowerBound)) } else { print("not found") } // not found - 진행방향에서 안 보였기 때문 str.hasPrefix("swift") str.lowercased().hasPrefix("swift") if let _ = str.range(of: "swift", options: [.anchored, .caseInsensitive]) { print("same prefix") } // same prefix str.hasSuffix("swift") if let _ = str.range(of: "swift", options: [.anchored, .backwards,.caseInsensitive]) { print("same prefix") } // same prefix } func stringOptions2() { //Numeric Option - 문자에 포함된 숫자를 숫자 자체로 처리함 "A" < "B" // true "a" < "B" // false - 문자에 할당되어있는 코드(아스키)의 크기 비교 let file9 = "file9.txt" let file10 = "file10.txt" file9 < file10 // false file9.compare(file10) == .orderedAscending // false file9.compare(file10, options: .numeric) // ture // Diacritic Insensitive Option - 발음기호 무시 let a = "Cafe" let b = "Cafè" a == b // false a.compare(b) == .orderedSame // 실제 모양이 다르므로 false a.compare(b, options: .diacriticInsensitive) == .orderedSame // ture // Width insensitive Option - 전각, 반각문자 무시 let x = "\u{30A1}" let y = "\u{ff67}" x == y // false x.compare(y) == .orderedSame // false a.compare(b, options: .widthInsensitive) == .orderedSame // true // Forced Ordering Option - 전체 옵션 적용시 같은 문자열이라면 순서를 판단하기 위해 일부 옵션을 무시하고 정렬함 let upper = "STRING" let lower = "string" upper == lower upper.compare(lower, options: [.caseInsensitive]) == .orderedSame // true upper.compare(lower, options: [.caseInsensitive, .forcedOrdering]) == .orderedSame // false // Regular Expression Option - 정규식 옵션 let emailPattern = "([0-9a-zA-z_-]+)@([0-9a-zA-z_-]+){\\.[0-9a-zA-z_-]+)(1,2}" let emailAddress = "user@example.com" if let _ = emailAddress.range(of: emailPattern) { print("found") } else { print("not found") } // 바인딩 실패, 문자열 자체 비교 if let _ = emailAddress.range(of: emailPattern, options: .regularExpression) { print("found") } else { print("not found") } // found, 올바른 범위를 리턴하지만 올바른 이메일이라고 할 수는 없음 // 패턴이 존재한다면 그냥 리턴함. 이 경우 다시 한 번 확인 if let range = emailAddress.range(of: emailPattern, options: .regularExpression), (range.lowerBound, range.upperBound) == (emailAddress.startIndex, emailAddress.endIndex) { print("found") } else { print("not found") } // 범위가 일치하는지 튜플로 저장한 후 크기를 비교함 } func characterSet() { // 문자 집합. 문자열 검색이나 잘못된 문자 삭제시 사용 // CharacterSet -> 구조체로 선언되어 있음 let a = CharacterSet.uppercaseLetters // 대문자만 포함 let b = a.inverted // 나머지 모든 문자가 포함됨 var str = "loRem Ipsum" var charSet = CharacterSet.uppercaseLetters if let range = str.rangeOfCharacter(from: charSet) { print(str.distance(from: str.startIndex, to:range.lowerBound )) } // 2 if let range = str.rangeOfCharacter(from: charSet, options: .backwards) { print(str.distance(from: str.startIndex, to:range.lowerBound )) } // 6 str = " A p p l e " charSet = .whitespaces let trimmed = str.trimmingCharacters(in: charSet) print(trimmed) // 시작과 끝의 공백 제거 var editTarget = CharacterSet.uppercaseLetters editTarget.insert("#") // 문자 추가 editTarget.insert(charactersIn: "~!@") // 3개 추가 editTarget.remove("A") editTarget.remove(charactersIn: "BCD") // custom let customCharSet = CharacterSet(charactersIn: "@.") let email = "userId@example.com" let components = email.components(separatedBy: customCharSet) // 문자열 분리 후 리턴 // userID, example, com }
true
65067542e13ca469c1cedf9077a64adde6204a62
Swift
ahmedkhder/gd-ios
/GetDonate/GetDonate/NetworkLayer/DataDecodable.swift
UTF-8
540
2.796875
3
[]
no_license
// // DataDecode.swift // // Created by JMD on 11/09/19. // Copyright © 2019 JMD All rights reserved. // import Foundation ///- MARK: Data Decodable extension Data { func decode<T>(model: T.Type) throws -> T? where T : Decodable { if let modelDecodable = try? model.init(jsonData: self) { return modelDecodable } return nil } } extension Decodable { init(jsonData: Data) throws { let decoder = JSONDecoder() self = try decoder.decode(Self.self, from: jsonData) } }
true
ee0f39e072998d8172d65ad507dc1536e1661eb2
Swift
hi0617fu/ChatBluetooth
/ChatBluetooth/CentralViewController.swift
UTF-8
10,214
2.53125
3
[]
no_license
import Foundation import UIKit import CoreBluetooth import os var string: String! class CentralViewController: UIViewController { @IBOutlet weak var baseTableView: UITableView! @IBOutlet weak var refreshButton: UIBarButtonItem! var centralManager: CBCentralManager! //Core Bluetoothを始動させるための変数 var discoveredPeripheral: CBPeripheral! //connectするPeripheralを格納する変数 var start: Date! //Scanから検知までの時間を計測する変数 var start2: Date! //Tapから接続、キャラクタリスティクス読み込みまでの時間を計測する変数 var timer: Timer = Timer() //Scanの時間を決めるための変数 var myUuids: NSMutableArray = NSMutableArray() //見つけたPeripheralのUUIDを格納するArray(配列) var myPeripheral: NSMutableArray = NSMutableArray() //見つけたPeripheralのCBPeripheralを格納する配列 override func viewDidLoad() { // 画面に遷移した最初に行うこと.配列の初期化、tableViewの初期化、ボタンの配置、Scanの開始 myUuids = NSMutableArray() myPeripheral = NSMutableArray() self.baseTableView.delegate = self self.baseTableView.dataSource = self self.view.addSubview(baseTableView) let backButton = UIBarButtonItem(title: "Disconnect", style: .plain, target: nil, action: nil) navigationItem.backBarButtonItem = backButton self.retrievePeripheral() } override func viewWillDisappear(_ animated: Bool) { // 別の画面に映る瞬間に行うこと、保持していたPeripheralの情報を削除してtableviewから見れなくする. discoveredPeripheral = nil myUuids = [] myPeripheral = [] baseTableView.reloadData() super.viewWillDisappear(animated) } private func retrievePeripheral() { //Scan関数. timerを5秒に設定し、centralManagerを始動(①に移動).5秒経ったらstopscan関数を実行 print("retrieve") timer = Timer.scheduledTimer(timeInterval: 5.0,target: self, selector: #selector(self.stopscan), userInfo: nil, repeats: false) start = Date() centralManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey: true]) } @objc func stopscan() { //centralManagerのScanを止める print("5seconds stop Scan") centralManager.stopScan() } private func cleanup() { //.connected状態のPeripheralが存在すればそのPeripheralのservice,characteristicsを削除 guard let discoveredPeripheral = discoveredPeripheral, case .connected = discoveredPeripheral.state else { return } for service in (discoveredPeripheral.services ?? [] as [CBService]) { for characteristic in (service.characteristics ?? [] as [CBCharacteristic]) { if characteristic.uuid == TransferService.characteristic_UUID && characteristic.isNotifying { self.discoveredPeripheral?.setNotifyValue(false, for: characteristic) print("cleanup") } } } centralManager.cancelPeripheralConnection(discoveredPeripheral) } @IBAction func refreshAction(_ sender: AnyObject) { //一旦保持しているPeripheralの情報を削除してtableviewを更新してからScan再開 discoveredPeripheral = nil myUuids = [] myPeripheral = [] self.baseTableView.reloadData() self.retrievePeripheral() } } extension CentralViewController: CBCentralManagerDelegate { internal func centralManagerDidUpdateState(_ central: CBCentralManager) { //① 端末のBluetoothがONになっていればPeripheral端末の検知がstart.検知したら②に移動 switch central.state { case .poweredOn: os_log("CBManager is powered on") centralManager.scanForPeripherals(withServices: [TransferService.serviceUUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey: true]) case .poweredOff: os_log("CBManager is not powered on") return case .resetting: os_log("CBManager is resetting") return case .unauthorized: return case .unknown: os_log("CBManager state is unknown") return case .unsupported: os_log("Bluetooth is not supported on this device") return @unknown default: os_log("A previously unknown central manager state occurred") return } } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) { //②見つけたPeripheralのCBPeripheral,identifierをそれぞれmyPeripheral,myUuidsに格納.ただし、同じ名前のものは再び入らないようにする.格納されたら③に移動 guard RSSI.intValue >= -100 else { os_log("Discovered perhiperal not in expected range, at %d", RSSI.intValue) return } if (myUuids.contains(peripheral.identifier.uuidString) || myPeripheral.contains(peripheral)){ // スルー } else { os_log("Discovered %s at %d", String(describing: peripheral.name), RSSI.intValue) myPeripheral.add(peripheral) myUuids.add(peripheral.identifier.uuidString) //か、ここ } self.baseTableView.reloadData() let elapsed = Date().timeIntervalSince(start) print(elapsed) } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { //centralManager.connectが失敗したらここに来る.本来使わないゾーン os_log("Failed to connect to %@. %s", peripheral, String(describing: error)) cleanup() } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { os_log("Scanning stopped") //⑤接続したperipheralのserviceを探索serviceを見つけたら⑥に移動 peripheral.delegate = self peripheral.discoverServices([TransferService.serviceUUID]) } func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { //Peripheralとの接続を削除 os_log("Perhiperal Disconnected") discoveredPeripheral = nil } } extension CentralViewController: CBPeripheralDelegate { func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { if let error = error { os_log("Error discovering services: %s", error.localizedDescription) cleanup() return } //⑥service内のcharacteristicsを探索.見つけたら⑦に移動 peripheral.discoverCharacteristics([TransferService.characteristic_UUID], for: (peripheral.services?.first)!) } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { if let error = error { os_log("Error discovering characteristics: %s", error.localizedDescription) cleanup() return } //⑦見つけたcharacteristicsを通知する.通知がきたら⑧に移動 peripheral.setNotifyValue(true, for: (service.characteristics?.first)!) } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if let error = error { os_log("Error discovering characteristics: %s", error.localizedDescription) cleanup() return } //⑧受け取ったcharacteristicをstring型に直してチャットボックスに遷移 guard let characteristicData = characteristic.value, let stringFromData = String(data: characteristicData, encoding: .utf8) else { return } os_log("Received %d bytes: %s", characteristicData.count, stringFromData) string = stringFromData let elapsed2 = Date().timeIntervalSince(start2) print("end," ,elapsed2) performSegue(withIdentifier: "CentralChatBox", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { //チャットボックスに遷移する際に、受け取ったcharacteristicをCentralChatBox内でも使えるように準備 if (segue.identifier == "CentralChatBox") { let vc2: CentralChatBox = (segue.destination as? CentralChatBox)! vc2.udidData = string } } } extension CentralViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //③格納されたmyUuidsの数をそのままcellの個数に反映させる return myUuids.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //③格納されたmyUuidsをtableViewに表示.ユーザがそれをタップしたら④に移動 let cell = tableView.dequeueReusableCell(withIdentifier: "BlueCell") as! PeripheralTableViewCell cell.peripheralLabel!.text = "\(myUuids[indexPath.row])" return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //④centralManagerのScanを止めて選択したPeripheralと接続.接続されたら⑤に移動 self.discoveredPeripheral = myPeripheral[indexPath.row] as? CBPeripheral centralManager.stopScan() start2 = Date() centralManager.connect(self.discoveredPeripheral, options: nil) print("connect") tableView.deselectRow(at: indexPath, animated: true) } }
true
724844484544b0a1ebd0b011ebd02d5ca79d4106
Swift
miscy210/SwiftPractice
/Project38_NightMode/NightMode/ViewController.swift
UTF-8
4,052
3
3
[]
no_license
// // ViewController.swift // NightMode // // Created by baiwei-mac on 17/1/6. // Copyright © 2017年 YuHua. All rights reserved. // import UIKit /*夜间模式,实现思路: 1.配置夜间和白天的数据,分别保存 2.配置数据时,通过单例manager的一个方法去取数据,该方法内判断是否是夜间模式,返回不同的数据 3.用户点击切换后,需要: 1.把manager的是否是夜间模式标志位切换 2.截取当前屏幕,覆盖到最上层,然后图片用动画fadeOut消失----这一步不是必须,只是让变化更加平滑 3.将主题变化了通知到其它view,其它view刷新 4.应该把manager的判断是否是夜间模式的字段保存到配置文件中,下次打开app记录上次退出时的状态 */ let YHRect = UIScreen.main.bounds let YHHeight = YHRect.size.height let YHWidth = YHRect.size.width let YHNoNavRect = CGRect(x: 0, y: 0, width: YHWidth, height: YHHeight - 64) let YHNoTarRect = CGRect(x: 0, y: 0, width: YHWidth, height: YHHeight - 49) let YHNoNavTarRect = CGRect(x: 0, y: 0, width: YHWidth, height: YHHeight - 49 - 64) class ViewController: CustomSupVC { let label = UILabel(frame: CGRect(x: 10, y: 20, width:YHWidth-20, height:300)) let imageView = UIImageView(frame: CGRect(x: 30, y: 320, width: YHWidth-60, height: 200)) override func viewDidLoad() { super.viewDidLoad() setupView() setViewColor() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupView() { label.textAlignment = .left label.numberOfLines = 0//如果指定为0,则label可以自动换行,多行显示,知道不能显示完为止。 label.text = "夜间模式,实现思路:\n1.配置夜间也白天的,分别保存\n2.配置数据时,通过单例manager的一个方法去取数据,该方法内判断是否是夜间模式,返回不同的数据\n3.用户点击切换后,需要:\n 1.把manager的是否是夜间模式标志位切换\n 2.截取当前屏幕,覆盖到最上层,然后图片用动画fadeOut消失\n 3.将主题变化了通知到其它view,其它view刷新\n4.应该把manager的判断是否是夜间模式的字段保存到配置文件中,下次打开app记录上次退出时的状态" let witch = UISwitch() witch.center = CGPoint(x: view.center.x, y:YHHeight-80) witch.addTarget(self, action: #selector(changeNight(sender:)), for: .valueChanged) view.addSubview(witch) view.addSubview(label) view.addSubview(imageView) } @objc func changeNight(sender: UISwitch) { fadeAnimation() NightManager.sharedInstance.isNight = sender.isOn NotificationCenter.default.post(name: NSNotification.Name(NightChange), object: nil) } //渐变动画 func fadeAnimation() { //模拟器是无法看到快照的,真机可以看到,模拟器运行屏幕会闪一下就是这个原因 let snaphot = UIApplication.shared.keyWindow?.snapshotView(afterScreenUpdates: false) UIApplication.shared.keyWindow?.addSubview(snaphot!) UIView.animate(withDuration: 0.3, animations: { snaphot?.alpha = 0 }) { (_) in snaphot?.removeFromSuperview() } } override func setViewColor() { //改变状态栏 setNeedsStatusBarAppearanceUpdate() imageView.image = NightManager.sharedInstance.image(name: "image1") view.backgroundColor = NightManager.sharedInstance.color(color: "white") label.textColor = NightManager.sharedInstance.color(color: "orange") tabBarController?.tabBar.backgroundColor = NightManager.sharedInstance.color(color: "gray") tabBarController?.tabBar.tintColor = NightManager.sharedInstance.color(color: "blue") } }
true
22b1763efa41a58f73e1e8085946a5d67a97e115
Swift
op2b/ToDoFire
/ToDoFire/Controller/TasksViewController.swift
UTF-8
4,109
2.75
3
[]
no_license
import UIKit import Firebase import FirebaseAuth import FirebaseDatabase class TasksViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var user: UserI! var ref: DatabaseReference! var taskArray = Array<Task>() override func viewDidLoad() { super.viewDidLoad() guard let correntUser = Auth.auth().currentUser else {return} user = UserI(user: correntUser) ref = Database.database().reference(withPath: "users").child(String(user.uid)).child("tasks") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) ref.observe(.value, with: { (snapShot) in var _tasks = Array<Task>() for i in snapShot.children { let task = Task(snapshot: i as! DataSnapshot) _tasks.append(task) } self.taskArray = _tasks self.tableView.reloadData() }) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) ref.removeAllObservers() } //кол-во ячеек (обязательный метод) func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return taskArray.count } //что мы будем отоброжать внутри ячийки (обязатльный метод) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let task = taskArray[indexPath.row] let taskTitel = task.title let isComplited = task.complited cell.backgroundColor = .clear cell.textLabel?.textColor = .white cell.textLabel?.text = taskTitel toogleComplition(cell, isComplited: isComplited ) return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } //delete cell func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let task = taskArray[indexPath.row] task.ref?.removeValue() } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let cell = tableView.cellForRow(at: indexPath) else {return} let task = taskArray[indexPath.row] let isComplited = !task.complited toogleComplition(cell, isComplited: isComplited) task.ref?.updateChildValues(["complited": isComplited]) } func toogleComplition(_ cell: UITableViewCell, isComplited:Bool) { cell.accessoryType = isComplited ? .checkmark : .none } @IBOutlet weak var tableView: UITableView! @IBAction func addTapped(_ sender: UIBarButtonItem) { let ac = UIAlertController(title: "New Task", message: "Add new task", preferredStyle: .alert) ac.addTextField() let save = UIAlertAction(title: "Save", style: .default) { [weak self] _ in guard let textField = ac.textFields?.first, textField.text != "" else { return } let task = Task(titel: textField.text!, userID: (self?.user.uid)!) let taskRef = self?.ref.child(task.title.lowercased()) taskRef?.setValue(task.converToDictionary()) } let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil) ac.addAction(save) ac.addAction(cancel) present(ac, animated: true, completion: nil) } @IBAction func signOutTapped(_ sender: UIBarButtonItem) { do { try Auth.auth().signOut() } catch { print(error.localizedDescription) } dismiss(animated: true, completion: nil) } }
true
47f568fef7f5a57dbd82a95c60f7bfd471f2132d
Swift
mzyy94/Capriccio
/Capriccio/MusicStoreManager/MusicTrackInformation.swift
UTF-8
1,131
2.5625
3
[ "MIT" ]
permissive
// // MusicTrackInformation.swift // Capriccio // // Created by Yuki MIZUNO on 6/30/15. // Copyright (c) 2015 Yuki MIZUNO. All rights reserved. // import UIKit class MusicTrackInformation: NSObject { // MARK: - Instance fileds var trackId: Int var trackName: String var artistName: String var collectionName: String? var collectionArtistName: String? var trackPrice: Float var currency: String var artworkUrl: NSURL? var previewUrl: NSURL? var trackViewUrl: NSURL // MARK: - Initialization init(fromDictionary dict: NSDictionary) { self.trackId = dict["trackId"]!.integerValue self.trackName = dict["trackName"] as! String self.artistName = dict["artistName"] as! String self.collectionName = dict["collectionName"] as? String self.collectionArtistName = dict["collectionArtistName"] as? String self.trackPrice = dict["trackPrice"]!.floatValue self.currency = dict["currency"] as! String self.artworkUrl = NSURL(string: dict["artworkUrl100"] as! String) self.previewUrl = NSURL(string: dict["previewUrl"] as! String) self.trackViewUrl = NSURL(string: dict["trackViewUrl"] as! String)! } }
true
b35795026c2a2de78d7cf6a0e43d7859c1fd0133
Swift
nucci/swift-tour
/SwiftTour.playground/Pages/Enums.xcplaygroundpage/Contents.swift
UTF-8
2,538
4.78125
5
[]
no_license
//: [Closures](@previous) /*: ## Enum >Enum (ou enumerado) é um tipo utilizado para definir uma lista de valores. Podemos fazer uma analogia com o mundo do desenvolvimento web e dizer que toda vez que usaríamos um dropdown de valores na web, podemos usar Enums na Swift. >Uma enumeração pode armazenar valores de qualquer tipo e os tipos destes valores podem ser diferentes para cada membro da enumeração. Para declarar um Enum, utilizamos a palavra enum, seguida do nome que daremos ao nosso Enum. Dentro do bloco, utilizamos case (sim, igual ao do switch) para cada opção. */ //: Declarando um Enum enum CompassPoint { case north case south case east case west } enum Planet { case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune } //: Utilizando um enum var direction = CompassPoint.west direction = .east //: Para extrairmos os valores inseridos em um enum, utilizamos switch direction = .south switch direction { case .north: print("Rumo ao norte") case .south: print("Pinguins") case .east: print("Onde o Sol nasce") case .west: print("Onde o céu é azul") } let somePlanet = Planet.earth switch somePlanet { case .earth: print("Planeta azul") default: print("Não conheço") } //: Também podemos declarar Enums que recebem diferentes tipos: /*: >Podemos utilizar Enums de maneira fortemente tipada, fazendo com que seus valores sejam sempre do mesmo tipo. >Se utilizarmos inteiros, os valores são auto-incrementados se uma sequência não for informada. Não é possível declarar valores iguais. */ // Associated Values enum Barcode { case upc(Int, Int, Int, Int) case qrCode(String) } var productBarcode = Barcode.upc(8, 85909, 51226, 3) //productBarcode = .qrCode("ABCDEFGHIJKLMNOP") switch productBarcode { case .upc(let numberSystem, let manufacturer, let product, let check): print("UPC: \(numberSystem), \(manufacturer), \(product), \(check)") case .qrCode(let productCode): print("QR code: \(productCode).") } // Raw Values enum ASCIIControlCharacter: Character { case tab = "\t" case lineFeed = "\n" case carriageReturn = "\r" } // Implicitly Assigned Raw Values enum PlanetRaw: Int { case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune } let earthsOrder = PlanetRaw.earth.rawValue // earthsOrder é 3 enum CompassPointRaw: String { case north, south, east, west } let sunsetDirection = CompassPointRaw.west.rawValue // sunsetDirection é "west" //: [Structure and Classes](@next)
true
ac35ac2c9e7a0198869559c380d6aeb0bc5006c7
Swift
djk12587/BasicNetworkingLayer
/NetworkingExample/Networking/Networking.swift
UTF-8
2,163
2.6875
3
[]
no_license
// // Networking.swift // NetworkingExample // // Created by Daniel Koza on 2/10/20. // Copyright © 2020 Daniel Koza. All rights reserved. // import Foundation extension NetworkRouterCodable { @discardableResult func request(completion: @escaping (Result<ModelType, Error>) -> Void) -> URLRequest? { do { let request = try asURLRequest() session.dataTask(with: request) { (responseData, response, error) in if let error = error { DispatchQueue.main.async { completion(.failure(error)) } return } else if let responseData = responseData { let serializedResponse: Result<ModelType, Error> = responseData.serializeModel() DispatchQueue.main.async { completion(serializedResponse) } } else { DispatchQueue.main.async { completion(.failure(NetworkingError.invalidRequest)) } } } return request } catch let error { DispatchQueue.main.async { completion(.failure(error)) } return nil } } @discardableResult func requestCollection(completion: @escaping (Result<[ModelType], Error>) -> Void) -> URLRequest? { do { let request = try asURLRequest() session.dataTask(with: request) { (responseData, response, error) in if let error = error { DispatchQueue.main.async { completion(.failure(error)) } return } else if let responseData = responseData { let serializedResponse: Result<[ModelType], Error> = responseData.serializeModels() DispatchQueue.main.async { completion(serializedResponse) } } else { DispatchQueue.main.async { completion(.failure(NetworkingError.invalidRequest)) } } } return request } catch let error { DispatchQueue.main.async { completion(.failure(error)) } return nil } } }
true
478064f4313c14d9fa78f6a17cef0029e1648873
Swift
SangHwi-Back/MommyTalk
/MommyTalk/View/InitialConfirmView.swift
UTF-8
7,316
2.734375
3
[]
no_license
// // InitialConfirmView.swift // MommyTalk // // Created by 백상휘 on 2020/08/18. // Copyright © 2020 Sanghwi Back. All rights reserved. // referenced ::: https://mildwhale.github.io/2020-03-12-Interfacing-with-UIKit-1/ // import UIKit import SwiftUI import Combine struct InitialConfirmView<Page: View>: View { @State var policyShow: Bool = false @State var privateAgreementShow: Bool = false @State var eventNotificationShow: Bool = false @State var currentIndex: Int = 0 @EnvironmentObject var appEnvironmentObject: AppEnvironmentObject var viewControllers: [UIHostingController<Page>] init(_ views: [Page]) { self.viewControllers = views.map{ UIHostingController(rootView: $0) } } var body: some View { VStack{ ZStack { PageViewController(controllers: viewControllers, currentIndex: self.$currentIndex) VStack { Spacer() HStack(spacing: 10) { ForEach(0..<viewControllers.count, id: \.self) { Circle().frame(width: 10, height: 10) .foregroundColor($0 == self.currentIndex ? Color(UIColor.brown) : Color(UIColor.gray)) } }.padding() } } HStack(spacing: 10) { //이용약관, 개인정보 수집/ 띄고 이용 및 이벤트 정보 수신 VStack { HStack(spacing:2) { Button(action: { self.policyShow = true }, label: { Text("이용약관") }).sheet(isPresented: self.$policyShow) { DetailActionSheet(header: "서비스 이용약관", content: Model.policyShowContent) } Text(",") Button(action: { self.privateAgreementShow = true }, label: { Text("개인정보 수집/이용") }).sheet(isPresented: self.$privateAgreementShow) { DetailActionSheet(header: "개인정보 수집/이용 동의", content: Model.privateAgreementContent) } Text(",") } Button(action: { self.eventNotificationShow = true }, label: { Text("이벤트 정보 수신") }).sheet(isPresented: self.$eventNotificationShow) { DetailActionSheet(header: "이벤트 정보 수신", content: Model.eventNotificationContent) } } .font(.caption) Button(action: { UserDefaults.standard.set(true, forKey: "isConfirmed") self.appEnvironmentObject.isConfirmed = true }, label: { Text("동의하고 시작하기") .frame(width: 150, height: 50, alignment: .center) .font(.footnote) }) .foregroundColor(.white) .background(Color(UIColor.brown)) .cornerRadius(30) .padding(2) } } } } struct InitialConfirmView_Previews: PreviewProvider { static var previews: some View { InitialConfirmView(["DetailInitialConfirmImage1Cropped","DetailInitialConfirmImage2Cropped","DetailInitialConfirmImage3Cropped" ].map({DetailInitialConfirmView(imageName: $0)})) } } struct PageViewController: UIViewControllerRepresentable { var controllers: [UIViewController] @Binding var currentIndex: Int func makeUIViewController(context: Context) -> UIPageViewController { let pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal) pageViewController.dataSource = context.coordinator //dataSource 설정 pageViewController.delegate = context.coordinator return pageViewController } func updateUIViewController(_ uiViewController: UIPageViewController, context: Context) { DispatchQueue.main.async { uiViewController.setViewControllers([self.controllers[self.currentIndex]], direction: .forward, animated: true) self.$currentIndex.wrappedValue = context.coordinator.currentIndex } } func makeCoordinator() -> Coordinator { Coordinator(self, currentIndex: $currentIndex) } class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate { var parent: PageViewController @Binding var currentIndex: Int init(_ pageViewController: PageViewController, currentIndex: Binding<Int>) { self.parent = pageViewController self._currentIndex = currentIndex } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = parent.controllers.firstIndex(of: viewController) else { return nil } // 내가 보고 있는 뷰컨트롤러의 인덱스 print("viewControllerBefore") if index == 0 { return nil } return parent.controllers[index - 1] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = parent.controllers.firstIndex(of: viewController) else { return nil } print("viewControllerAfter") if index + 1 == parent.controllers.count { return nil } return parent.controllers[index + 1] } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if !completed { return } self.currentIndex = parent.controllers.firstIndex(of: pageViewController.viewControllers!.first!) ?? 0 } } } struct DetailInitialConfirmView: View { let imageName: String init(imageName: String) { self.imageName = imageName } var body: some View { Image(imageName) } } struct DetailActionSheet: View { let header: String let content: String init(header: String, content: String) { self.header = header self.content = content } var body: some View { List { Text(header).font(.headline) if header == "서비스 이용약관" { Text("제1장 총칙").font(.subheadline) } ScrollView { Text(content).font(.body) } } } }
true
7abb16e87c8cf4a20b4b24753fc0d0b3413745b9
Swift
hoangtuanfithou/weather
/Weather/Weather/Model/DKCity.swift
UTF-8
890
2.640625
3
[]
no_license
// // DKCity.swift // // Created by NHT on 9/6/17. // Copyright © 2017 NHT. All rights reserved. // import Foundation import ObjectMapper import Alamofire class DKCity: BaseModel, DKCityProtocol { var lat: Double? var lon: Double? var name: String? var weatherInfoDidChange: ((DKCityProtocol) -> ())? var request: Request? var weather: DKWeatherResponse? { get { if weatherResponse == nil && request?.task?.state != .running { requestWeatherInfo() } return weatherResponse } } internal var weatherResponse: DKWeatherResponse? { didSet { weatherInfoDidChange?(self) } } override func mapping(map: Map) { super.mapping(map: map) lat <- map["lat"] lon <- map["lon"] name <- map["name"] } }
true
2990e74645cac47a4774f547bc8c9d5cce0a5edd
Swift
Panosstylianou/projproj
/Learnoid/MainVC.swift
UTF-8
7,327
2.671875
3
[]
no_license
// // ViewController.swift // Learnoid // // Created by Panayiotis Stylianou on 02/11/2015. // Copyright © 2015 Panayiotis Stylianou. All rights reserved. // import Cocoa import Carbon import AppKit class MainVC: NSViewController { @IBOutlet weak var firstLabel: NSTextField! @IBOutlet weak var secondLabel: NSTextField! @IBOutlet weak var thirdLabel: NSTextField! @IBOutlet weak var largeImage: NSImageView? @IBOutlet weak var smallImage: NSImageView? var count: Int = 0 var lesson :NSMutableArray = [] var picture :NSMutableArray = [] var zoomed :Bool = false // var lessonObj:Lesson = Lesson.init(name: "Lesson1") override func viewDidLoad() { super.viewDidLoad() count = -1 // Do any additional setup after loading the view. } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } func populateLesson(){ let array :NSMutableArray = [] array.addObject("Step 1") array.addObject("Step 2") array.addObject("Step 3") array.addObject("Step 4") array.addObject("Step 5") array.addObject("Step 6") let pictures:NSMutableArray = [] pictures.addObject(NSImage(named: "image1")!) pictures.addObject(NSImage(named: "image2")!) pictures.addObject(NSImage(named: "image3")!) pictures.addObject(NSImage(named: "image4")!) pictures.addObject(NSImage(named: "image5")!) pictures.addObject(NSImage(named: "image6")!) // lessonObj.addStep("Step1", image: NSImage(named: "image1")!) // lessonObj.addStep("Step2", image: NSImage(named: "image2")!) No Lesson Object // lessonObj.addStep("Step3", image: NSImage(named: "image3")!) // lessonObj.addStep("Step4", image: NSImage(named: "image4")!) // lessonObj.addStep("Step5", image: NSImage(named: "image5")!) // lessonObj.addStep("Step6", image: NSImage(named: "image6")!) lesson = array picture = pictures // let dir = NSString(string:"~/Desktop").stringByExpandingTildeInPath // // NSKeyedArchiver.archiveRootObject(lessonObj, toFile: dir + lessonObj.name) // let data = NSKeyedArchiver.archivedDataWithRootObject(lessonObj) // data.writeToFile(dir, atomically: true) // lessonObj.save() // No Lesson Object } func getDocumentsDirectory() -> String { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let documentsDirectory = paths[0] return documentsDirectory } func addPicture(picture : NSImage){ smallImage!.image = picture smallImage!.hidden = false largeImage!.hidden = true zoomed = false largeImage!.image = nil smallImage!.layer = CALayer() } func addZoomedPicture(picture : NSImage){ largeImage!.image = picture largeImage!.hidden = false smallImage!.hidden = true zoomed = true smallImage!.image = nil largeImage!.layer = CALayer() } func hotkeyWithEventZ(hkEvent : NSEvent){ if(count>0){ count-- // // let dictionary = lessonObj.data.objectAtIndex(count) // let str = dictionary["text"] // let image = dictionary["image"]! // // // addOutput(str as!String) // addPicture(image as! NSImage ) // No Lesson Object } } func hotkeyWithEventX(hkEvent : NSEvent){ // if(count<lessonObj.data.count-1){ No Lesson Object // count++ // // let dictionary = lessonObj.data.objectAtIndex(count) // let str = dictionary["text"] // let image = dictionary["image"]! // // addOutput(str as! String) // addPicture(image as! NSImage) // }else{ // addOutput("Lesson Finished") // count = lessonObj.data.count // } } func hotkeyWithEventC(hkEvent : NSEvent){ if(!zoomed){ addZoomedPicture((smallImage?.image)!) }else{ addPicture((largeImage?.image)!) } } @IBAction func goToWebsite (sender: AnyObject) { self.performSegueWithIdentifier("websiteSegue", sender: nil) } @IBAction func create(sender: AnyObject) { unregister() self.performSegueWithIdentifier("createSegue", sender: nil) } @IBAction func lessons(sender: AnyObject) { self.performSegueWithIdentifier("lessonsSegue", sender: nil) } @IBAction func start(sender: AnyObject) { self.populateLesson() let z: DDHotKeyCenter = DDHotKeyCenter.sharedHotKeyCenter() if((z.registerHotKeyWithKeyCode(UInt16(kVK_ANSI_Z), modifierFlags: NSEventModifierFlags.ControlKeyMask.rawValue, target: self, action: Selector("hotkeyWithEventZ:"), object: nil) == nil)){ print("Unable to register") }else{ } let x: DDHotKeyCenter = DDHotKeyCenter.sharedHotKeyCenter() if((x.registerHotKeyWithKeyCode(UInt16(kVK_ANSI_X), modifierFlags: NSEventModifierFlags.ControlKeyMask.rawValue, target: self, action: Selector("hotkeyWithEventX:"), object: nil) == nil)){ print("Unable to register") }else{ } let c: DDHotKeyCenter = DDHotKeyCenter.sharedHotKeyCenter() if((c.registerHotKeyWithKeyCode(UInt16(kVK_ANSI_C), modifierFlags: NSEventModifierFlags.ControlKeyMask.rawValue, target: self, action: Selector("hotkeyWithEventC:"), object: nil) == nil)){ print("Unable to register") }else{ } // } // _btnStart.setTransparent(true) // _btnStart.setHidden(true) // _btnStart.setEnabled(false) } func addOutput(newOutput: String) { firstLabel.stringValue = newOutput if count > 0 { // secondLabel.stringValue = lessonObj.data.objectAtIndex(count-1)["text"] as! String // No Lesson Object }else{ secondLabel.stringValue = "" } if count > 1 { // thirdLabel.stringValue = lessonObj.data.objectAtIndex(count-2)["text"] as! String // No Lesson Object }else{ thirdLabel.stringValue = "" } } func unregister(){ let x : DDHotKeyCenter = DDHotKeyCenter.sharedHotKeyCenter() let z : DDHotKeyCenter = DDHotKeyCenter.sharedHotKeyCenter() let c : DDHotKeyCenter = DDHotKeyCenter.sharedHotKeyCenter() c.unregisterHotKeyWithKeyCode(UInt16(kVK_ANSI_C), modifierFlags: NSEventModifierFlags.ControlKeyMask.rawValue) x.unregisterHotKeyWithKeyCode(UInt16(kVK_ANSI_X), modifierFlags: NSEventModifierFlags.ControlKeyMask.rawValue) z.unregisterHotKeyWithKeyCode(UInt16(kVK_ANSI_Z), modifierFlags: NSEventModifierFlags.ControlKeyMask.rawValue) print("Unregistered") } }
true
a65790555887645fa47f1bce63b62668b403157e
Swift
TomGarske/Simple-iOS-Client
/simple ios client/ProfileViewController.swift
UTF-8
979
2.609375
3
[]
no_license
// // ProfileViewController.swift // simple ios client // // Created by Thomas Garske on 12/12/16. // Copyright © 2016 csci4211. All rights reserved. // import UIKit class ProfileViewController: UIViewController { @IBOutlet weak var usernameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() usernameLabel.text = "UserID: " + String(self.getUserId()) } @IBAction func didTapLogout(_ sender: Any) { let alert = UIAlertController(title: "Confirm Logout", message: "Are you sure you want to log out?", preferredStyle:.alert) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil)); alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: {(action:UIAlertAction) in self.dismiss(animated: true, completion: nil) })); present(alert, animated: true, completion: nil); } }
true
d915349bc688d85c56dde583b83b47e32c309e6e
Swift
edenerio/Tip-Calculator
/Tip Calculator/SettingsViewController.swift
UTF-8
4,360
2.75
3
[ "Apache-2.0" ]
permissive
// // SettingsViewController.swift // Tip Calculator // // Created by Edison Enerio on 4/11/21. // import UIKit class SettingsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listCurrencies.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let listCell = tableView.dequeueReusableCell(withIdentifier: "supportedCurrencies", for: indexPath) listCell.textLabel!.text = String( listCurrencies[indexPath.row].currName) return listCell } @IBOutlet weak var darkMode: UISwitch! @IBOutlet weak var defRateLeft: UILabel! @IBOutlet weak var defRateMid: UILabel! @IBOutlet weak var defRateRight: UILabel! @IBOutlet weak var newRateLeft: UITextField! @IBOutlet weak var newRateMid: UITextField! @IBOutlet weak var newRateRight: UITextField! @IBOutlet var dropDownCurr: UITableView!{ didSet { dropDownCurr.dataSource = self dropDownCurr.delegate = self dropDownCurr.remembersLastFocusedIndexPath = true } } override func viewDidLoad() { super.viewDidLoad() newRateLeft.becomeFirstResponder() //to check if dark mode is enabled if dm.isDarkM { overrideUserInterfaceStyle = .dark darkMode.setOn(true, animated: true) } else { overrideUserInterfaceStyle = .light } //to show default rates defRateLeft.text = String(currDefaults[0] * 100) defRateMid.text = String(currDefaults[1] * 100) defRateRight.text = String(currDefaults[2] * 100) darkMode.addTarget(self, action: #selector(isDarkMode), for: .valueChanged) self.title = "Settings" // Do any additional setup after loading the view. } @IBAction func saveButton(_ sender: Any) { //to check if user has input on new default rates let tempLeft = Double(newRateLeft.text!) ?? 0 let newLeft = tempLeft / 100 let tempMid = Double(newRateMid.text!) ?? 0 let newMid = tempMid / 100 let tempRight = Double(newRateRight.text!) ?? 0 let newRight = tempRight / 100 if isEmpty(newRateLeft){ currDefaults[0] = newLeft }; if isEmpty(newRateMid) { currDefaults[1] = newMid }; if isEmpty(newRateRight) { currDefaults[2] = newRight } //to check if user changed the currency let currentIndex = dropDownCurr.indexPathForSelectedRow?.row currCurrency = listCurrencies[currentIndex ?? defaultIndex] if currentIndex != nil && currentIndex != 0{ defaultIndex = currentIndex ?? 0 customCurrency = true } else if currentIndex != nil && customCurrency == false{ currCurrency = listCurrencies[defaultIndex] } else if currentIndex == 0{ customCurrency = false } viewDidLoad() } //to keep track of total currencies supported func numberOfCurrencySupported(tableView: UITableView) -> Int { return Currency.numOfSupportedCurrencies } //to keep the dark mode switch updated @IBAction func isDarkMode(_ sender: Any){ if darkMode.isOn { dm.isDarkM = true viewDidLoad() } else { dm.isDarkM = false viewDidLoad() } } //to check if the user did not provide any input on the new default rate text fields func isEmpty (_ textField: UITextField) -> Bool { if let text = textField.text, !text.isEmpty{ return true } else { return false } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
true
d6a602d7cfed2ee514c3bb48006820460d33f7cd
Swift
marian19/Weather
/Weather/Weather/Data Layer/RemoteDataSource/HttpClient/AlamofireClient.swift
UTF-8
1,738
3.171875
3
[]
no_license
// // AlamofireClient.swift // Weather // // Created by Marian on 6/8/18. // Copyright © 2018 Marian. All rights reserved. // import Foundation import Alamofire struct AlamofireClient { // MARK: - Shared Instance static let sharedInstance = AlamofireClient() private init() { } func getRequest(path: String, parameters: [String: Any]?, completion:@escaping (Data?, Error?) -> Void) { ActivityIndicator().show() let url = Constants.baseURL + path + "&units=metric&appid=" + Constants.apiKey Alamofire.request(url, parameters: parameters, headers: nil).responseJSON { response in ActivityIndicator().hide() let statusCode = response.response?.statusCode print(statusCode ?? "statusCode default value") guard response.result.isSuccess else { print("Error while fetching : \(String(describing: response.result.error))") return } guard statusCode == 200, response.result.error == nil else { completion(nil, response.result.error) return } completion(response.data, nil) } } func downloadImageWith(icon: String,completion:@escaping (UIImage?, Error?) -> Void){ let url:String = "\(Constants.iconsBaseURL)\(icon).png" Alamofire.request(url).responseData(completionHandler: { response in if let imageData = response.result.value { let image = UIImage(data: imageData) completion(image,response.error) } completion(nil,response.error) }) } }
true
ca4895f7b8a7a622bb1c7e77502cbc59e79fb901
Swift
ArtemB49/ComputerDatabase
/ComputerDatabase/Flows/Controllers/Computer/ComputerBuilder/ComputerDefaultBuilder.swift
UTF-8
762
2.78125
3
[]
no_license
/** * Реализация билдера контроллера компьютера */ import Foundation import UIKit class ComputerDefaultBuilder: ComputerBuilder { private let computerID: Int init(computerID: Int) { self.computerID = computerID } func build() -> UIViewController { guard let viewController = UIStoryboard(name: "Computer", bundle: nil).instantiateViewController(withIdentifier: "ComputerViewController") as? ComputerViewController else { return ComputerViewController() } let router = CardDefaultRouter(viewController: viewController) viewController.cardRouter = router viewController.computerID = computerID return viewController } }
true
0eacd68c2f09201ac8fd4ee4f65238a01adf7e26
Swift
Freeway1979/ReactNativeApp
/ios/Common/Localize/Localize.swift
UTF-8
1,938
3.0625
3
[ "MIT" ]
permissive
// // Localize.swift // Study // // Copyright © 2020 Study. All rights reserved. // import Foundation /// Default language. English. If English is unavailable defaults to base localization. let localizedDefaultLanguage = "en" /// Base bundle as fallback. let baseBundle = "Base" /// Name for language change notification public let languageChangeNotification = "LanguageChangeNotification" extension Notification.Name { static let currentLanguageChanged = Notification.Name(rawValue: languageChangeNotification) } class Localize { class func availableLanguages(_ excludeBase: Bool = false) -> [String] { var availableLanguages = Bundle.main.localizations if let indexOfBase = availableLanguages.firstIndex(of: "Base"), excludeBase == true { availableLanguages.remove(at: indexOfBase) } return availableLanguages } class func currentLanguage() -> String { // TODO: return "en" } class func setCurrentLanguage(_ language: String) { let selectedLanguage = availableLanguages().contains(language) ? language : defaultLanguage() if selectedLanguage != currentLanguage() { // TODO: set language NotificationCenter.default.post(name: .currentLanguageChanged, object: nil) } } class func defaultLanguage() -> String { var defaultLanguage = String() guard let preferredLanguage = Bundle.main.preferredLocalizations.first else { return defaultLanguage } let availableLanguages: [String] = self.availableLanguages() if availableLanguages.contains(preferredLanguage) { defaultLanguage = preferredLanguage } else { defaultLanguage = localizedDefaultLanguage } return defaultLanguage } class func resetCurrentLanguageToDefault() { setCurrentLanguage(self.defaultLanguage()) } }
true
7bb27052074b5221ea802302b2a92155838fb8d8
Swift
vgladush/Swift-iOS
/d01/ex02/Value.swift
UTF-8
338
2.8125
3
[]
no_license
public enum Value: Int { case two = 2 case three = 3 case four = 4 case five = 5 case six = 6 case seven = 7 case eight = 8 case nine = 9 case ten = 10 case jack = 11 case queen = 12 case king = 13 case ace = 14 static let allValues: [Value] = [two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace] }
true
ea63a442697a2c9f956062a8bc23e0c9f28ab94d
Swift
wircho/URLSessionSync
/Sources/URLSessionSync/HTTPHeaders.swift
UTF-8
798
3.421875
3
[]
no_license
// // HTTPHeaders.swift // /** Initialize by: - `["A": "1", "B": "2"]` (`HTTPHeaders` conforms to `ExpressibleByDictionaryLiteral`) - `HTTPHeaders.from(value)` where `value` is `Encodable` to a JSON object of type `[String: String]` */ public enum HTTPHeaders { case dictionary([String: String]) } extension HTTPHeaders: ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, String)...) { self = .dictionary(.init(uniqueKeysWithValues: elements)) } } public extension HTTPHeaders { static func from<T: Encodable>(_ value: T) throws -> HTTPHeaders { return try .dictionary(value.converted()) } } internal extension HTTPHeaders { var dictionary: [String: String] { switch self { case .dictionary(let dictionary): return dictionary } } }
true
83a8e97abc3eda2ac5dc3a553a87072d383a3390
Swift
Maheshme/CircleBinder
/Binder/ViewController.swift
UTF-8
1,034
2.8125
3
[]
no_license
// // ViewController.swift // Binder // // Created by Mahesh.me on 1/19/17. // Copyright © 2017 Mahesh.me. All rights reserved. // import UIKit class ViewController: UIViewController { var bind: Bind! var curveBinder: CurveBinder! override func loadView() { self.view = UIView.init(frame: UIScreen.main.bounds) self.view.backgroundColor = UIColor.white bind = Bind.init(frame: CGRect.zero) self.view.addSubview(bind) curveBinder = CurveBinder.init(frame: CGRect.zero) self.view.addSubview(curveBinder) } override func viewWillLayoutSubviews() { bind.frame = CGRect.init(x: 0, y: 0, width: self.view.frame.size.width/2, height: self.view.frame.size.width/2) bind.center = CGPoint.init(x: self.view.frame.size.width/2, y: self.view.frame.size.height/4) curveBinder.frame = CGRect.init(x: 0, y: self.view.frame.size.height/2, width: self.view.frame.size.width, height: self.view.frame.size.height/2) } }
true
8118fbbd9c1350ad33af6c916abba3411104d98e
Swift
memof90/chatBox
/chatBox/Respuesta.swift
UTF-8
952
3.296875
3
[]
no_license
// // Respuesta.swift // chatBox // // Created by Memo Figueredo on 1/25/19. // Copyright © 2019 Memo Figueredo. All rights reserved. // import Foundation struct Respuesta { func respondeme(question: String)-> String { let casedQuestion = question.lowercased() if casedQuestion == "hello there"{ return "Why, hello there" } else if casedQuestion == "where are the cookies" { return "In the cookies jar" } else if casedQuestion.hasPrefix("where"){ return "To the North" } else { let numeroDefecto = question.utf8CString.count % 3 if numeroDefecto == 0 { return "That really depends" } else if numeroDefecto == 1 { return "Ask me again tomorow" } else {//2 return "I`m not sure, I understand" } } } }
true
8a5d5ad729320121923ed8e450b9340f5ca4e4d1
Swift
Dean151/Advent-of-code-2020
/AdventOfCode-Swift/Days/Day09/Day09.swift
UTF-8
2,243
3.390625
3
[ "MIT" ]
permissive
import Foundation enum Day09: Day { static func test() throws { let input = try Input.getFromFile("\(Self.self)", file: "test") let values = try integers(for: input) let number = try findFirstNumberThatIsNotASum(from: values, in: 5) let (min, max) = try find(number, asCongruentSumIn: values) precondition(values.count == 20) precondition(number == 127) precondition((min, max) == (15, 47)) } static func run(input: String) throws { let values = try integers(for: input) // Day 9-1 let number = try findFirstNumberThatIsNotASum(from: values, in: 25) print("Solution for day 9-1 is \(number)") // Day 9-2 let (min, max) = try find(number, asCongruentSumIn: values) print("Solution for day 9-2 is \(min + max)") } private static func findFirstNumberThatIsNotASum(from input: [Int], in window: Int) throws -> Int { assert(input.count > window) for current in window..<input.count { let number = input[current] if !isNumber(number, sumOfTwoIn: input[current-window...current-1]) { return number } } throw Errors.unsolvable } private static func isNumber(_ number: Int, sumOfTwoIn numbers: ArraySlice<Int>) -> Bool { var toTest = numbers while let first = toTest.popLast() { let second = number - first if toTest.contains(second) { return true } } return false } private static func find(_ number: Int, asCongruentSumIn numbers: [Int]) throws -> (min: Int, max: Int) { // Brute force is probably not the most elegant solution mainLoop: for minIndex in 0..<numbers.count-1 { for maxIndex in minIndex+1..<numbers.count { let subArray = numbers[minIndex...maxIndex] let sum = subArray.reduce(0, +) if sum == number { return (subArray.min()!, subArray.max()!) } if sum > number { continue mainLoop } } } throw Errors.unsolvable } }
true
6121c8e38346f5c96c4152f9e527a36f795ed1b9
Swift
cjcoax/PhotoTransition
/PhotoTransition/DetailVC.swift
UTF-8
2,436
2.640625
3
[ "Apache-2.0" ]
permissive
// // DetailVC.swift // PhotoTransition // // Created by Amir Rezvani on 7/20/18. // Copyright © 2018 Amir Rezvani. All rights reserved. // import UIKit class DetailVC: UIViewController { @IBOutlet weak var locationImageView: UIImageView! @IBOutlet weak var scrollView: UIScrollView! private let threshold: CGFloat = 0.2 private var originalCenter: CGPoint! private var initialTouchPoint: CGPoint! var locationImage: UIImage? weak var transition: FullScreenPhotoTransition? override func viewDidLoad() { super.viewDidLoad() locationImageView.image = locationImage originalCenter = view.center } @IBAction func didPan(_ sender: UIPanGestureRecognizer) { guard let view = sender.view else { return } let translation = sender.translation(in: view) switch sender.state { case .began: initialTouchPoint = sender.location(in: view.superview!) case .changed, .possible: self.view.frame.origin.y += translation.y case .ended: print(sender.location(in: view.superview!).y) print(initialTouchPoint.y) let percentage = (sender.location(in: view.superview!).y - initialTouchPoint.y)/view.frame.height print(percentage) guard percentage > threshold else { UIView.animate(withDuration: TimeInterval(max(abs(percentage), 0.3)), delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .curveEaseOut, animations: { [weak self] in guard let `self` = self else { return } self.view.center = self.originalCenter }, completion: nil) return } dismiss(animated: true, completion: nil) default: break } sender.setTranslation(CGPoint.zero, in: view) } } extension DetailVC: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return locationImageView } }
true
f55e12c9c5ec35e1982eb470b90d20dc1e5455ad
Swift
rikapsu2018/dracoon-swift-sdk
/dracoon-sdk/Model/CopyNodesRequest.swift
UTF-8
1,095
2.546875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // CopyNodesRequest.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public struct CopyNodesRequest: Codable { public enum ResolutionStrategy: String, Codable { case autorename = "autorename" case overwrite = "overwrite" case fail = "fail" } /** List of nodes to be copied */ public var items: [CopyNode]? /** Node conflict resolution strategy: * &#x60;autorename&#x60; * &#x60;overwrite&#x60; * &#x60;fail&#x60; (default: &#x60;autorename&#x60;) */ public var resolutionStrategy: ResolutionStrategy? /** Preserve Download Share Links and point them to the new node. (default: false) */ public var keepShareLinks: Bool? /** &#x60;DEPRECATED&#x60;: Node IDs; use &#x60;items&#x60; attribute */ public var nodeIds: [Int64]? public init(items: [CopyNode], resolutionStrategy: ResolutionStrategy?, keepShareLinks: Bool?) { self.items = items self.resolutionStrategy = resolutionStrategy self.keepShareLinks = keepShareLinks } }
true
482a40a4d680a0043a7ed2206b4a28a9e5446086
Swift
yintao910816/SpecialTraining
/SpecialTraining/Utils/ImagePicker/AVCaptureSessionManager.swift
UTF-8
5,014
2.515625
3
[]
no_license
// // AVCaptureSessionManager.swift // SpecialTraining // // Created by 尹涛 on 2018/12/8. // Copyright © 2018 youpeixun. All rights reserved. // import UIKit import Photos import AVFoundation class AVCaptureSessionManager { /** AVCaptureSession 视频捕获 input和output 的桥梁 videoDevice 视频输入设备 audioDevice 音频输入设备 */ private let captureSession = AVCaptureSession() private let videoDevice = AVCaptureDevice.default(for: AVMediaType.video) private let audioDevice = AVCaptureDevice.default(for: AVMediaType.audio) private let fileOutPut = AVCaptureMovieFileOutput() var isRecording = false var isReady = false private var tmpFileUrl:URL? private var viewController: UIViewController! public weak var delegate: CaptureSessionDelegate? init(root viewController: UIViewController) { self.viewController = viewController } func startRecord() { if isReady == true { if isRecording == true { captureSession.stopRunning() } captureSession.startRunning() }else { creatUI() } } func stopRecord() { captureSession.stopRunning() } func creatUI() { //添加视频音频输入设备、添加视频捕获输出 guard let video = videoDevice else { NoticesCenter.alert(title: "提示", message: "不支持录像") return } guard let audio = audioDevice else { NoticesCenter.alert(title: "提示", message: "不支持录音") return } do { let videoInput = try AVCaptureDeviceInput.init(device: video) let audioInput = try AVCaptureDeviceInput.init(device: audio) captureSession.addInput(videoInput) captureSession.addInput(audioInput) captureSession.addOutput(fileOutPut) let videoLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoLayer.frame = viewController.view.bounds videoLayer.videoGravity = .resizeAspectFill viewController.view.layer.insertSublayer(videoLayer, at: 0) isReady = true captureSession.startRunning() } catch { isReady = false NoticesCenter.alert(title: "提示", message: "设备初始化失败!") } } private func openMedia() { if UIImagePickerController.isSourceTypeAvailable(.camera) { //获取相机权限 let status = AVCaptureDevice.authorizationStatus(for: .metadata) switch status { case .notDetermined: // 第一次触发 AVCaptureDevice.requestAccess(for: .metadata) { [weak self] _ in self?.openMedia() } case .restricted: //此应用程序没有被授权访问的照片数据 NoticesCenter.alert(message: "此应用程序没有被授权访问的照片数据") case .denied: //用户已经明确否认了这一照片数据的应用程序访问 NoticesCenter.alert(message: "请前往设置中心授权相册权限") break case .authorized://已经有权限 break } }else { NoticesCenter.alert(message: "此设备不支持摄像") } } } extension AVCaptureSessionManager { func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) { print("StartRecording 开始") isRecording = true } func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) { isRecording = false delegate?.capture(didFinishRecordingToOutputFileAt: outputFileURL) // var message:String! // // //将录制好的录像保存到照片库中 // PHPhotoLibrary.shared().performChanges({ // // PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputFileURL) // }) { (isSuccess:Bool, error:Error?) in // if isSuccess { // message = "保存成功" // }else { // message = "失败:\(String(describing: error?.localizedDescription))" // } // // DispatchQueue.main.async {[weak self] in // let alertVC = UIAlertController(title: message, message: nil, preferredStyle: .alert) // let cancelAction = UIAlertAction(title: "sure", style: .cancel, handler: nil) // alertVC.addAction(cancelAction) // } // } } } protocol CaptureSessionDelegate: class { func capture(didFinishRecordingToOutputFileAt outputFileURL: URL) }
true
4e6cc011cb0be8a96dabd7b3c8d0527fe975b618
Swift
engin7/weatherMeta
/weather/Extensions/Loadable.swift
UTF-8
1,227
3
3
[]
no_license
// // Loadable.swift // weather // // Created by Engin KUK on 10.10.2020. // import UIKit fileprivate struct Constants { /// an arbitrary tag id for the loading view, so it can be retrieved later without keeping a reference to it fileprivate static let loadingViewTag = 1234 } /// Default implementation for UIViewController extension Loadable where Self: UIViewController { func showLoadingView() { let loadingView = LoadingView() view.addSubview(loadingView) loadingView.translatesAutoresizingMaskIntoConstraints = false loadingView.widthAnchor.constraint(equalToConstant: 100).isActive = true loadingView.heightAnchor.constraint(equalToConstant: 100).isActive = true loadingView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true loadingView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true loadingView.animate() loadingView.tag = Constants.loadingViewTag } func hideLoadingView() { view.subviews.forEach { subview in if subview.tag == Constants.loadingViewTag { subview.removeFromSuperview() } } } }
true
3d11d1d4115bf579d35f6f40e776b454642b368d
Swift
Xitric/AR-Programming
/ProgramModel/ProgramModel/Api/CardCollection.swift
UTF-8
298
2.625
3
[]
no_license
// // CardCollection.swift // ProgramModel // // Created by Kasper Schultz Davidsen on 06/04/2019. // Copyright © 2019 Emil Nielsen and Kasper Schultz Davidsen. All rights reserved. // import Foundation /// A container storing all cards available for programming. public protocol CardCollection { var cards: [Card] { get } }
true
3508848f7357d0ce195693c380ca657eb7ac70d0
Swift
feilfeilundfeil/Cyanic
/Tests/ViewModelTests.swift
UTF-8
15,358
2.96875
3
[ "MIT" ]
permissive
// // ViewModelTests.swift // Tests // // Created by Julio Miguel Alorro on 2/6/19. // Copyright © 2019 Feil, Feil, & Feil GmbH. All rights reserved. // import Quick import Nimble @testable import Cyanic class ViewModelTests: QuickSpec { // MARK: - Test Data Structures struct TestState: State { static var `default`: ViewModelTests.TestState { return ViewModelTests.TestState( string: "Hello, World", isTrue: false, double: 1337.0, asyncOnSuccess: Async<Bool>.uninitialized, asyncOnFailure: Async<Bool>.uninitialized ) } var string: String var isTrue: Bool var double: Double var asyncOnSuccess: Async<Bool> var asyncOnFailure: Async<Bool> } class TestViewModel: ViewModel<TestState> {} enum AsyncError: CyanicError { case failed var errorDescription: String { return "Async Property failed" } } // MARK: - Factory Method private func createViewModel() -> TestViewModel { return TestViewModel(initialState: TestState.default) } override func spec() { describe("withState and setState methods") { it("setState closure should be executed before withState closures even if withState is called first.") { let viewModel: TestViewModel = self.createViewModel() var currentState: TestState = viewModel.currentState var isCurrentState: Bool = false var value: Double = -1000.0 let finalValue: Double = 5.0 viewModel.withState(block: { (state: TestState) -> Void in currentState = state }) var isEqual: Bool = false viewModel.setState(with: { $0.double = 0.0 value = 0.0 }) viewModel.withState(block: { (state: TestState) -> Void in print("Double: \(state.double), FinalValue: \(finalValue)") isEqual = state.double == finalValue }) viewModel.withState(block: { (state: TestState) -> Void in print("CurrentState: \(currentState)") print("State: \(state)") isCurrentState = currentState == state }) viewModel.setState(with: { $0.double = 1.0 value = 1.0 }) viewModel.setState(with: { $0.double = finalValue value = finalValue }) expect(isCurrentState).toEventually(equal(true), description: "isCurrentState is \(isCurrentState)") expect(isEqual).toEventually(equal(true), description: "Value is \(value).") } } describe("asyncSubscribe method") { context("If the Async property is mutated to .success") { it("should execute the onSuccess closure") { let viewModel: TestViewModel = self.createViewModel() var wasSuccess: Bool = false viewModel.asyncSubscribe( to: \TestState.asyncOnSuccess, postInitialValue: false, onSuccess: { (value: Bool) -> Void in wasSuccess = value }, onFailure: { (error: Error) -> Void in fail() } ) viewModel.setState(with: { (state: inout TestState) -> Void in state.asyncOnSuccess = .success(true) }) expect(wasSuccess).toEventually(equal(true)) } } context("If the Async property is mutated to .failure") { it("should execute the onFailure closure") { let viewModel: TestViewModel = self.createViewModel() var wasFailure: Bool = false viewModel.asyncSubscribe( to: \TestState.asyncOnFailure, postInitialValue: false, onSuccess: { (value: Bool) -> Void in fail() }, onFailure: { (error: Error) -> Void in wasFailure = true } ) viewModel.setState(with: { (state: inout TestState) -> Void in state.asyncOnFailure = .failure(AsyncError.failed) }) expect(wasFailure).toEventually(equal(true)) expect(viewModel.currentState.asyncOnFailure).toEventually(equal(Async.failure(AsyncError.failed))) } } context("If the Async property is already .success/failure") { it("should not execute the onSuccess/Failure closure after subscribing") { let viewModel: TestViewModel = self.createViewModel() let state: TestState = viewModel.currentState // Set the asyncOnSuccess property to success synchronously viewModel.stateStore.stateRelay .accept(state.copy(with: {$0.asyncOnSuccess = .success(true) })) viewModel.asyncSubscribe( to: \TestState.asyncOnSuccess, postInitialValue: false, onSuccess: { (value: Bool) -> Void in fail() }, onFailure: { (error: Error) -> Void in fail() } ) viewModel.setState(with: { $0.asyncOnSuccess = .success(true) $0.string = "This" }) viewModel.setState(with: { $0.asyncOnSuccess = .success(true) $0.string = "That" }) expect(viewModel.currentState.string).toEventually(equal("That")) } } } describe("selectSubscribe single keyPath") { context("If the subscribed property changes to a different value") { it("should execute the onNewValue closure") { let viewModel: TestViewModel = self.createViewModel() var newProperty: String = "" let expectedValue: String = "Cyanic" viewModel.selectSubscribe( to: \TestState.string, postInitialValue: false, onNewValue: { (newValue: String) -> Void in newProperty = newValue } ) viewModel.setState(with: { (state: inout TestState) -> Void in state.string = expectedValue }) expect(newProperty).toEventually(equal(expectedValue)) } } context("If the subscribed property is mutated to the same value") { it("should not execute the onNewValue closure") { let viewModel: TestViewModel = self.createViewModel() let initialString: String = viewModel.currentState.string viewModel.selectSubscribe( to: \TestState.string, postInitialValue: false, onNewValue: { (value: String) -> Void in guard value != initialString else { fail("\(value) is equal to \(initialString)"); return } } ) viewModel.setState(with: { (state: inout TestState) -> Void in state.string = initialString state.double = 1339 }) viewModel.setState(with: { (state: inout TestState) -> Void in state.string = initialString state.double = 1340 }) viewModel.setState(with: { (state: inout TestState) -> Void in state.string = "Hello" state.double = 1341 }) expect(viewModel.currentState.string).toEventually(equal("Hello")) } } } describe("selectSubscribe multiple keyPaths") { context("If either ofthe subscribed properties change value") { it("should execute the onNewValue closure for two properties") { let viewModel: TestViewModel = self.createViewModel() let currentString: String = viewModel.currentState.string let currentDouble: Double = viewModel.currentState.double var counter: Int = 0 viewModel.selectSubscribe( keyPath1: \TestState.double, keyPath2: \TestState.string, postInitialValue: false, onNewValue: { (double: Double, string: String) -> Void in counter += 1 } ) // Should not increment DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) { viewModel.setState(with: { (state: inout TestState) -> Void in state.string = currentString // Hello, World state.double = currentDouble // 1337.0 state.isTrue = true }) } // Should increment DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) { viewModel.setState(with: { (state: inout TestState) -> Void in state.string = currentString // Hello, World state.double = 1339.0 // 1339.0 }) } // Should increment DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { viewModel.setState(with: { (state: inout TestState) -> Void in state.string = "Hello" // Hello state.double = 1339.0 // 1339.0 }) } // Should increment DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { viewModel.setState(with: { (state: inout TestState) -> Void in state.string = "Hello" // Hello state.double = 1341.0 // 1341.0 }) } expect(counter).toEventually(equal(3), timeout: 0.5, pollInterval: 0.5, description: "") } it("should execute the onNewValue closure for two properties") { let viewModel: TestViewModel = self.createViewModel() let initialString: String = viewModel.currentState.string // Hello, World let initialDouble: Double = viewModel.currentState.double // 1337.0 let initialIsTrue: Bool = viewModel.currentState.isTrue // false var counter: Int = 0 viewModel.selectSubscribe( keyPath1: \TestState.double, keyPath2: \TestState.string, keyPath3: \TestState.isTrue, postInitialValue: false, onNewValue: { (double: Double, string: String, isTrue: Bool) -> Void in counter += 1 } ) // Should not increment DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) { viewModel.setState(with: { (state: inout TestState) -> Void in state.string = initialString // Hello, World state.double = initialDouble // 1337.0 state.isTrue = initialIsTrue // false }) } // Should increment DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) { viewModel.setState(with: { (state: inout TestState) -> Void in state.string = initialString // Hello, World state.double = 1339.0 // 1339.0 state.isTrue = initialIsTrue // false }) } // Should increment DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { viewModel.setState(with: { (state: inout TestState) -> Void in state.string = initialString // Hello, World state.double = initialDouble // 1337.0 state.isTrue = initialIsTrue // false }) } // Should not increment DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { viewModel.setState(with: { (state: inout TestState) -> Void in state.string = initialString // Hello, World state.double = initialDouble // 1337.0 state.isTrue = initialIsTrue // false }) } // Should increment DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { viewModel.setState(with: { (state: inout TestState) -> Void in state.string = "Hi" // Hi state.double = 1340 // 1340 // state.isTrue // false }) } // Should increment DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.35) { viewModel.setState(with: { (state: inout TestState) -> Void in state.string = "Hi" // Hi // state.double // 1340 state.isTrue = true // true }) } expect(counter) .toEventually(equal(4), timeout: 0.5, pollInterval: 0.5, description: "") } } } } }
true
40567114882ecfb32f1cdced2ffab988567c23c5
Swift
josephjeno/Swift-Course
/API Demo/API Demo/ViewController.swift
UTF-8
2,217
3.046875
3
[]
no_license
// // ViewController.swift // API Demo // // Created by Joseph Jeno on 8/26/17. // Copyright © 2017 josephjeno. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //url of website with api data let url = URL(string:"http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=08e64df2d3f3bc0822de1f0fc22fcb2d")! // double click on completionHandler to set data, response, and error let task = URLSession.shared.dataTask(with: url) { (data, response, error) in if error != nil { print(error!) } else { // safety check to ensure data exists if let urlContent = data { do { // creates api object let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject // prints entire jsonResult (from api link) print(jsonResult) // prints just requested jsonResult (in this case name) print(jsonResult["name"]) // prints the description within weather array of jsonResult if let description = ((jsonResult["weather"] as? NSArray)?[0] as? NSDictionary)?["description"] as? String { print(description) } } catch { print("JSON processing failed") } } } } task.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
68a0a84ee6888b6ccaa86d8c013a75dcea1f3421
Swift
danielrhammond/pilot
/UI/Source/CollectionViews/mac/CollectionViewController.swift
UTF-8
21,372
2.796875
3
[ "Apache-2.0" ]
permissive
import AppKit import Pilot /// Struct representing what to display when the collection view is empty. public enum EmptyCollectionDisplay { /// Returns a custom string with font and color, which is displayed in the center of the empty collection view. case text(String, NSFont, NSColor) /// Returns a custom view that will be centered in the empty collection view. case view(NSView) /// Returns a custom view and a custom constraint creation block to hook up constraints to the parent view. /// Paramaters of the closure are the parent view and the child view, in order. Return value is an /// array of constraints which will be added. case viewWithCustomConstraints(NSView, (NSView, NSView) -> [NSLayoutConstraint]) /// No empty view. case none } /// Struct representing what spinner to display when the collection view is empty and loading. /// TODO:(wkiefer) Bring this to iOS (and share where possible). public enum LoadingCollectionDisplay { /// No loading view. case none /// Shows the default system spinner centered in the view. case systemSpinner /// Shows the default system spinner with the provided custom constraints. /// Paramaters of the closure are the parent view and the child view, in order. Return value is an /// array of constraints which will be added. case systemSpinnerWithConstraints((NSView, NSView) -> [NSLayoutConstraint]) /// Shows a custom loading indicator view centered in the view. case custom(NSView) /// Shows a custom loading indicator view with the provided custom constraints. /// Paramaters of the closure are the parent view and the child view, in order. Return value is an /// array of constraints which will be added. case customWithConstraints(NSView, (NSView, NSView) -> [NSLayoutConstraint]) } /// View controller implementation which contains the core MVVM binding support to show a given `ModelCollection` /// in a collection view. /// Subclassing should typically be only for app-specific view controller behavior (and not cell configuration). open class CollectionViewController: NSViewController, CollectionViewDelegate { // MARK: Init public init( model: ModelCollection, modelBinder: ViewModelBindingProvider, viewBinder: ViewBindingProvider, layout: NSCollectionViewLayout, context: Context, reuseIdProvider: CollectionViewCellReuseIdProvider = DefaultCollectionViewCellReuseIdProvider() ) { self.layout = layout self.dataSource = CollectionViewModelDataSource( model: model, modelBinder: modelBinder, viewBinder: viewBinder, context: context.newScope(), reuseIdProvider: reuseIdProvider) // loadView will never fail super.init(nibName: nil, bundle: nil)! } @available(*, unavailable, message: "Use `init(model:modelBinder:viewBinder:layout:context:)`") public required init?(coder: NSCoder) { Log.fatal(message: "Use `init(model:modelBinder:viewBinder:layout:context:)` instead") } deinit { unreigsterForMenuTrackingEnd() unregisterForModelEvents() collectionView.delegate = nil collectionView.dataSource = nil } // MARK: Public /// Read-only access to the model collection representing the data as far as the CollectionView /// has been told. If the current code path is initiated by the CollectionView and uses an IndexPath, /// this is the collection that should be used. /// See `CollectionViewModelDataSource.currentCollection` for more documentation. public var collection: ModelCollection { return dataSource.currentCollection } /// Read-only access to the underlying context. public var context: Context { return dataSource.context } /// Read-only access to the collection view data source. public let dataSource: CollectionViewModelDataSource /// Layout for the collection view. open var layout: NSCollectionViewLayout { didSet { guard isViewLoaded else { return } collectionView.collectionViewLayout = layout } } open var backgroundColor = NSColor.clear { didSet { guard isViewLoaded else { return } collectionView.backgroundColors = [backgroundColor] } } /// Read-only access to the underlying collection view. open let collectionView: CollectionView = CollectionView() /// Read-only access to the underlying scroll view. open var scrollView: NSScrollView { return internalScrollView } /// Enables or disables scrolling on the hosted scrollview. open var scrollEnabled: Bool { get { return internalScrollView.scrollEnabled } set { internalScrollView.scrollEnabled = newValue } } /// Determines what should be displayed for an empty collection that is loading. open var loadingDisplay: LoadingCollectionDisplay = .systemSpinner // MARK: Public Intended for subclass override /// Returns the root view created during `loadView`. Subclasses may override to provide their own customized /// view instance. open func makeRootView() -> NSView { return NSView() } /// Returns an `EmptyCollectionDisplay` struct defining what to show for an empty collection in the `Error` state. /// Intended for subclass override. open func displayForErrorState(_ error: Error) -> EmptyCollectionDisplay { return .none } /// Returns an `EmptyCollectionDisplay` struct defining what to show for an empty collection that has no data but /// is in the `Loaded` state. Intended for subclass override. open func displayForNoContentState() -> EmptyCollectionDisplay { return .none } /// Intended for subclass override - invoked when a model object is displayed in the collection. open func willDisplayViewModel(_ viewModel: ViewModel) { // NOP - intended for subclassing. } // MARK: NSViewController public final override func loadView() { view = makeRootView() view.autoresizingMask = [.viewWidthSizable, .viewHeightSizable] view.addSubview(scrollView) scrollView.frame = view.bounds scrollView.autoresizingMask = [.viewWidthSizable, .viewHeightSizable] scrollView.wantsLayer = true scrollView.layerContentsRedrawPolicy = .onSetNeedsDisplay scrollView.horizontalScroller = FullWidthScroller() scrollView.verticalScroller = FullWidthScroller() scrollView.documentView = collectionView scrollView.drawsBackground = false scrollView.contentView.copiesOnScroll = true collectionView.wantsLayer = true collectionView.layerContentsRedrawPolicy = .onSetNeedsDisplay collectionView.allowsMultipleSelection = false collectionView.backgroundColors = [backgroundColor] collectionView.itemPrototype = nil collectionView.isSelectable = true collectionView.autoresizingMask = [.viewWidthSizable, .viewHeightSizable] } open override func viewDidLoad() { super.viewDidLoad() view.layer?.backgroundColor = NSColor.clear.cgColor dataSource.collectionView = collectionView collectionView.collectionViewLayout = layout collectionView.dataSource = dataSource collectionView.delegate = self collectionView.layer?.backgroundColor = NSColor.clear.cgColor dataSource.willRebindViewModel = { [weak self] viewModel in self?.willDisplayViewModel(viewModel) } scrollView.scrollerStyle = .overlay registerForModelEvents() } open override func viewWillLayout() { super.viewWillLayout() let bounds = view.bounds if !bounds.equalTo(lastBounds) { dataSource.clearCachedItemSizes() } lastBounds = bounds } // MARK: CollectionViewDelegate open func collectionViewDidReceiveReturnKey(_ collectionView: NSCollectionView) -> Bool { // Right now, only a single selected item is supported for the return/enter keys. guard let indexPath = collectionView.selectionIndexPaths.first else { return false } guard let vm = viewModelAtIndexPath(indexPath) else { return false } if vm.canHandleUserEvent(.enterKey) { vm.handleUserEvent(.enterKey) return true } return false } open func collectionViewDidReceiveSpaceKey(_ collectionView: NSCollectionView) -> Bool { // Right now, only a single selected item is supported for the space keys. guard let indexPath = collectionView.selectionIndexPaths.first else { return false } guard let vm = viewModelAtIndexPath(indexPath) else { return false } if vm.canHandleUserEvent(.spaceKey) { vm.handleUserEvent(.spaceKey) return true } return false } open func collectionView(_ collectionView: NSCollectionView, didClickIndexPath indexPath: IndexPath) { guard let vm = viewModelAtIndexPath(indexPath) else { return } if vm.canHandleUserEvent(.click) { vm.handleUserEvent(.click) } } open func collectionView(_ collectionView: NSCollectionView, menuForIndexPath indexPath: IndexPath) -> NSMenu? { guard let vm = viewModelAtIndexPath(indexPath) else { return nil } if vm.canHandleUserEvent(.secondaryClick) { vm.handleUserEvent(.secondaryClick) let actions = vm.secondaryActions(for: .secondaryClick) if !actions.isEmpty { let menu = NSMenu.fromSecondaryActions(actions, action: #selector(didSelectContextMenuItem(_:))) if let item = collectionView.item(at: indexPath) as? CollectionViewHostItem { item.highlightStyle = .contextMenu registerForMenuTrackingEnd(menu, item: item) } return menu } } return nil } // MARK: NSCollectionViewDelegate open func collectionView( _ collectionView: NSCollectionView, willDisplay item: NSCollectionViewItem, forRepresentedObjectAt indexPath: IndexPath ) { guard let viewModel = dataSource.viewModelAtIndexPath(indexPath) else { return } willDisplayViewModel(viewModel) } open func collectionView( _ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath> ) { guard let indexPath = indexPaths.first , indexPaths.count == 1 else { return } guard let vm = viewModelAtIndexPath(indexPath) else { return } if vm.canHandleUserEvent(.select) { vm.handleUserEvent(.select) } } // MARK: Private private var lastBounds = CGRect.zero private let internalScrollView = FullWidthScrollView() private func viewModelAtIndexPath(_ indexPath: IndexPath) -> ViewModel? { guard let item = collectionView.item(at: indexPath as IndexPath) as? CollectionViewHostItem else { return nil} return item.hostedView?.viewModel } /// View to show when in the `loading` state - dictated by `loadingDisplay`. private var loadingView: NSView? private func showLoadingView() { guard self.loadingView == nil else { return } guard let loadingView = loadingView(for: loadingDisplay) else { return } self.loadingView = loadingView loadingView.translatesAutoresizingMaskIntoConstraints = false collectionView.addSubview(loadingView) let makeConstraints = loadingViewConstraints(for: loadingDisplay) NSLayoutConstraint.activate(makeConstraints(view, loadingView)) } private func hideLoadingView() { loadingView?.removeFromSuperview() loadingView = nil } private func loadingView(for display: LoadingCollectionDisplay) -> NSView? { switch display { case .none: return nil case .custom(let view): return view case .customWithConstraints(let view, _): return view case .systemSpinnerWithConstraints(_): fallthrough case .systemSpinner: let spinner = NSProgressIndicator() spinner.style = .spinningStyle spinner.controlSize = .small spinner.startAnimation(self) return spinner } } private func loadingViewConstraints( for display: LoadingCollectionDisplay ) -> (NSView, NSView) -> [NSLayoutConstraint] { let defaultConstraints: (NSView, NSView) -> [NSLayoutConstraint] = { parent, child in return [child.centerXAnchor.constraint(equalTo: parent.centerXAnchor), child.centerYAnchor.constraint(equalTo: parent.centerYAnchor), child.bottomAnchor.constraint(lessThanOrEqualTo: parent.bottomAnchor), child.topAnchor.constraint(greaterThanOrEqualTo: parent.topAnchor)] } switch display { case .custom(_): return defaultConstraints case .customWithConstraints(_, let constraints): return constraints case .none: return { _, _ in return [] } case .systemSpinner: return defaultConstraints case .systemSpinnerWithConstraints(let constraints): return constraints } } @objc private func didSelectContextMenuItem(_ menuItem: NSMenuItem) { guard let action = menuItem.representedAction else { Log.warning(message: "No action attached to secondary action menu item: \(menuItem)") return } action.send(from: context) } private func registerForMenuTrackingEnd(_ menu: NSMenu, item: CollectionViewHostItem) { unreigsterForMenuTrackingEnd() let cookie = item.menuTrackingCookie NotificationCenter.default.addObserver( forName: NSNotification.Name.NSMenuDidEndTracking, object: menu, queue: OperationQueue.main) { [weak item] _ in guard let item = item , item.menuTrackingCookie == cookie else { return } item.highlightStyle = .none } } private var menuNotificationObserver: NSObjectProtocol? private func unreigsterForMenuTrackingEnd() { guard let menuNotificationObserver = self.menuNotificationObserver else { return } NotificationCenter.default.removeObserver(menuNotificationObserver) self.menuNotificationObserver = nil } // MARK: Observing model state changes. private var collectionObserver: Observer? private func registerForModelEvents() { assertWithLog(collectionObserver == nil, message: "Expected to start with a nil token") collectionObserver = collection.observe { [weak self] event in self?.handleModelEvent(event) } // Upon registering, fire an initial state change to match existing state. handleModelEvent(.didChangeState(collection.state)) } private func unregisterForModelEvents() { collectionObserver = nil } private func handleModelEvent(_ event: CollectionEvent) { hideEmptyContentView() switch event { case .didChangeState(let state): if !state.isLoading { // Non-loading states should hide the spinner. hideLoadingView() } switch state { case .notLoaded: break case .loading(let models): if models == nil || state.isEmpty { showLoadingView() } case .loaded: updateEmptyContentViewVisibility() case .error(_): updateEmptyContentViewVisibility() } } } /// View which is displayed when there is no content (either due to error or lack of loaded data). private var emptyContentView: NSView? private func showEmptyContentView() { guard self.emptyContentView == nil else { return } let display: EmptyCollectionDisplay if case .error(let error) = collection.state { display = displayForErrorState(error) } else { display = displayForNoContentState() } if let emptyContentView = emptyContentView(for: display) { self.emptyContentView = emptyContentView emptyContentView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(emptyContentView) let makeConstraints = emptyContentViewConstraints(for: display) NSLayoutConstraint.activate(makeConstraints(view, emptyContentView)) } } private func hideEmptyContentView() { emptyContentView?.removeFromSuperview() emptyContentView = nil } private func updateEmptyContentViewVisibility() { switch collection.state { case .error(_), .loaded: if collection.isEmpty { showEmptyContentView() } else { hideEmptyContentView() } case .notLoaded, .loading: hideEmptyContentView() } } private func emptyContentView(for display: EmptyCollectionDisplay) -> NSView? { switch display { case .none: return nil case .text(let string, let font, let color): let label = NSTextField() label.isEditable = false label.isBordered = false label.backgroundColor = .clear label.alignment = .center label.font = font label.textColor = color label.stringValue = string return label case .viewWithCustomConstraints(let view, _): return view case .view(let view): return view } } private func emptyContentViewConstraints( for display: EmptyCollectionDisplay ) -> (NSView, NSView) -> [NSLayoutConstraint] { switch display { case .viewWithCustomConstraints(_, let constraints): return constraints case .text(_, _, _): return { parent, child in return [child.widthAnchor.constraint(equalTo: parent.widthAnchor), child.heightAnchor.constraint(lessThanOrEqualTo: parent.widthAnchor), child.centerXAnchor.constraint(equalTo: parent.centerXAnchor), child.centerYAnchor.constraint(equalTo: parent.centerYAnchor)] } default: return { parent, child in return [child.centerXAnchor.constraint(equalTo: parent.centerXAnchor), child.centerYAnchor.constraint(equalTo: parent.centerYAnchor)] } } } } // MARK: - /// Private helper class to force the scroller to always appear as a modern over-content scroller. private final class FullWidthScroller: NSScroller { // MARK: NSScroller override class func isCompatibleWithOverlayScrollers() -> Bool { return true } override class func preferredScrollerStyle() -> NSScrollerStyle { return .overlay } override func drawKnobSlot(in slotRect: NSRect, highlight flag: Bool) { // Nop } override class func scrollerWidth( for controlSize: NSControlSize, scrollerStyle: NSScrollerStyle ) -> CGFloat { if FullWidthScroller.widthOverride { return 0.0 } return super.scrollerWidth(for: controlSize, scrollerStyle: scrollerStyle) } // MARK: Private static var widthOverride = false } /// Private helper class to force the vertical scroller to always appear as a modern over-content scroller. fileprivate final class FullWidthScrollView: NSScrollView { fileprivate var scrollEnabled: Bool = true // MARK: NSScrollView fileprivate override func scrollWheel(with theEvent: NSEvent) { if scrollEnabled { super.scrollWheel(with: theEvent) } } fileprivate override func flashScrollers() { if scrollEnabled { super.flashScrollers() } } fileprivate override func tile() { // For the superclass's tile implementation, the scroller returns zero width so content underneath is always // full width. FullWidthScroller.widthOverride = true super.tile() FullWidthScroller.widthOverride = false guard let verticalScroller = verticalScroller else { return } // Now adjust the actual scroller frame since the `super.tile()` call made it zero width. let bounds = self.bounds let vInset = contentInsets let vWidth = FullWidthScroller.scrollerWidth( for: verticalScroller.controlSize, scrollerStyle: verticalScroller.scrollerStyle) verticalScroller.frame = CGRect( x: bounds.width - vWidth - vInset.right, y: vInset.top, width: vWidth, height: bounds.height - vInset.top - vInset.bottom) } }
true
7700fadb4ce89ccc44b7875e4708ad53071b621f
Swift
ilyapuchka/Quandoo
/Quandoo/Data Access Layer/NetworkSession.swift
UTF-8
1,148
2.875
3
[]
no_license
// // NetworkSession.swift // Quandoo // // Created by Ilya Puchka on 12/10/2017. // Copyright © 2017 Ilya Puchka. All rights reserved. // import Foundation protocol NetworkSession { func request<T: Codable>(_ request: URLRequest, completion: @escaping (T?, Data?, URLResponse?, Error?) -> Void) } extension URLSession: NetworkSession { func request<T: Codable>(_ request: URLRequest, completion: @escaping (T?, Data?, URLResponse?, Error?) -> Void) { dataTask(with: request) { (data, response, error) in if let data = data { do { let decoded = try JSONDecoder().decode(T.self, from: data) DispatchQueue.main.async { completion(decoded, data, response, nil) } } catch { DispatchQueue.main.async { completion(nil, data, response, error) } } } else { DispatchQueue.main.async { completion(nil, data, response, error) } } }.resume() } }
true
7512ade33e406d9d34c53053f7648a7ab000c414
Swift
Hackice/ZPhotoPicker
/ZPhotoPicker/Classes/ZPhotoMutilPickerController.swift
UTF-8
2,277
2.6875
3
[ "MIT" ]
permissive
// // ZPhotoMutilPickerController.swift // hhh // // Created by Zack・Zheng on 2018/1/30. // Copyright © 2018年 Zack・Zheng. All rights reserved. // import UIKit class ZPhotoMutilPickerController: UINavigationController { private var imagesPickedHandler: ((_ image: [UIImage]) -> Void)? private var cancelledHandler: (() -> Void)? deinit { print("\(self) \(#function)") } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } convenience init(maxCount: Int, imagesPickedHandler: ((_ image: [UIImage]) -> Void)? = nil, cancelledHandler: (() -> Void)? = nil) { let vc = ZPhotoMutilPickerHostController(collectionViewLayout: UICollectionViewFlowLayout()) self.init(rootViewController: vc) self.imagesPickedHandler = imagesPickedHandler self.cancelledHandler = cancelledHandler vc.delegate = self vc.maxCount = maxCount } override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) } } extension ZPhotoMutilPickerController { class func pickPhotoes(onPresentingViewController controller: UIViewController, maxCount: Int, imagesPickedHandler: @escaping (_ image: [UIImage]) -> Void, cancelledHandler: (() -> Void)? = nil) { let vc = ZPhotoMutilPickerController(maxCount: maxCount, imagesPickedHandler: imagesPickedHandler, cancelledHandler: cancelledHandler) controller.present(vc, animated: true, completion: nil) } } extension ZPhotoMutilPickerController: ZPhotoMutilPickerHostControllerDelegate { func photoMutilPickerHostController(_ controller: ZPhotoMutilPickerHostController, didFinishPickingImages images: [UIImage]) { self.dismiss(animated: true, completion: { [weak self] in self?.imagesPickedHandler?(images) }) } func photoMutilPickerHostControllerDidCancel(_ controller: ZPhotoMutilPickerHostController) { self.dismiss(animated: true, completion: { [weak self] in self?.cancelledHandler?() }) } }
true
5a4dc4ee2aff7680390c75eaf8d3830b2f0f492b
Swift
benswift404/Compass-Wallpaper
/CompassImage/ImageViewController.swift
UTF-8
10,157
2.78125
3
[]
no_license
// // ImageViewController.swift // CompassImage // // Created by Ben Swift on 2/4/21. // import Cocoa enum LayoutOption { case Panel case Frame case Banner case Pill case None } class ImageViewController: NSViewController { @IBOutlet weak var backBox: NSBox! @IBOutlet weak var imageShadowBox: NSBox! @IBOutlet weak var displayImage: NSButton! @IBOutlet weak var choosePanelLayout: NSButton! @IBOutlet weak var chooseFrameLayout: NSButton! @IBOutlet weak var chooseBannerLayout: NSButton! @IBOutlet weak var choosePillLayout: NSButton! @IBOutlet weak var saveButton: NSButton! @IBOutlet weak var cancelButton: NSButton! var selectedImage: NSImage! var currentSelectedButton: LayoutOption! @IBOutlet weak var chooseLayoutHeaderText: NSTextField! @IBOutlet weak var panelIndicator: NSImageView! @IBOutlet weak var frameIndicator: NSImageView! @IBOutlet weak var bannerIndicator: NSImageView! @IBOutlet weak var pillIndicator: NSImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Compass Wallpaper" currentSelectedButton = .None hideSelectionButtons(hideOrShow: false) self.displayImage.wantsLayer = true self.displayImage.layer?.cornerRadius = 12 self.displayImage.layer?.masksToBounds = true setUpUI(image: choosePanelLayout) setUpUI(image: chooseFrameLayout) setUpUI(image: chooseBannerLayout) setUpUI(image: choosePillLayout) panelIndicator.isHidden = true frameIndicator.isHidden = true bannerIndicator.isHidden = true pillIndicator.isHidden = true chooseLayoutHeaderText.textColor = .lightGray saveButton.isEnabled = false cancelButton.isEnabled = false } override func viewDidAppear() { self.view.window?.styleMask.remove(NSWindow.StyleMask.resizable) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } // - Helper Functions func setUpUI(image: NSButton) { print("Setting up the UI") image.wantsLayer = true image.layer?.cornerRadius = 8 image.layer?.masksToBounds = true } func hideSelectionButtons(hideOrShow: Bool) { self.choosePanelLayout.isEnabled = hideOrShow self.chooseFrameLayout.isEnabled = hideOrShow self.chooseBannerLayout.isEnabled = hideOrShow self.choosePillLayout.isEnabled = hideOrShow } func showIndicatorFor(layout: LayoutOption) { switch layout { case .Panel: panelIndicator.isHidden = false frameIndicator.isHidden = true bannerIndicator.isHidden = true pillIndicator.isHidden = true break case .Frame: panelIndicator.isHidden = true frameIndicator.isHidden = false bannerIndicator.isHidden = true pillIndicator.isHidden = true break case .Banner: panelIndicator.isHidden = true frameIndicator.isHidden = true bannerIndicator.isHidden = false pillIndicator.isHidden = true break case .Pill: panelIndicator.isHidden = true frameIndicator.isHidden = true bannerIndicator.isHidden = true pillIndicator.isHidden = false break default: panelIndicator.isHidden = true frameIndicator.isHidden = true bannerIndicator.isHidden = true pillIndicator.isHidden = true break } } func createImage(layout: LayoutOption) -> NSImage { let image = selectedImage let bottomImage = image var topImage: NSImage! switch layout { case .Panel: topImage = NSImage(named: "Panel") break case .Frame: topImage = NSImage(named: "Frame") break case .Banner: topImage = NSImage(named: "Banner") break case .Pill: topImage = NSImage(named: "Pill") break default: NSSound.beep() print("Error gettimg image") let alert = NSAlert() alert.messageText = "Error!" alert.informativeText = "Something went wrong and we couldn't get an image. Try again" alert.alertStyle = .informational alert.addButton(withTitle: "OK") alert.runModal() } let newImage = NSImage(size: NSSize(width: 1366, height: 768)) newImage.lockFocus() var newImageRect: CGRect = .zero newImageRect.size = newImage.size bottomImage?.draw(in: newImageRect) topImage?.draw(in: newImageRect) newImage.unlockFocus() return newImage } @IBAction func selectImageAction(_ sender: Any) { guard let window = view.window else { return } let panel = NSOpenPanel() panel.canChooseFiles = true panel.canChooseDirectories = false panel.allowsMultipleSelection = false panel.allowedFileTypes = ["png", "jpg", "jpeg"] panel.beginSheetModal(for: window) { [self] (result) in if result.rawValue == NSApplication.ModalResponse.OK.rawValue { print(panel.urls[0]) self.selectedImage = NSImage(contentsOf: panel.urls[0]) self.displayImage.image = self.selectedImage self.hideSelectionButtons(hideOrShow: true) self.choosePanelLayout.image = self.createImage(layout: .Panel) self.chooseFrameLayout.image = self.createImage(layout: .Frame) self.chooseBannerLayout.image = self.createImage(layout: .Banner) self.choosePillLayout.image = self.createImage(layout: .Pill) self.currentSelectedButton = .None let shadow = NSShadow() shadow.shadowOffset = NSMakeSize(2, -2) shadow.shadowColor = NSColor.lightGray shadow.shadowBlurRadius = 25 self.imageShadowBox.shadow = shadow self.chooseLayoutHeaderText.textColor = .black saveButton.isEnabled = true cancelButton.isEnabled = true panelIndicator.isHidden = true frameIndicator.isHidden = true bannerIndicator.isHidden = true pillIndicator.isHidden = true } } } @IBAction func choosePanelLayoutAction(_ sender: Any) { if currentSelectedButton != .Panel { showIndicatorFor(layout: .Panel) self.displayImage.image = createImage(layout: .Panel) currentSelectedButton = .Panel } } @IBAction func chooseFrameLayoutAction(_ sender: Any) { if currentSelectedButton != .Frame { showIndicatorFor(layout: .Frame) self.displayImage.image = createImage(layout: .Frame) currentSelectedButton = .Frame } } @IBAction func chooseBannerLayoutAction(_ sender: Any) { if currentSelectedButton != .Banner { showIndicatorFor(layout: .Banner) self.displayImage.image = createImage(layout: .Banner) currentSelectedButton = .Banner } } @IBAction func choosePillLayoutAction(_ sender: Any) { if currentSelectedButton != .Pill { showIndicatorFor(layout: .Pill) self.displayImage.image = createImage(layout: .Pill) currentSelectedButton = .Pill } } @IBAction func cancelButtonAction(_ sender: Any) { guard let window = view.window else { return } let alert = NSAlert() alert.messageText = "Are you sure you want to quit?" alert.alertStyle = .warning alert.addButton(withTitle: "Yes") alert.addButton(withTitle: "Cancel") alert.beginSheetModal(for: window) { (modalResponse) in if modalResponse == .alertFirstButtonReturn { NSApplication.shared.terminate(self) } } } @IBAction func saveButtonAction(_ sender: Any) { let savePanel = NSSavePanel() savePanel.allowedFileTypes = ["png"] savePanel.begin { (result) in if result.rawValue == NSApplication.ModalResponse.OK.rawValue { if let finalImage = self.displayImage.image { let imageRep = NSBitmapImageRep(data: finalImage.tiffRepresentation!) let pngData = imageRep?.representation(using: NSBitmapImageRep.FileType.png, properties: [:]) do { try pngData?.write(to: savePanel.url!) NSSound.beep() print("Success!") let alert = NSAlert() alert.messageText = "Success! 😎" alert.informativeText = "Your new wallpaper has been saved!" alert.alertStyle = .informational alert.addButton(withTitle: "Ok") alert.runModal() } catch { NSSound.beep() print("Error saving file") let alert = NSAlert() alert.messageText = "Error!" alert.informativeText = "Something went wrong and we couldn't save the file. Try again" alert.alertStyle = .informational alert.addButton(withTitle: "Ok") alert.runModal() } } } } } } // == .alertFirstButtonReturn
true
07ceb26c4d00d9016d0fe28830d9e05e0c8bc237
Swift
Tettere/Example2
/Example2/ViewController.swift
UTF-8
1,152
2.53125
3
[]
no_license
// // ViewController.swift // Example2 // // Created by 内藤大輝 on 2020/01/10. // Copyright © 2020 Hiroki Naito. All rights reserved. // import UIKit class ViewController: UIViewController { var date:String = "" var name:String = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //iPhone11proMaxの大きさに仮想想定 let Example:ScrollView = ScrollView(frame: CGRect(x: 0, y: 88,width: UIScreen.main.bounds.size.width, height: 725)); self.view.addSubview(Example) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { /* if(segue.identifier == "inputsegue"){ // let nextVC = segue.destination as? inputViewController // nextVC!.delegate = self as? GetDataprotocol }else if(segue.identifier == "collectphotosegue"){ }*/ } @IBAction func Toinput(_ sender: Any) { performSegue(withIdentifier: "inputsegue", sender: nil) } }
true
c5d3579887df663c03b99c6359e31feb422259de
Swift
Zulqurnain24/VideoANDImageRecording
/VideoANDImageRecording/Controllers/ReviewImageViewController.swift
UTF-8
3,972
2.609375
3
[]
no_license
// // ReviewImageViewController.swift // YouVRAssignment // // Created by Mohammad Zulqarnain on 09/07/2019. // Copyright © 2019 Mohammad Zulqarnain. All rights reserved. // import UIKit class ReviewImageViewController: UIViewController { @IBOutlet weak var saveToGalleryButton: UIButton! @IBOutlet weak var shareButton: UIButton! @IBOutlet weak var imageView: UIImageView! var imageURL: URL? override func viewDidLoad() { super.viewDidLoad() //Assign access identifiers saveToGalleryButton.accessibilityIdentifier = Strings.saveToGalleryButton.rawValue shareButton.accessibilityIdentifier = Strings.shareButton.rawValue // Do any additional setup after loading the view. } func saveImageDocumentDirectoryAndReturnURL(image: UIImage, imageName: String) -> NSURL? { let fileManager = FileManager.default let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(Strings.directoryFolderName.rawValue) if !fileManager.fileExists(atPath: path) { try! fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) } let url = NSURL(string: path) let imagePath = url!.appendingPathComponent(imageName) let urlString: String = imagePath!.absoluteString let imageData = image.pngData() fileManager.createFile(atPath: urlString as String, contents: imageData, attributes: nil) return url } @IBAction func shareImageAction(_ sender: Any) { guard let image = imageView.image as UIImage? else { return } self.imageURL = self.saveImageDocumentDirectoryAndReturnURL(image: image, imageName: "\(Strings.imageNamePostFix.rawValue)\(UtilityFunctions.shared.getNowDateString().trimmingCharacters(in: .whitespaces))") as URL? guard let url = imageURL as URL?, let urlString = "file://\(imageURL?.absoluteString)" as! String? else { return } print("url: \(urlString)") let activityItems: [Any] = [URL(string: urlString), Strings.imageShareGalleryname.rawValue] let activityController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) activityController.popoverPresentationController?.sourceView = view activityController.popoverPresentationController?.sourceRect = view.frame self.present(activityController, animated: true, completion: nil) } @IBAction func saveImageToGalleryAction(_ sender: Any) { guard let image = imageView.image as UIImage? else { return } UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil) } //MARK: - Add image to Library @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) { if error != nil { // we got back an error! let ac = UIAlertController(title: Strings.messageTitle.rawValue, message: Strings.unableToSaveImage.rawValue, preferredStyle: .alert) ac.addAction(UIAlertAction(title: Strings.affirmation.rawValue, style: .default)) present(ac, animated: true) } else { let ac = UIAlertController(title: Strings.messageTitle.rawValue, message: Strings.yourImageSuccessfullySaved.rawValue, preferredStyle: .alert) ac.addAction(UIAlertAction(title: Strings.affirmation.rawValue, style: .default)) present(ac, animated: true) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
true
b728f1cf3eb970aeed79a544bd573d30214cdb24
Swift
kliao2016/Golf-Client
/PGA Client/ViewModels/TournamentViewModel.swift
UTF-8
1,004
2.71875
3
[]
no_license
// // TournamentViewModel.swift // PGA Client // // Created by Kevin Liao on 7/8/18. // Copyright © 2018 Kevin Liao. All rights reserved. // import Foundation import AlamofireObjectMapper import Alamofire class TournamentViewModel { static var tournament: Tournament? typealias FetchCompletion = (() -> ()) static let tournamentURL = "https://ixgihulbxi.execute-api.us-east-1.amazonaws.com/dev/tournament" static let userInteractiveQueue = DispatchQueue.global(qos: .userInteractive) // Method to fetch current tournaments static func fetchTournament(completion: FetchCompletion?) { Alamofire.request(tournamentURL).responseObject(queue: userInteractiveQueue, keyPath: "body") { (response: DataResponse<Tournament>) in if let tournamentResponse = response.result.value { tournament = tournamentResponse } DispatchQueue.main.async { completion?() } } } }
true
1e891305f86983e6bc99155711fcd2468f245213
Swift
ePerrin/FinalWeather
/FinalWeather/Weather+CoreDataClass.swift
UTF-8
1,833
2.84375
3
[]
no_license
// // Weather+CoreDataClass.swift // FinalWeather // // Created by Emeric Perrin on 01/02/2017. // Copyright © 2017 Emeric. All rights reserved. // import Foundation import CoreData @objc(Weather) public class Weather: NSManagedObject { // MARK: Utilities fileprivate var isIconLoading = false class func insertNewEntityInContext(_ context: NSManagedObjectContext) -> Weather { return NSEntityDescription.insertNewObject(forEntityName: "Weather", into: context) as! Weather } func loadIconIfNeeded() { guard let iconName = self.iconName, self.icon == nil && !self.isIconLoading else { return } self.isIconLoading = true APIManager.sharedInstance().getImage(forIconName: iconName , success: { data in guard self.managedObjectContext != nil else { return } self.icon = data self.isIconLoading = false }, error: { error in guard self.managedObjectContext != nil else { return } self.isIconLoading = false }) } // MARK: Query class func get(byId id: Int64, inContext context: NSManagedObjectContext) -> Weather? { let request: NSFetchRequest = Weather.fetchRequest() request.predicate = NSPredicate(format:"\(Weather.id) == %i", id) do { let entities = try context.fetch(request) if entities.count == 1 { return entities.last } } catch { NSLog("Error just occured to get Weather with \(Weather.id) = \(id)") } return nil } }
true
ba04011c0750c10e5a4886900e51792f65792003
Swift
LeoQingit/EnjoyMusic
/MusicModel/Song.swift
UTF-8
5,007
2.546875
3
[]
no_license
// // Model.swift // Music // import UIKit import CoreLocation import CoreData import CoreDataHelpers public class Song: NSManagedObject { @NSManaged public fileprivate(set) var date: Date @NSManaged public fileprivate(set) var colors: [UIColor] @NSManaged public var creatorID: String? @NSManaged public var remoteIdentifier: RemoteRecordID? @NSManaged public fileprivate(set) var album___: Album @NSManaged public fileprivate(set) var album: Album? @NSManaged public fileprivate(set) var coverURL: String? @NSManaged public fileprivate(set) var duration: Double @NSManaged public fileprivate(set) var favorite: Int16 @NSManaged public var name: String? @NSManaged public var songURL: String? public var progress: Progress? public override func awakeFromInsert() { super.awakeFromInsert() primitiveDate = Date() } public static func insert(into moc: NSManagedObjectContext, songURL: String?) -> Song { let song: Song = moc.insertObject() song.songURL = songURL song.date = Date() return song } public static func insert(into moc: NSManagedObjectContext, songURL: String?, remoteIdentifier: RemoteRecordID? = nil, date: Date? = nil, creatorID: String? = nil) -> Song { let song: Song = moc.insertObject() song.songURL = songURL song.album = Album.findOrCreate(for: "未知", in: moc) song.remoteIdentifier = remoteIdentifier if let d = date { song.date = d } song.creatorID = creatorID return song } public override func willSave() { super.willSave() if changedForDelayedDeletion || changedForRemoteDeletion { removeFromAlbum() } } // MARK: Private @NSManaged fileprivate var primitiveDate: Date fileprivate func removeFromAlbum() { guard album != nil else { return } album = nil } } extension Song: Managed { public static var defaultSortDescriptors: [NSSortDescriptor] { return [NSSortDescriptor(key: #keyPath(date), ascending: false)] } public static var defaultPredicate: NSPredicate { return notMarkedForDeletionPredicate } } extension Song: DelayedDeletable { @NSManaged public var markedForDeletionDate: Date? } extension Song: RemoteDeletable { @NSManaged public var markedForRemoteDeletion: Bool } private let MaxColors = 8 extension UIImage { fileprivate var songColors: [UIColor] { var colors: [UIColor] = [] for c in dominantColors(.Music) where colors.count < MaxColors { colors.append(c) } return colors } } extension Data { public var songColors: [UIColor]? { guard count > 0 && count % 3 == 0 else { return nil } var rgbValues = Array(repeating: UInt8(), count: count) rgbValues.withUnsafeMutableBufferPointer { buffer in let voidPointer = UnsafeMutableRawPointer(buffer.baseAddress) let _ = withUnsafeBytes { bytes in memcpy(voidPointer, bytes, count) } } let rgbSlices = rgbValues.sliced(size: 3) return rgbSlices.map { slice in guard let color = UIColor(rawData: slice) else { fatalError("cannot fail since we know tuple is of length 3") } return color } } } extension Sequence where Iterator.Element == UIColor { public var songData: Data { let rgbValues = flatMap { $0.rgb } return rgbValues.withUnsafeBufferPointer { return Data(bytes: UnsafePointer<UInt8>($0.baseAddress!), count: $0.count) } } } private let ColorsTransformerName = "ColorsTransformer" extension Song { static func registerValueTransformers() { _ = self.__registerOnce } fileprivate static let __registerOnce: () = { ClosureValueTransformer.registerTransformer(withName: ColorsTransformerName, transform: { (colors: NSArray?) -> NSData? in guard let colors = colors as? [UIColor] else { return nil } return colors.songData as NSData }, reverseTransform: { (data: NSData?) -> NSArray? in return data .flatMap { ($0 as Data).songColors } .map { $0 as NSArray } }) }() } extension UIColor { fileprivate var rgb: [UInt8] { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: nil) return [UInt8(red * 255), UInt8(green * 255), UInt8(blue * 255)] } fileprivate convenience init?(rawData: [UInt8]) { if rawData.count != 3 { return nil } let red = CGFloat(rawData[0]) / 255 let green = CGFloat(rawData[1]) / 255 let blue = CGFloat(rawData[2]) / 255 self.init(red: red, green: green, blue: blue, alpha: 1) } }
true
90f92713ac04c61ba360da33f5891f878f92b84d
Swift
JamesLinus/CotEditor
/CotEditor/Sources/IntegrationPaneController.swift
UTF-8
3,916
2.5625
3
[ "Apache-2.0" ]
permissive
/* IntegrationPaneController.swift CotEditor https://coteditor.com Created by 1024jp on 2014-12-20. ------------------------------------------------------------------------------ © 2014-2017 1024jp Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Cocoa final class IntegrationPaneController: NSViewController { // MARK: Private Properties private static let commandURL = Bundle.main.sharedSupportURL!.appendingPathComponent("bin/cot").standardizedFileURL private static let preferredLinkURL = URL(fileURLWithPath: "/usr/local/bin/cot") private static let preferredLinkTargetURL: URL = { // cot in CotEditor.app in /Applications directory let applicationDirURL = try! FileManager.default.url(for: .applicationDirectory, in: .localDomainMask, appropriateFor: nil, create: false) let appName = AppInfo.bundleName return applicationDirURL.appendingPathComponent(appName).appendingPathExtension("app") }() @objc private dynamic var linkURL: URL! @objc private dynamic var installed = false @objc private dynamic var warning: String? // MARK: - // MARK: View Controller Methods /// update warnings before view appears override func viewWillAppear() { super.viewWillAppear() self.installed = self.validateSymLink() } // MARK: Private Methods /// check the destination of symlink and return whether 'cot' command is exists at '/usr/local/bin/' private func validateSymLink() -> Bool { // reset once self.warning = nil // check only preferred link location self.linkURL = type(of: self).preferredLinkURL // not installed yet (= can install) if !self.linkURL.isReachable { return false } // ???: `resolvingSymlinksInPath` doesn't work correctly on OS X 10.10 SDK, so I use a legacy way (2015-08). // let linkDestinationURL = self.linkURL.resolvingSymlinksInPath() let linkDestinationURL: URL = { let linkDestinationPath = try! FileManager.default.destinationOfSymbolicLink(atPath: self.linkURL.path) return URL(fileURLWithPath: linkDestinationPath) }() // treat symlink as "installed" if linkDestinationURL == self.linkURL { return true } // link to bundled cot is of course valid if linkDestinationURL == type(of: self).commandURL { return true } // link to '/Applications/CotEditor.app' is always valid if linkDestinationURL == type(of: self).preferredLinkTargetURL { return true } // display warning for invalid link if linkDestinationURL.isReachable { // link destinaiton is not running CotEditor self.warning = NSLocalizedString("The current 'cot' symbolic link doesn’t target the running CotEditor.", comment: "") } else { // link destination is unreachable self.warning = NSLocalizedString("The current 'cot' symbolic link may target an invalid path.", comment: "") } return true } }
true
122bd501cfca65e3ace82829c6a8bde0e1ae7808
Swift
backmeupplz/controlio-ios
/Controlio/AttachmentContainerView.swift
UTF-8
1,655
2.53125
3
[ "MIT" ]
permissive
// // AttachmentContainerView.swift // Controlio // // Created by Nikita Kolmogorov on 10/05/16. // Copyright © 2016 Nikita Kolmogorov. All rights reserved. // import UIKit import NohanaImagePicker import Photos protocol AttachmentContainerViewDelegate: class { func closeImagePicker() } class AttachmentContainerView: UIView, AllPickerDelegate { // MARK: - NohanaImagePickerControllerDelegate - func nohanaImagePickerDidCancel(_ picker: NohanaImagePickerController){ picker.dismiss(animated: true, completion: nil) } func nohanaImagePicker(_ picker: NohanaImagePickerController, didFinishPickingPhotoKitAssets pickedAssts: [PHAsset]){ for image in pickedAssts { wrapperView.attachments.append(picker.getAssetUIImage(image)) } picker.dismiss(animated: true, completion: nil) } // MARK: - Variables - weak var delegate: AttachmentContainerViewDelegate? // MARK: - Outlets - @IBOutlet weak var wrapperView: AttachmentWrapperView! // MARK: - View Life Cycle - override func layoutSubviews() { super.layoutSubviews() wrapperView.preferredMaxLayoutWidth = wrapperView.frame.width super.layoutSubviews() } // MARK: - UIImagePickerControllerDelegate - func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { wrapperView.attachments.append(pickedImage) } delegate?.closeImagePicker() } }
true
fb600d450194ab06ef8db09f544f77754798d76b
Swift
gergelymor/RPG-Attack-
/RPG Attack!/ViewController.swift
UTF-8
5,288
2.6875
3
[]
no_license
// // ViewController.swift // RPG Attack! // // Created by Gergely Mor Bacskai on 16/05/16. // Copyright © 2016 bacskai. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { //starting screen @IBOutlet weak var newGameLbl: UILabel! @IBOutlet weak var newGameBtn: UIButton! @IBOutlet weak var splashScreenBg: UIImageView! //graves to hide & unhide @IBOutlet weak var p2Grave: UIImageView! @IBOutlet weak var p1Grave: UIImageView! //to unhide on start @IBOutlet weak var p2Character: UIImageView! @IBOutlet weak var p1Character: UIImageView! @IBOutlet weak var infoLbl: UILabel! @IBOutlet weak var textHolderBg: UIImageView! @IBOutlet weak var p2HpLbl: UILabel! @IBOutlet weak var p1HpLbl: UILabel! @IBOutlet weak var p1AttackBtn: UIButton! @IBOutlet weak var p2AttackBtn: UIButton! //Sorry for these two @IBOutlet weak var p1AttackBtnLbl: UILabel! @IBOutlet weak var p2AttackBtnLbl: UILabel! @IBOutlet weak var backGroundImg: UIImageView! @IBOutlet weak var groundImg: UIImageView! var p1: Character! var p2: Character! var hitSound: AVAudioPlayer! var deathSound: AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() let hitPath = NSBundle.mainBundle().pathForResource("sword", ofType: "wav") let hitSoundURL = NSURL(fileURLWithPath: hitPath!) let deathPath = NSBundle.mainBundle().pathForResource("death", ofType: "wav") let deathSoundURL = NSURL(fileURLWithPath: deathPath!) do{ try hitSound = AVAudioPlayer(contentsOfURL: hitSoundURL) hitSound.prepareToPlay() try deathSound = AVAudioPlayer(contentsOfURL: deathSoundURL) deathSound.prepareToPlay() }catch let err as NSError{ print(err.debugDescription) } } @IBAction func onP1AttackTapped(sender: AnyObject) { if p1.isAlive(){ let attack = Int(arc4random_uniform(UInt32(p1.maxAttackPwr))+10) if p2.getInjured(attack) == true{ infoLbl.text = "Orc attacked Knight for \(attack) HP!" p2HpLbl.text = "\(p2.hp) HP" playHitSound() } else{ infoLbl.text = "Orc killed Knight!" p2HpLbl.text = "0 HP" p2Character.hidden = true p2Grave.hidden = false playDeathSound() NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(ViewController.gameEnd), userInfo: nil, repeats: false) } } } @IBAction func onP2AttackTapped(sender: AnyObject) { if p2.isAlive(){ let attack = Int(arc4random_uniform(UInt32(p2.maxAttackPwr))+10) if p1.getInjured(attack) == true{ infoLbl.text = "Knight attacked Orc for \(attack) HP!" p1HpLbl.text = "\(p1.hp) HP" playHitSound() } else{ infoLbl.text = "Knight killed Orc!" p1HpLbl.text = "0 HP" p1Character.hidden = true p1Grave.hidden = false playDeathSound() NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(ViewController.gameEnd), userInfo: nil, repeats: false) } } } @IBAction func onNewGameTapped(sender: AnyObject) { gameInit() } func gameInit(){ p1 = Character(hp: 100, maxAttackPwr: 20) p2 = Character(hp: 100, maxAttackPwr: 20) p1HpLbl.text = "\(p1.hp) HP" p2HpLbl.text = "\(p2.hp) HP" infoLbl.text = "Press Attack to attack!" newGameBtn.hidden = true newGameLbl.hidden = true splashScreenBg.hidden = true p1Character.hidden = false p2Character.hidden = false infoLbl.hidden = false textHolderBg.hidden = false p1HpLbl.hidden = false p2HpLbl.hidden = false p1AttackBtn.hidden = false p2AttackBtn.hidden = false p1AttackBtnLbl.hidden = false p2AttackBtnLbl.hidden = false backGroundImg.hidden = false groundImg.hidden = false p1Grave.hidden = true p2Grave.hidden = true } func gameEnd(){ newGameBtn.hidden = false newGameLbl.hidden = false splashScreenBg.hidden = false p1Character.hidden = true p2Character.hidden = true infoLbl.hidden = true textHolderBg.hidden = true p1HpLbl.hidden = true p2HpLbl.hidden = true p1AttackBtn.hidden = true p2AttackBtn.hidden = true p1AttackBtnLbl.hidden = true p2AttackBtnLbl.hidden = true backGroundImg.hidden = true groundImg.hidden = true p1Grave.hidden = true p2Grave.hidden = true } func playHitSound(){ if hitSound.playing{ hitSound.stop() } hitSound.play() } func playDeathSound(){ deathSound.play() } }
true
acd00e919911611104626dd42b0a5d76c0d8e7ed
Swift
tauypaldiyev/Jusan-Test
/Jusan Test/Scenes/News/Modules/NewsTab/View/Cell/NewsTabCell.swift
UTF-8
1,314
2.65625
3
[]
no_license
// // NewsTabCell.swift // Jusan Test // // Created by Rauan on 28.06.2021. // import SnapKit import UIKit public final class NewsTabCell: UICollectionViewCell { public override var isSelected: Bool { didSet { configureColors() } } // MARK: - Properties private lazy var titleLabel: UILabel = { let view = UILabel() view.textAlignment = .center return view }() // MARK: - Init public override init(frame: CGRect) { super.init(frame: frame) configureViews() } required init?(coder: NSCoder) { return nil } // MARK: - Methods public func configure(with viewModel: NewsTabCellProtocol) { titleLabel.attributedText = viewModel.title } private func configureViews() { [titleLabel].forEach { contentView.addSubview($0) } configureColors() makeConstraints() } private func makeConstraints() { titleLabel.snp.makeConstraints { make in make.edges.equalToSuperview() } } private func configureColors() { backgroundColor = .clear titleLabel.textColor = isSelected ? .black : .gray } }
true
7d51414e2a139426d8401ef5b691e5ed2a734e92
Swift
flip902/swift
/99Problems.playground/Contents.swift
UTF-8
2,475
4
4
[]
no_license
//: Playground - noun: a place where people can play import UIKit import Foundation class List<T> { var value: T var nextItem: List<T>? convenience init?(_ values: T...) { self.init(Array(values)) } init?(_ values: [T]) { guard let first = values.first else { return nil } value = first nextItem = List(Array(values.suffix(from: 1))) } } // P01: Find the last element of a linked list extension List { // var last: T { // guard let element = self.nextItem else { // return self.value // } // return element.last // } public var last: T { return nextItem?.last ?? value } } List(1, 1, 2, 3, 5, 8)!.last // P02: Find the last but one element of a linked list extension List { var pennultimate: T? { guard let next = self.nextItem else { return nil } if next.nextItem == nil { return value } return next.pennultimate } } List(1, 1, 2, 3, 5, 8)?.pennultimate // P03: Find the Nth element of a linked list //extension List { // subscript(index: Int) -> T? { // var list = self // for _ in 0..<index { // if list.nextItem == nil { // return nil // } // list = list.nextItem! // } // return list.value // } //} extension List { public subscript(index: Int) -> T? { guard index >= 0 else { return nil } return (index == 0) ? value : nextItem?[index-1] } } let list = List(1, 1, 2, 3, 5, 8)! list[4] // P04: Find the number of elements of a linked list extension List { var length: Int { var count = 1 var current = self while let next = current.nextItem { count += 1 current = next } return count } } list.length // P05: Reverse a linked list extension List { public func reverse() -> List { let head = self let tail = self.nextItem head.nextItem = nil return reversing(head: head, tail: tail) } private func reversing(head: List, tail: List?) -> List { guard let tail = tail else { return head } let newTail = tail.nextItem let newHead = tail newHead.nextItem = head return reversing(head: newHead, tail: newTail) } } let reversedList = list.reverse() print(String(describing: reversedList))
true