repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Staance/DKImagePickerController
DKImagePickerController/DKImagePickerController.swift
1
8807
// // DKImagePickerController.swift // DKImagePickerController // // Created by ZhangAo on 14-10-2. // Copyright (c) 2014年 ZhangAo. All rights reserved. // import UIKit import AssetsLibrary // MARK: - Public DKAsset /** * An `DKAsset` object represents a photo or a video managed by the `DKImagePickerController`. */ public class DKAsset: NSObject { /// Returns a CGImage of the representation that is appropriate for displaying full screen. public private(set) lazy var fullScreenImage: UIImage? = { return UIImage(CGImage: (self.originalAsset?.defaultRepresentation().fullScreenImage().takeUnretainedValue())!) }() /// Returns a CGImage representation of the asset. public private(set) lazy var fullResolutionImage: UIImage? = { return UIImage(CGImage: (self.originalAsset?.defaultRepresentation().fullResolutionImage().takeUnretainedValue())!) }() /// The url uniquely identifies an asset that is an image or a video. public private(set) var url: NSURL? /// It's a square thumbnail of the asset. public private(set) var thumbnailImage: UIImage? /// When the asset was an image, it's false. Otherwise true. public private(set) var isVideo: Bool = false /// play time duration(seconds) of a video. public private(set) var duration: Double? internal var isFromCamera: Bool = false internal var originalAsset: ALAsset? internal init(originalAsset: ALAsset) { super.init() self.thumbnailImage = UIImage(CGImage:originalAsset.thumbnail().takeUnretainedValue()) self.url = originalAsset.valueForProperty(ALAssetPropertyAssetURL) as? NSURL self.originalAsset = originalAsset let assetType = originalAsset.valueForProperty(ALAssetPropertyType) as! NSString if assetType == ALAssetTypeVideo { let duration = originalAsset.valueForProperty(ALAssetPropertyDuration) as! NSNumber self.isVideo = true self.duration = duration.doubleValue } } internal init(image: UIImage) { super.init() self.isFromCamera = true self.fullScreenImage = image self.fullResolutionImage = image self.thumbnailImage = image } // Compare two DKAssets override public func isEqual(object: AnyObject?) -> Bool { let another = object as! DKAsset! if let url = self.url, anotherUrl = another.url { return url.isEqual(anotherUrl) } else { return false } } } /** * allPhotos: Get all photos assets in the assets group. * allVideos: Get all video assets in the assets group. * allAssets: Get all assets in the group. */ public enum DKImagePickerControllerAssetType : Int { case allPhotos, allVideos, allAssets } public struct DKImagePickerControllerSourceType : OptionSetType { private var value: UInt = 0 init(_ value: UInt) { self.value = value } // MARK: _RawOptionSetType public init(rawValue value: UInt) { self.value = value } // MARK: NilLiteralConvertible public init(nilLiteral: ()) { self.value = 0 } // MARK: RawRepresentable public var rawValue: UInt { return self.value } // MARK: BitwiseOperationsType public static var allZeros: DKImagePickerControllerSourceType { return self.init(0) } public static var Camera: DKImagePickerControllerSourceType { return self.init(1 << 0) } public static var Photo: DKImagePickerControllerSourceType { return self.init(1 << 1) } } // MARK: - Public DKImagePickerController /** * The `DKImagePickerController` class offers the all public APIs which will affect the UI. */ public class DKImagePickerController: UINavigationController { /// The maximum count of assets which the user will be able to select. public var maxSelectableCount = 999 /// The type of picker interface to be displayed by the controller. public var assetType = DKImagePickerControllerAssetType.allAssets /// If sourceType is Camera will cause the assetType & maxSelectableCount & allowMultipleTypes & defaultSelectedAssets to be ignored. public var sourceType: DKImagePickerControllerSourceType = [.Camera, .Photo] /// Whether allows to select photos and videos at the same time. public var allowMultipleTypes = true /// The callback block is executed when user pressed the select button. public var didSelectAssets: ((assets: [DKAsset]) -> Void)? /// The callback block is executed when user pressed the cancel button. public var didCancel: (() -> Void)? /// It will have selected the specific assets. public var defaultSelectedAssets: [DKAsset]? { didSet { if let defaultSelectedAssets = self.defaultSelectedAssets { for (index, asset) in defaultSelectedAssets.enumerate() { if asset.isFromCamera { self.defaultSelectedAssets!.removeAtIndex(index) } } self.selectedAssets = defaultSelectedAssets self.updateDoneButtonTitle() } } } internal var selectedAssets = [DKAsset]() private lazy var doneButton: UIButton = { let button = UIButton(type: UIButtonType.Custom) button.setTitle("", forState: UIControlState.Normal) button.setTitleColor(self.navigationBar.tintColor, forState: UIControlState.Normal) button.reversesTitleShadowWhenHighlighted = true button.addTarget(self, action: "done", forControlEvents: UIControlEvents.TouchUpInside) return button }() public convenience init() { let rootVC = DKAssetGroupDetailVC() self.init(rootViewController: rootVC) rootVC.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: self.doneButton) rootVC.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "dismiss") } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override public func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectedImage:", name: DKImageSelectedNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "unselectedImage:", name: DKImageUnselectedNotification, object: nil) } private func updateDoneButtonTitle() { if self.selectedAssets.count > 0 { self.doneButton.setTitle(DKImageLocalizedString.localizedStringForKey("select") + "(\(selectedAssets.count))", forState: UIControlState.Normal) } else { self.doneButton.setTitle("", forState: UIControlState.Normal) } self.doneButton.sizeToFit() } internal func dismiss() { self.dismissViewControllerAnimated(true, completion: nil) self.didCancel?() } internal func done() { self.dismissViewControllerAnimated(true, completion: nil) self.didSelectAssets?(assets: self.selectedAssets) } // MARK: - Notifications internal func selectedImage(noti: NSNotification) { if let asset = noti.object as? DKAsset { selectedAssets.append(asset) if asset.isFromCamera { self.done() } else { updateDoneButtonTitle() } } } internal func unselectedImage(noti: NSNotification) { if let asset = noti.object as? DKAsset { selectedAssets.removeAtIndex(selectedAssets.indexOf(asset)!) updateDoneButtonTitle() } } // MARK: - Handles Orientation public override func shouldAutorotate() -> Bool { return false } public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait } } // MARK: - Utilities internal extension UIViewController { var imagePickerController: DKImagePickerController? { get { let nav = self.navigationController if nav is DKImagePickerController { return nav as? DKImagePickerController } else { return nil } } } }
mit
5605376e55cf132d3a8208bd0522cc91
33.802372
155
0.634639
5.572785
false
false
false
false
pixeldock/RxAppState
Example/RxAppState/UILabel+Rx.swift
1
2339
// // UILabel+Rx.swift // RxAppState // // Created by Jörn Schoppe on 06.03.16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxAppState extension UILabel { public var rx_appState: AnyObserver<AppState> { return Binder(self) { label, appState in switch appState { case .active: label.backgroundColor = UIColor.green label.text = "ACTIVE" case .inactive: label.backgroundColor = UIColor.yellow label.text = "INACTIVE" case .background: label.backgroundColor = UIColor.red label.text = "BACKGROUND" case .terminated: label.backgroundColor = UIColor.lightGray label.text = "TERMINATED" } } .asObserver() } public var rx_firstLaunch: AnyObserver<Bool> { return Binder(self) { label, isFirstLaunch in if isFirstLaunch { label.backgroundColor = UIColor.green label.text = "YES" } else { label.backgroundColor = UIColor.red label.text = "NO" } } .asObserver() } public var rx_viewState: AnyObserver<ViewControllerViewState> { return Binder(self) { label, appState in switch appState { case .viewDidLoad: label.backgroundColor = UIColor.blue label.text = "VIEW DID LOAD" case .viewDidLayoutSubviews: label.backgroundColor = UIColor.magenta label.text = "VIEW DID LAYOUT SUBVIEWS" case .viewWillAppear: label.backgroundColor = UIColor.yellow label.text = "VIEW WILL APPEAR" case .viewDidAppear: label.backgroundColor = UIColor.green label.text = "VIEW DID APPEAR" case .viewWillDisappear: label.backgroundColor = UIColor.orange label.text = "VIEW WILL DISAPPEAR" case .viewDidDisappear: label.backgroundColor = UIColor.red label.text = "VIEW DID DISAPPEAR" } } .asObserver() } }
mit
3a1c84b9ee42cee09b9f0d3c0b6a4c18
31.013699
67
0.537013
5.15894
false
false
false
false
mbeloded/beaconDemo
PassKitApp/PassKitApp/Classes/UI/NavigationController/RootViewController.swift
1
3804
// // RootViewController.swift // PassKitApp // // Created by Alexandr Chernyy on 10/10/14. // Copyright (c) 2014 Alexandr Chernyy. All rights reserved. // import UIKit class RootViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let image = UIImage(named: BACK_BUTTON_IMAGE) let leftView = UIView(frame: CGRectMake(0, 0, image.size.width * 1.2, 35)) leftView.backgroundColor = UIColor.clearColor() let btn0 = UIButton(frame: CGRectMake(0,0,image.size.width, image.size.height)) btn0.setImage(image, forState: UIControlState.Normal) btn0.addTarget(self, action: "backAction", forControlEvents: UIControlEvents.TouchUpInside) leftView.addSubview(btn0) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftView) let image1 = UIImage(named: "options_button") let image2 = UIImage(named: "ios7-help-icon") let rightView = UIView(frame: CGRectMake(0, 0, image1.size.width * 1.2 + image2.size.width * 1.2, 30)) rightView.backgroundColor = UIColor.clearColor() let btn1 = UIButton(frame: CGRectMake(0,0,image1.size.width, image1.size.height)) btn1.setImage(image1, forState: UIControlState.Normal) btn1.addTarget(self, action: "optionsAction", forControlEvents: UIControlEvents.TouchUpInside) rightView.addSubview(btn1) let btn2 = UIButton(frame: CGRectMake(image1.size.width * 1.2 + 10, 0,image2.size.width, image2.size.height)) btn2.setImage(image2, forState: UIControlState.Normal) btn2.addTarget(self, action: "helpAction", forControlEvents: UIControlEvents.TouchUpInside) rightView.addSubview(btn2) let rightBtn = UIBarButtonItem(customView: rightView) self.navigationItem.rightBarButtonItem = rightBtn; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func backAction() { self.navigationController?.popViewControllerAnimated(true) } func optionsAction() { var optionsController:OptionsViewController var mainStoryboard:UIStoryboard mainStoryboard = UIStoryboard(name: "Main", bundle: nil) optionsController = mainStoryboard.instantiateViewControllerWithIdentifier("Options") as OptionsViewController self.navigationController?.pushViewController(optionsController, animated: true) } func helpAction() { let alert = UIAlertView() alert.title = "Comming soon..." alert.message = "" alert.addButtonWithTitle(BUTTON_TEXT_OK) alert.show() // let mainView:UIView = UIApplication.sharedApplication().windows.last as UIView // var view:UIView = UIView(frame: CGRectMake(0, 0, mainView.frame.size.width, mainView.frame.size.height)) // view.backgroundColor = UIColor.blackColor() // view.alpha = 0.5 // mainView.addSubview(view) } func hideLeftButton() { self.navigationController?.setNavigationBarHidden(false, animated: false) self.navigationItem.setHidesBackButton(true, animated: false) self.navigationItem.leftBarButtonItem = nil; } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
94a9ca31a3ee32d5f0e84e4e1c5a39bb
35.576923
120
0.667192
4.766917
false
false
false
false
squiffy/AlienKit
Example/Pods/p2.OAuth2/Sources/Base/extensions.swift
1
3031
// // extensions.swift // OAuth2 // // Created by Pascal Pfiffner on 6/6/14. // Copyright 2014 Pascal Pfiffner // // 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 // // http://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 Foundation extension NSHTTPURLResponse { /// A localized string explaining the current `statusCode`. public var statusString: String { get { return NSHTTPURLResponse.localizedStringForStatusCode(self.statusCode) } } } extension String { private static var wwwFormURLPlusSpaceCharacterSet: NSCharacterSet = NSMutableCharacterSet.wwwFormURLPlusSpaceCharacterSet() /// Encodes a string to become x-www-form-urlencoded; the space is encoded as plus sign (+). var wwwFormURLEncodedString: String { let characterSet = String.wwwFormURLPlusSpaceCharacterSet return (stringByAddingPercentEncodingWithAllowedCharacters(characterSet) ?? "").stringByReplacingOccurrencesOfString(" ", withString: "+") } /// Decodes a percent-encoded string and converts the plus sign into a space. var wwwFormURLDecodedString: String { let rep = stringByReplacingOccurrencesOfString("+", withString: " ") return rep.stringByRemovingPercentEncoding ?? rep } } extension NSMutableCharacterSet { /** Return the character set that does NOT need percent-encoding for x-www-form-urlencoded requests INCLUDING SPACE. YOU are responsible for replacing spaces " " with the plus sign "+". RFC3986 and the W3C spec are not entirely consistent, we're using W3C's spec which says: http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm > If the byte is 0x20 (U+0020 SPACE if interpreted as ASCII): > - Replace the byte with a single 0x2B byte ("+" (U+002B) character if interpreted as ASCII). > If the byte is in the range 0x2A (*), 0x2D (-), 0x2E (.), 0x30 to 0x39 (0-9), 0x41 to 0x5A (A-Z), 0x5F (_), > 0x61 to 0x7A (a-z) > - Leave byte as-is */ class func wwwFormURLPlusSpaceCharacterSet() -> NSMutableCharacterSet { let set = NSMutableCharacterSet.alphanumericCharacterSet() set.addCharactersInString("-._* ") return set } } extension NSURLRequest { /** Print the requests's headers and body to stdout. */ public func oauth2_print() { print("---") print("HTTP/1.1 \(HTTPMethod ?? "METHOD") \(URL?.description ?? "/")") allHTTPHeaderFields?.forEach() { print("\($0): \($1)") } print("") if let data = HTTPBody, let body = NSString(data: data, encoding: NSUTF8StringEncoding) { print(body as String) } print("---") } }
mit
8091c0d5af91e0adbe23fe1f54930edb
32.677778
140
0.716595
3.921087
false
false
false
false
MrPudin/Skeem
IOS/Prevoir/AppDelegate.swift
1
2869
// // AppDelegate.swift // Prevoir // // Created by Zhu Zhan Yan on 17/9/16. // Copyright © 2016 SSTInc. All rights reserved. // import UIKit public enum SKMUserDefaultKey:String { case suite = "pvr_ud_suite" case use = "pvr_ud_use" case setting = "pvr_ud_setting" } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { //UI var window: UIWindow? //App Status var use_cnt:Int! //App Data var DB:SKMDatabase! var DBC:SKMDataController! var CFG:SKMConfig! //App Logic var SCH:SKMScheduler! //Storage var ud:UserDefaults! //MARK:App Delegate func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { //Init Data self.use_cnt = 0 self.DB = SKMDatabase() self.DBC = SKMDataController(db: DB) self.CFG = SKMConfig(cfg: Dictionary<String,NSCoding>()) self.SCH = SKMScheduler(dataCtrl: self.DBC,cfg: self.CFG) self.loadUD() return true } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { try? DB.load() return true } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { DB.commit() } func applicationWillEnterForeground(_ application: UIApplication) { try? DB.load() } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { DB.commit() } //MARK:Additional Methods public func loadUD() { //Load user Defaults if let ud = UserDefaults(suiteName: SKMUserDefaultKey.suite.rawValue) { self.ud = ud self.use_cnt = ud.integer(forKey: SKMUserDefaultKey.use.rawValue) } else { //No Suite for User Defaults UserDefaults().addSuite(named: SKMUserDefaultKey.suite.rawValue) let ud = UserDefaults(suiteName: SKMUserDefaultKey.suite.rawValue)! self.ud = ud } //Load App Settins If Present if self.use_cnt > 1 { let cfg_data = (ud.object(forKey: SKMUserDefaultKey.setting.rawValue) as! [String : NSCoding]) self.CFG = SKMConfig(cfg: cfg_data) } //Update use count self.use_cnt = self.use_cnt + 1 } public func commitUD() { //Save App Status ud.set(self.use_cnt, forKey: SKMUserDefaultKey.use.rawValue) ud.set(self.CFG.cfg, forKey: SKMUserDefaultKey.setting.rawValue) self.ud.synchronize() } }
mit
bc90dddb650929f07eec3780abf666a6
25.555556
152
0.621339
4.255193
false
false
false
false
gregomni/swift
test/Generics/sr12120.swift
3
1449
// RUN: %target-typecheck-verify-swift -debug-generic-signatures -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s // CHECK: sr12120.(file).Swappable1@ // CHECK-NEXT: Requirement signature: <Self where Self == Self.[Swappable1]Swapped.[Swappable1]Swapped, Self.[Swappable1]B == Self.[Swappable1]Swapped.[Swappable1]A, Self.[Swappable1]Swapped : Swappable1> protocol Swappable1 { associatedtype A associatedtype B associatedtype Swapped : Swappable1 where Swapped.B == A, // expected-warning {{redundant same-type constraint 'Self.Swapped.B' == 'Self.A'}} Swapped.A == B, Swapped.Swapped == Self } // CHECK: sr12120.(file).Swappable2@ // CHECK-NEXT: Requirement signature: <Self where Self == Self.[Swappable2]Swapped.[Swappable2]Swapped, Self.[Swappable2]B == Self.[Swappable2]Swapped.[Swappable2]A, Self.[Swappable2]Swapped : Swappable2> protocol Swappable2 { associatedtype A associatedtype B associatedtype Swapped : Swappable2 where Swapped.B == A, Swapped.Swapped == Self } // CHECK: sr12120.(file).Swappable3@ // CHECK-NEXT: Requirement signature: <Self where Self == Self.[Swappable3]Swapped.[Swappable3]Swapped, Self.[Swappable3]B == Self.[Swappable3]Swapped.[Swappable3]A, Self.[Swappable3]Swapped : Swappable3> protocol Swappable3 { associatedtype A associatedtype B associatedtype Swapped : Swappable3 where Swapped.A == B, Swapped.Swapped == Self }
apache-2.0
7fd6f17e200abe56d73ac10aa4b25424
44.28125
204
0.727398
3.51699
false
false
false
false
akio0911/UIKitTips
UIKitTips/ContentInset/ContentInsetTableViewController.swift
1
2540
// // ContentInsetTableViewController.swift // UIKitTips // // Created by akio0911 on 2016/05/13. // Copyright © 2016年 akio0911. All rights reserved. // import UIKit class ContentInsetTableViewController: UITableViewController { enum CellData { case HiddenNav case Text(String) var text: String? { switch self { case .HiddenNav: return nil case let .Text(text): return text } } var backgroundColor: UIColor { switch self { case .HiddenNav: return UIColor.lightGrayColor() case .Text: return UIColor.whiteColor() } } } var cellDatas: [CellData] = [] private var statusAndNavigtationBarHeight: CGFloat { var statusHeight: CGFloat { return UIApplication.sharedApplication().statusBarFrame.height } var navigationHeight: CGFloat { return navigationController!.navigationBar.bounds.height } return statusHeight + navigationHeight } override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false tableView.scrollIndicatorInsets = UIEdgeInsets(top: statusAndNavigtationBarHeight, left: 0, bottom: 0, right: 0) cellDatas += [CellData.HiddenNav] cellDatas += (1...30).map{ (num: Int) -> CellData in CellData.Text(num.description) } } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellDatas.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let cellData = cellDatas[indexPath.row] cell.backgroundColor = cellData.backgroundColor cell.textLabel?.text = cellData.text return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch cellDatas[indexPath.row] { case .HiddenNav: return statusAndNavigtationBarHeight case .Text: return 44 } } }
mit
e4d01f123a89a1a416973125616fcdac
30.320988
118
0.58652
5.527233
false
false
false
false
cavalcantedosanjos/ND-OnTheMap
OnTheMap/OnTheMap/ViewControllers/StudentsTableViewController.swift
1
4909
// // StudentsTableViewController.swift // OnTheMap // // Created by Joao Anjos on 06/02/17. // Copyright © 2017 Joao Anjos. All rights reserved. // import UIKit class StudentsTableViewController: UITableViewController { // MARK: - Properties let kLocationSegue = "locationSegue" // MARK: - Life Cycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) tableView.reloadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == kLocationSegue) { let vc = segue.destination as! SearchLocationViewController vc.delegate = self } } // MARK: - Actions @IBAction func logoutButton_Clicked(_ sender: Any) { self.dismiss(animated: true, completion: nil) logout() } @IBAction func refreshButton_Clicked(_ sender: Any) { getStudentsLocation() } @IBAction func pinButton_Clicked(_ sender: Any) { getCurrentLocation { self.checkLocation() } } // MARK: - Services func getStudentsLocation() { LocationService.sharedInstance().getStudentsLocation(onSuccess: { (studentsLocation) in StudentDataSource.sharedInstance.studentData.removeAll() if studentsLocation.count > 0 { StudentDataSource.sharedInstance.studentData = studentsLocation } }, onFailure: { (error) in }, onCompleted: { self.tableView.reloadData() }) } func getCurrentLocation(onCompletedWithSuccess: @escaping ()-> Void) { LocationService.sharedInstance().getCurrentLocation(onSuccess: { (locations) in if let location = locations.first{ User.current.location = location } onCompletedWithSuccess() }, onFailure: { (errorRespons) in self.showMessage(message: errorRespons.error!, title: "") }, onCompleted: { //Nothing }) } func logout() { StudentService.sharedInstance().logout(onSuccess: { //Nothing }, onFailure: { (error) in //Nothing }, onCompleted: { //Nothing }) } // MARK: - UITableView override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return StudentDataSource.sharedInstance.studentData.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "studentCell") as! StudentsTableViewCell cell.setup(location: StudentDataSource.sharedInstance.studentData[indexPath.row]) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if let url = URL(string: StudentDataSource.sharedInstance.studentData[indexPath.row].mediaUrl!) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { showMessage(message: "Can't Open URL", title: "") } } // MARK: - Helpers func checkLocation() { if User.current.location != nil{ let alert: UIAlertController = UIAlertController(title: "", message: "You Have Already Posted a Student Location. Would You Like to Overwrite. Your Current Location?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Overwrite", style: .default, handler: { (action) in self.performSegue(withIdentifier: "locationSegue", sender: nil) })) alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in alert.dismiss(animated: true, completion: nil) })) self.present(alert, animated: true, completion: nil) } else { performSegue(withIdentifier: "locationSegue", sender: nil) } } func showMessage(message: String, title: String) { let alert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in alert.dismiss(animated: true, completion: nil) })) self.present(alert, animated: true, completion: nil) } } // MARK: - SearchLocationViewControllerDelegate extension StudentsTableViewController: SearchLocationViewControllerDelegate { func didFinishedPostLocation() { self.getStudentsLocation() } }
mit
4ea97048782e33be602d8bf90e294e2e
32.387755
203
0.607172
5.160883
false
false
false
false
HassanEskandari/Eureka
Source/Rows/StepperRow.swift
4
2781
// // StepperRow.swift // Eureka // // Created by Andrew Holt on 3/4/16. // Copyright © 2016 Xmartlabs. All rights reserved. // import UIKit // MARK: StepperCell open class StepperCell: Cell<Double>, CellType { @IBOutlet public weak var stepper: UIStepper! @IBOutlet public weak var valueLabel: UILabel? required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { let stepper = UIStepper() self.stepper = stepper self.stepper.translatesAutoresizingMaskIntoConstraints = false let valueLabel = UILabel() self.valueLabel = valueLabel self.valueLabel?.translatesAutoresizingMaskIntoConstraints = false self.valueLabel?.numberOfLines = 1 super.init(style: style, reuseIdentifier: reuseIdentifier) addSubview(stepper) addSubview(valueLabel) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[v]-[s]-|", options: .alignAllCenterY, metrics: nil, views: ["s": stepper, "v": valueLabel])) addConstraint(NSLayoutConstraint(item: stepper, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .centerY, relatedBy: .equal, toItem: stepper, attribute: .centerY, multiplier: 1.0, constant: 0)) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func setup() { super.setup() selectionStyle = .none stepper.addTarget(self, action: #selector(StepperCell.valueChanged), for: .valueChanged) valueLabel?.textColor = stepper.tintColor } deinit { stepper.removeTarget(self, action: nil, for: .allEvents) } open override func update() { super.update() stepper.isEnabled = !row.isDisabled stepper.value = row.value ?? 0 stepper.alpha = row.isDisabled ? 0.3 : 1.0 valueLabel?.alpha = row.isDisabled ? 0.3 : 1.0 valueLabel?.text = row.displayValueFor?(row.value) detailTextLabel?.text = nil } @objc func valueChanged() { row.value = stepper.value row.updateCell() } } // MARK: StepperRow open class _StepperRow: Row<StepperCell> { required public init(tag: String?) { super.init(tag: tag) displayValueFor = { value in guard let value = value else { return nil } return DecimalFormatter().string(from: NSNumber(value: value)) } } } /// Double row that has a UIStepper as accessoryType public final class StepperRow: _StepperRow, RowType { required public init(tag: String?) { super.init(tag: tag) } }
mit
ff01176f16ddcbe393f2a025aeb071c9
31.325581
168
0.651799
4.542484
false
false
false
false
ifabijanovic/RxBattleNet
RxBattleNet/WoW/Model/Challenge.swift
1
4542
// // Challenge.swift // RxBattleNet // // Created by Ivan Fabijanović on 07/08/16. // Copyright © 2016 Ivan Fabijanovic. All rights reserved. // import SwiftyJSON public extension WoW { public struct Challenge: Model { public struct Time: Model { public let time: Int public let hours: Int public let minutes: Int public let seconds: Int public let milliseconds: Int public let isPositive: Bool internal init(json: JSON) { self.time = json["time"].intValue self.hours = json["hours"].intValue self.minutes = json["minutes"].intValue self.seconds = json["seconds"].intValue self.milliseconds = json["milliseconds"].intValue self.isPositive = json["isPositive"].boolValue } } public struct Map: Model { public let id: Int public let name: String public let slug: String public let hasChallengeMode: Bool public let bronzeCriteria: WoW.Challenge.Time public let silverCriteria: WoW.Challenge.Time public let goldCriteria: WoW.Challenge.Time internal init(json: JSON) { self.id = json["id"].intValue self.name = json["name"].stringValue self.slug = json["slug"].stringValue self.hasChallengeMode = json["hasChallengeMode"].boolValue self.bronzeCriteria = WoW.Challenge.Time(json: json["bronzeCriteria"]) self.silverCriteria = WoW.Challenge.Time(json: json["silverCriteria"]) self.goldCriteria = WoW.Challenge.Time(json: json["goldCriteria"]) } } public struct Group: Model { public struct Member: Model { public struct Spec: Model { public let name: String public let role: String public let backgroundImage: String public let icon: String public let description: String public let order: Int internal init(json: JSON) { self.name = json["name"].stringValue self.role = json["role"].stringValue self.backgroundImage = json["backgroundImage"].stringValue self.icon = json["icon"].stringValue self.description = json["description"].stringValue self.order = json["order"].intValue } } public let character: WoW.Character public let spec: WoW.Challenge.Group.Member.Spec internal init(json: JSON) { self.character = WoW.Character(json: json["character"]) self.spec = WoW.Challenge.Group.Member.Spec(json: json["spec"]) } } public let ranking: Int public let time: WoW.Challenge.Time public let date: String public let medal: String public let faction: String public let isRecurring: Bool public let members: [WoW.Challenge.Group.Member] internal init(json: JSON) { self.ranking = json["ranking"].intValue self.time = WoW.Challenge.Time(json: json["time"]) self.date = json["date"].stringValue self.medal = json["medal"].stringValue self.faction = json["faction"].stringValue self.isRecurring = json["isRecurring"].boolValue self.members = json["members"].map { WoW.Challenge.Group.Member(json: $1) } } } // MARK: - Properties public let realm: WoW.Realm? public let map: WoW.Challenge.Map public let groups: [WoW.Challenge.Group] // MARK: - Init internal init(json: JSON) { let realmJson = json["realm"] self.realm = realmJson.isExists() ? WoW.Realm(json: realmJson) : nil self.map = WoW.Challenge.Map(json: json["map"]) self.groups = json["groups"].map { WoW.Challenge.Group(json: $1) } } } }
mit
17645be03c35ff419e56e27cdd118546
36.520661
91
0.514097
5.272938
false
false
false
false
judi0713/TouTiao
TouTiao/View/SettingMenuAction.swift
2
1663
// // SettingMenuAction.swift // TouTiao // // Created by plusub on 4/26/16. // Copyright © 2016 tesths. All rights reserved. // import Cocoa import ServiceManagement class SettingMenuAction { let launcherAppIdentifier = "com.tesths.TouTiaoLauncher" var autoLaunch: Bool = true let startMenu = NSMenuItem(title: "开机启动", action: #selector(startLogin), keyEquivalent: "") func perform(_ sender: NSView) { let delegate = NSApplication.shared().delegate as! MainViewController let menu = NSMenu() // let hotShare = NSMenuItem() // hotShare.title = "热门分享" // let share7 = NSMenu(title: "最近 7 天") // let share30 = NSMenu(title: "最近 30 天") // let share30 = NSMenu().addItem(withTitle: "最近 30 天", action: #selector(delegate.quit), keyEquivalent: "q") // let hare90 = NSMenu().addItem(withTitle: "最近 90 天", action: #selector(delegate.quit), keyEquivalent: "q") // hotShare.submenu = share7 // hotShare.submenu = share30 // menu.addItem(NSMenuItem(title: "开机启动", action: #selector(startLogin), keyEquivalent: "")) menu.addItem(NSMenuItem(title: "退出", action: #selector(delegate.quit), keyEquivalent: "q")) NSMenu.popUpContextMenu(menu, with: NSApp.currentEvent!, for: sender) } @objc func startLogin() { autoLaunch = !autoLaunch if autoLaunch == true { startMenu.title = "开机启动" } else { startMenu.title = "开机不启动" } SMLoginItemSetEnabled(launcherAppIdentifier as CFString, autoLaunch) } }
mit
a85c88908719875441a653a05fce041a
31.489796
116
0.63191
3.808612
false
false
false
false
KazuCocoa/sampleTddInSwift
AppMenu/AppMenu/MenuViewController.swift
1
1482
// // MenuViewController.swift // AppMenu // // Created by KazuakiMATSUO on 1/2/15. // Copyright (c) 2015 KazuakiMATSUO. All rights reserved. // import UIKit class MenuViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var dataSource: MenuTableDataSource? var tapHandlerBuilder: MenuItemTapHandlerBuilder? override func viewDidLoad() { super.viewDidLoad() title = "App Menu" //tableView.delegate = dataSource //tableView.dataSource = dataSource } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectMenuItemNotification:", name: MenuTableDataSourceDidSelectItemNotification, object: nil) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self, name: MenuTableDataSourceDidSelectItemNotification, object: nil) } func didSelectMenuItemNotification(notification: NSNotification?) { var menuItem: MenuItem? = notification!.object as? MenuItem if let tapHandler = tapHandlerBuilder?.tapHandlerForMenuItem(menuItem) { self.navigationController?.pushViewController(tapHandler, animated: true) } } }
mit
24f5ec85aeb2bfdc2e58af0f9dd338d5
28.64
73
0.663968
5.448529
false
false
false
false
marcetcheverry/Outlets
Widget/TodayViewController.swift
1
2543
// // TodayViewController.swift // Widget // // Created by Marc on 5/31/16. // Copyright © 2016 Tap Light Software. All rights reserved. // import UIKit import NotificationCenter class TodayViewController: UIViewController, NCWidgetProviding { @IBOutlet weak var stackView1: UIStackView! @IBOutlet weak var stackView2: UIStackView! @IBOutlet weak var stackView3: UIStackView! @IBOutlet weak var stackView4: UIStackView! @IBOutlet weak var stackView5: UIStackView! @IBOutlet weak var stackViewAll: UIStackView! override func viewDidLoad() { super.viewDidLoad() extensionContext?.widgetLargestAvailableDisplayMode = .expanded updatedInterfaceBasedOnDisplayMode() } func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) { updatedInterfaceBasedOnDisplayMode(maxSize: maxSize) } private func updatedInterfaceBasedOnDisplayMode(maxSize: CGSize? = nil) { if extensionContext?.widgetActiveDisplayMode == .compact { stackView1.isHidden = true stackView2.isHidden = true stackView3.isHidden = true stackView4.isHidden = true stackView5.isHidden = true stackViewAll.isHidden = false let targetSize = view.systemLayoutSizeFitting(UILayoutFittingCompressedSize) if maxSize != nil && targetSize.width <= maxSize!.width && targetSize.height <= maxSize!.height { preferredContentSize = targetSize } else { preferredContentSize = maxSize ?? targetSize } } else if extensionContext?.widgetActiveDisplayMode == .expanded { stackView1.isHidden = false stackView2.isHidden = false stackView3.isHidden = false stackView4.isHidden = false stackView5.isHidden = false stackViewAll.isHidden = false preferredContentSize = view.systemLayoutSizeFitting(UILayoutFittingExpandedSize) } } @IBAction func touchedOn(_ sender: UIButton) { toggleOutlet(number: sender.tag, status: .on) } @IBAction func touchedOff(_ sender: UIButton) { toggleOutlet(number: sender.tag, status: .off) } private func toggleOutlet(number: Int, status: Outlets.status) { assert(number > 0) extensionContext?.open(URL(string: "outlets://\(number)/\(status.rawValue)")!, completionHandler: nil) } }
mit
a35f4cef037fbf43656fd97c3edcad49
35.314286
118
0.662864
5.317992
false
false
false
false
itsbriany/Weather
Weather/Weather/AppDelegate.swift
1
6085
// // AppDelegate.swift // Weather // // Created by Brian Yip on 2016-02-10. // Copyright © 2016 Brian Yip. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "itsbriany.Weather" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Weather", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
apache-2.0
1f633e06bc00cc6a4e9486a55dcc83a0
53.810811
291
0.719264
5.906796
false
false
false
false
jonnguy/HSTracker
HSTracker/Database/Models/ServerInfo.swift
2
1121
// // ServerInfo.swift // HSTracker // // Created by Benjamin Michotte on 5/01/17. // Copyright © 2017 Benjamin Michotte. All rights reserved. // import Foundation import RealmSwift import HearthMirror class ServerInfo: Object { @objc dynamic var address = "" @objc dynamic var auroraPassword = "" @objc dynamic var clientHandle = 0 @objc dynamic var gameHandle = 0 @objc dynamic var mission = 0 @objc dynamic var port = 0 @objc dynamic var resumable = false @objc dynamic var spectatorMode = false @objc dynamic var spectatorPassword = "" @objc dynamic var version = "" convenience init(info: MirrorGameServerInfo) { self.init() address = info.address auroraPassword = info.auroraPassword clientHandle = info.clientHandle as? Int ?? 0 gameHandle = info.gameHandle as? Int ?? 0 mission = info.mission as? Int ?? 0 port = info.port as? Int ?? 0 resumable = info.resumable spectatorMode = info.spectatorMode spectatorPassword = info.spectatorPassword version = info.version } }
mit
df92b33148fb90a4ff606d90977c6935
27.717949
60
0.658929
4.258555
false
false
false
false
strawberrycode/SafariOauthLogin
SafariOauthLogin/Auth.swift
1
2728
// // Auth.swift // SafariOauthLogin // // Created by Catherine Schwartz on 27/07/2015. // Copyright © 2015 StrawberryCode. All rights reserved. // import Foundation import Alamofire let INSTAGRAM_CLIENT_ID = "" let INSTAGRAM_CLIENT_SECRET = "" let INSTAGRAM_REDIRECT_URL = "" // Inspired by: https://github.com/MoZhouqi/PhotoBrowser struct AuthInstagram { enum Router: URLRequestConvertible { /// Returns a URL request or throws if an `Error` was encountered. /// /// - throws: An `Error` if the underlying `URLRequest` is `nil`. /// /// - returns: A URL request. public func asURLRequest() throws -> URLRequest { // follow example here: http://stackoverflow.com/a/39414724 let (path, parameters): (String, [String: AnyObject]) = { switch self { case .popularPhotos (let userID, let accessToken): let params = ["access_token": accessToken] let pathString = "/v1/users/" + userID + "/media/recent" return (pathString, params as [String : AnyObject]) case .requestOauthCode: _ = "/oauth/authorize/?client_id=" + Router.clientID + "&redirect_uri=" + Router.redirectURI + "&response_type=code" return ("/photos", [:]) } }() let BaeseURL = URL(string: Router.baseURLString) let URLRequest = Foundation.URLRequest(url: BaeseURL!.appendingPathComponent(path)) return try Alamofire.URLEncoding.default.encode(URLRequest, with: parameters) } static let baseURLString = "https://api.instagram.com" static let clientID = INSTAGRAM_CLIENT_ID static let redirectURI = INSTAGRAM_REDIRECT_URL static let clientSecret = INSTAGRAM_CLIENT_SECRET static let authorizationURL = URL(string: Router.baseURLString + "/oauth/authorize/?client_id=" + Router.clientID + "&redirect_uri=" + Router.redirectURI + "&response_type=code")! case popularPhotos(String, String) case requestOauthCode static func requestAccessTokenURLStringAndParms(_ code: String) -> (URLString: String, Params: [String: AnyObject]) { let params = ["client_id": Router.clientID, "client_secret": Router.clientSecret, "grant_type": "authorization_code", "redirect_uri": Router.redirectURI, "code": code] let pathString = "/oauth/access_token" let urlString = AuthInstagram.Router.baseURLString + pathString return (urlString, params as [String : AnyObject]) } } }
mit
1ade21ab58d36d7c0f89e83f8b56d8d2
39.701493
187
0.604327
4.590909
false
false
false
false
curtisforrester/SwiftNonStandardLibrary
source/SwiftNonStandardLibrary/Console.swift
1
884
// Swift Non-Standard Library // // Created by Russ Bishop // http://github.com/xenadu/SwiftNonStandardLibrary // // MIT licensed; see LICENSE for more information import Foundation ///reads a line from standard input /// ///@param max:Int /// specifies the number of bytes to read, must be at least 1 to account for null terminator. /// /// ///@return /// the string, or nil if an error was encountered trying to read Stdin public func readln(max:Int = 8192) -> String? { var buf:Array<CChar> = [] var c = getchar() let maxBuf = max - 1; let newline = CInt(10) assert(maxBuf > 1, "max must be between 1 and Int.max") while c != EOF && c != newline && buf.count < max { buf += CChar(c) c = getchar() } //always null terminate buf += CChar(0) return buf.withUnsafePointerToElements { String.fromCString($0) } }
mit
587531b6ed936f2350cc9ac57eb75d1f
24.257143
93
0.635747
3.652893
false
false
false
false
LipliStyle/Liplis-iOS
Liplis/CtvCellGeneralSettingCheck.swift
1
4445
// // CtvCellGeneralSettingCheck.swift // Liplis // //設定画面 要素 チェックボックス // //アップデート履歴 // 2015/05/02 ver0.1.0 作成 // 2015/05/09 ver1.0.0 リリース // 2015/05/16 ver1.4.0 リファクタリング // // Created by sachin on 2015/05/02. // Copyright (c) 2015年 sachin. All rights reserved. // import UIKit class CtvCellGeneralSettingCheck : UITableViewCell { ///============================= ///カスタムセル要素 internal var parView : ViewSetting! ///============================= ///カスタムセル要素 internal var lblTitle = UILabel(); internal var lblContent = UILabel(); internal var btnCheckBox = UIButton(); ///============================= ///レイアウト情報 internal var viewWidth : CGFloat! = 0 ///============================= ///設定インデックス internal var settingIdx : Int! = 0 ///============================= ///ON/OFF internal var on : Bool! = false //============================================================ // //初期化処理 // //============================================================ internal override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.lblTitle = UILabel(frame: CGRectMake(20, 5, 300, 15)); self.lblTitle.text = ""; self.lblTitle.font = UIFont.systemFontOfSize(16) self.addSubview(self.lblTitle); self.lblContent = UILabel(frame: CGRectMake(20, 24, 300, 15)); self.lblContent.text = ""; self.lblContent.font = UIFont.systemFontOfSize(10) self.addSubview(self.lblContent); //チェックボッックス self.btnCheckBox = UIButton() self.btnCheckBox.titleLabel?.font = UIFont.systemFontOfSize(12) self.btnCheckBox.frame = CGRectMake(0,0,32,32) self.btnCheckBox.layer.masksToBounds = true self.btnCheckBox.setTitle("", forState: UIControlState.Normal) self.btnCheckBox.addTarget(self, action: "onClickCheck:", forControlEvents: .TouchDown) self.btnCheckBox.setImage(UIImage(named: "checkOff.png"), forState: UIControlState.Normal) self.btnCheckBox.layer.cornerRadius = 3.0 self.addSubview(btnCheckBox) } /* ビューを設定する */ internal func setView(parView : ViewSetting) { self.parView = parView } /* 要素の位置を調整する */ internal func setSize(viewWidth : CGFloat) { self.viewWidth = viewWidth let locationY : CGFloat = CGFloat(viewWidth - 50 - 9) self.btnCheckBox.frame = CGRectMake(locationY, 6, 32, 32) } /* 値をセットする */ internal func setVal(settingIdx : Int, val : Int) { self.on = LiplisUtil.int2Bit(val) self.settingIdx = settingIdx if(self.on == true) { let imgOn : UIImage = UIImage(named: "checkOn.png")! self.btnCheckBox.setImage(imgOn, forState: UIControlState.Normal) } else { let imgOff : UIImage = UIImage(named: "checkOff.png")! self.btnCheckBox.setImage(imgOff, forState: UIControlState.Normal) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //============================================================ // //イベントハンドラ // //============================================================ /* スイッチ選択 */ internal func onClickCheck(sender: UIButton) { if(self.on == true) { print("チェックボックスOFF") let imgOff : UIImage = UIImage(named: "checkOff.png")! self.btnCheckBox.setImage(imgOff, forState: UIControlState.Normal) self.on = false self.parView.selectCheck(self.settingIdx,val: false) } else { print("チェックボックスON") let imgOn : UIImage = UIImage(named: "checkOn.png")! self.btnCheckBox.setImage(imgOn, forState: UIControlState.Normal) self.on = true self.parView.selectCheck(self.settingIdx,val: true) } } }
mit
7a94597458eb6897b8156ff40a7c4055
27.958333
98
0.530103
4.402323
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClientUnitTests/Spec/User/CreateMultipleCreatorsRequestSpec.swift
1
2423
// // CreateMultipleCreatorsRequestSpec.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Quick import Nimble @testable import CreatubblesAPIClient class CreateMultipleCreatorsRequestSpec: QuickSpec { override func spec() { describe("New creator request") { let amount = 15 let birthYear = 2_000 let group = "test" var multipleCreatorsRequest: CreateMultipleCreatorsRequest { return CreateMultipleCreatorsRequest(amount: amount, birthYear: birthYear, groupName: group) } it("Should have proper endpoint") { let request = multipleCreatorsRequest expect(request.endpoint) == "creator_builder_jobs" } it("Should have proper method") { let request = multipleCreatorsRequest expect(request.method) == RequestMethod.post } it("Should have proper parameters") { let request = multipleCreatorsRequest let params = request.parameters expect(params["amount"] as? Int) == amount expect(params["birth_year"] as? Int) == birthYear expect(params["group"] as? String) == group } } } }
mit
68710f78af159023aa27f84547c761dd
38.721311
108
0.662402
4.875252
false
false
false
false
curiousurick/BluetoothBackupSensor-iOS
CSS427Bluefruit_Connect/BluetoothLE Test WatchKit Extension/BLESessionManager.swift
4
2165
// // BLESessionManager.swift // Adafruit Bluefruit LE Connect // // Created by Collin Cunningham on 11/3/15. // Copyright © 2015 Adafruit Industries. All rights reserved. // import Foundation import WatchConnectivity class BLESessionManager: NSObject, WCSessionDelegate { static let sharedInstance = BLESessionManager() // var session:WCSession? var deviceConnected:Bool = false override init(){ super.init() if WCSession.isSupported() { let session = WCSession.defaultSession() session.delegate = self session.activateSession() } } func sendRequest(message:[String:AnyObject], sender:BLEInterfaceController) { sender.showDebugInfo("attempting to send request") if WCSession.defaultSession().reachable == false { sender.showDebugInfo("WCSession is unreachable") return } WCSession.defaultSession().sendMessage(message, replyHandler: { (replyInfo) -> Void in switch (replyInfo["connected"] as? Bool) { //received correctly formatted reply case let connected where connected != nil: if connected == true { //app has connection to ble device sender.showDebugInfo("device connected") sender.respondToConnected() self.deviceConnected = true } else { //app has NO connection to ble device sender.showDebugInfo("no device connected") sender.respondToNotConnected() self.deviceConnected = false } default: sender.showDebugInfo("no connection info in reply") sender.respondToNotConnected() self.deviceConnected = false } }, errorHandler: { (error) -> Void in sender.showDebugInfo("\(error)") // received reply w error }) } }
mit
931a3ae829a6798fb4963071d3780b8e
31.313433
95
0.545749
5.945055
false
false
false
false
josve05a/wikipedia-ios
Wikipedia/Third Party Code/SWStepSlider/SWStepSlider.swift
2
7981
// // SWStepSlider.swift // Pods // // Created by Sarun Wongpatcharapakorn on 2/4/16. // // import UIKit @IBDesignable open class SWStepSlider: UIControl { @IBInspectable open var minimumValue: Int = 0 @IBInspectable open var maximumValue: Int = 4 @IBInspectable open var value: Int = 2 { didSet { if self.value != oldValue && self.continuous { self.sendActions(for: .valueChanged) } } } @IBInspectable open var continuous: Bool = true // if set, value change events are generated any time the value changes due to dragging. default = YES let trackLayer = CALayer() var trackHeight: CGFloat = 1 var trackColor = UIColor(red: 152.0/255.0, green: 152.0/255.0, blue: 152.0/255.0, alpha: 1) var tickHeight: CGFloat = 8 var tickWidth: CGFloat = 1 var tickColor = UIColor(red: 152.0/255.0, green: 152.0/255.0, blue: 152.0/255.0, alpha: 1) let thumbLayer = CAShapeLayer() var thumbFillColor = UIColor.white var thumbStrokeColor = UIColor(red: 222.0/255.0, green: 222.0/255.0, blue: 222.0/255.0, alpha: 1) var thumbDimension: CGFloat = 28 var stepWidth: CGFloat { return self.trackWidth / CGFloat(self.maximumValue) } var trackWidth: CGFloat { return self.bounds.size.width - self.thumbDimension } var trackOffset: CGFloat { return (self.bounds.size.width - self.trackWidth) / 2 } var numberOfSteps: Int { return self.maximumValue - self.minimumValue + 1 } required public init?(coder: NSCoder) { super.init(coder: coder) self.commonInit() } override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } fileprivate func commonInit() { self.isAccessibilityElement = true self.accessibilityTraits = UIAccessibilityTraits.adjustable self.trackLayer.backgroundColor = self.trackColor.cgColor self.layer.addSublayer(trackLayer) self.thumbLayer.backgroundColor = UIColor.clear.cgColor self.thumbLayer.fillColor = self.thumbFillColor.cgColor self.thumbLayer.strokeColor = self.thumbStrokeColor.cgColor self.thumbLayer.lineWidth = 0.5 self.thumbLayer.frame = CGRect(x: 0, y: 0, width: self.thumbDimension, height: self.thumbDimension) self.thumbLayer.path = UIBezierPath(ovalIn: self.thumbLayer.bounds).cgPath // Shadow self.thumbLayer.shadowOffset = CGSize(width: 0, height: 2) self.thumbLayer.shadowColor = UIColor.black.cgColor self.thumbLayer.shadowOpacity = 0.3 self.thumbLayer.shadowRadius = 2 self.thumbLayer.contentsScale = UIScreen.main.scale // Tap Gesture Recognizer let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:))) self.addGestureRecognizer(tap) self.layer.addSublayer(self.thumbLayer) } open override func layoutSubviews() { super.layoutSubviews() var rect = self.bounds rect.origin.x = self.trackOffset rect.origin.y = (rect.size.height - self.trackHeight) / 2 rect.size.height = self.trackHeight rect.size.width = self.trackWidth self.trackLayer.frame = rect let center = CGPoint(x: self.trackOffset + CGFloat(self.value) * self.stepWidth, y: self.bounds.midY) let thumbRect = CGRect(x: center.x - self.thumbDimension / 2, y: center.y - self.thumbDimension / 2, width: self.thumbDimension, height: self.thumbDimension) self.thumbLayer.frame = thumbRect } open override func draw(_ rect: CGRect) { super.draw(rect) guard let ctx = UIGraphicsGetCurrentContext() else { return } ctx.saveGState() // Draw ticks ctx.setFillColor(self.tickColor.cgColor) for index in 0..<self.numberOfSteps { let x = self.trackOffset + CGFloat(index) * self.stepWidth - 0.5 * self.tickWidth let y = self.bounds.midY - 0.5 * self.tickHeight // Clip the tick let tickPath = UIBezierPath(rect: CGRect(x: x , y: y, width: self.tickWidth, height: self.tickHeight)) // Fill the tick ctx.addPath(tickPath.cgPath) ctx.fillPath() } ctx.restoreGState() } open override var intrinsicContentSize : CGSize { return CGSize(width: self.thumbDimension * CGFloat(self.numberOfSteps), height: self.thumbDimension) } // MARK: - Touch var previousLocation: CGPoint! var dragging = false var originalValue: Int! open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let location = touch.location(in: self) self.originalValue = self.value if self.thumbLayer.frame.contains(location) { self.dragging = true } else { self.dragging = false } self.previousLocation = location return self.dragging } open override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let location = touch.location(in: self) let deltaLocation = location.x - self.previousLocation.x let deltaValue = self.deltaValue(deltaLocation) if deltaLocation < 0 { // minus self.value = self.clipValue(self.originalValue - deltaValue) } else { self.value = self.clipValue(self.originalValue + deltaValue) } CATransaction.begin() CATransaction.setDisableActions(true) // Update UI without animation self.setNeedsLayout() CATransaction.commit() return true } open override func endTracking(_ touch: UITouch?, with event: UIEvent?) { self.previousLocation = nil self.originalValue = nil self.dragging = false if self.continuous == false { self.sendActions(for: .valueChanged) } } open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return !(gestureRecognizer is UIPanGestureRecognizer) } // MARK: - Helper func deltaValue(_ deltaLocation: CGFloat) -> Int { return Int(round(abs(deltaLocation) / self.stepWidth)) } func clipValue(_ value: Int) -> Int { return min(max(value, self.minimumValue), self.maximumValue) } // MARK: - Tap Gesture Recognizer @objc func handleTap(_ sender: UIGestureRecognizer) { if !self.dragging { let pointTapped: CGPoint = sender.location(in: self) let widthOfSlider: CGFloat = self.bounds.size.width let newValue = pointTapped.x * (CGFloat(self.numberOfSteps) / widthOfSlider) self.value = Int(newValue) if self.continuous == false { self.sendActions(for: .valueChanged) } self.setNeedsLayout() } } // MARK: - Accessibility open override func accessibilityIncrement() { guard self.value < self.maximumValue else { return } self.value = self.value + 1 if self.continuous == false { self.sendActions(for: .valueChanged) } self.setNeedsLayout() } open override func accessibilityDecrement() { guard self.value > self.minimumValue else { return } self.value = self.value - 1 if self.continuous == false { self.sendActions(for: .valueChanged) } self.setNeedsLayout() } }
mit
a896787365d529b15257081d59edf195
31.311741
165
0.5998
4.594704
false
false
false
false
Seanalair/GreenAR
GreenAR/Classes/Helpers/GeometryHelper.swift
1
10188
// // GeometryHelper.swift // Room Saver // // Created by Daniel Grenier on 9/21/17. // Copyright © 2017 Greenear Games. All rights reserved. // import Foundation import SceneKit /** Helper class with methods for manipulating three-dimensional coordinates and creating triangles and planes. */ class GeometryHelper { /** Calculates the distance between two `SCNVector3`s. - Parameter firstPosition: The first position. - Parameter secondPosition: The second position. - Returns: The distance between the two positions. */ public static func distanceBetweenPositions(_ firstPosition: SCNVector3, _ secondPosition: SCNVector3) -> Float { let deltaX = secondPosition.x - firstPosition.x let deltaY = secondPosition.y - firstPosition.y let deltaZ = secondPosition.z - firstPosition.z return sqrt(pow(deltaX, 2) + pow(deltaY, 2) + pow(deltaZ, 2)) } /** Calculates the coordinates produced by moving some distance from one point toward another point in three-dimensional space. - Parameter firstPosition: The position of the starting coordinates. - Parameter secondPosition: The position of the coordinates used to indicate a direction to move. - Parameter distance: The distance to move toward the `secondPosition` from the `firstPosition` - Returns: An `SCNVector3` representing the calculated coordinates. */ public static func positionByMovingTowardPosition(firstPosition: SCNVector3, secondPosition: SCNVector3, distance: Float) -> SCNVector3 { let totalDistance = distanceBetweenPositions(firstPosition, secondPosition) let proportionalX = (secondPosition.x - firstPosition.x) / totalDistance let proportionalY = (secondPosition.y - firstPosition.y) / totalDistance let proportionalZ = (secondPosition.z - firstPosition.z) / totalDistance return SCNVector3(firstPosition.x + (distance * proportionalX), firstPosition.y + (distance * proportionalY), firstPosition.z + (distance * proportionalZ)) } /** Applies an inset to the four corners of a rectangle by modifying the `SCNVector3` objects passed to it. - Parameter firstCorner: An `SCNVector3` representing the coordinates of the first corner. - Parameter secondCorner: An `SCNVector3` representing the coordinates of the second corner. - Parameter thirdCorner: An `SCNVector3` representing the coordinates of the third corner. - Parameter fourthCorner: An `SCNVector3` representing the coordinates of the fourth corner. */ public static func cornersWithInset(_ firstCorner: SCNVector3, _ secondCorner: SCNVector3, _ thirdCorner: SCNVector3, _ fourthCorner: SCNVector3, insetDistance: Float) -> (SCNVector3, SCNVector3, SCNVector3, SCNVector3) { if (insetDistance == 0) { return (firstCorner, secondCorner, thirdCorner, fourthCorner) } var positions = [firstCorner, secondCorner, thirdCorner, fourthCorner] for index in 0...3 { let positionToInset = positions[index] var positionAtGreatestDistance: SCNVector3? var greatestDistance: Float? for innerIndex in 0...3 { if innerIndex == index { continue } if (greatestDistance == nil || distanceBetweenPositions(positionToInset, positions[innerIndex]) > greatestDistance!) { positionAtGreatestDistance = positions[innerIndex] greatestDistance = distanceBetweenPositions(positionToInset, positionAtGreatestDistance!) } } positions[index] = GeometryHelper.positionByMovingTowardPosition(firstPosition: positionToInset, secondPosition: positionAtGreatestDistance!, distance: insetDistance) } return (positions[0], positions[1], positions[2], positions[3]) } /** Creates an `SCNGeometry` triangle from three sets of coordinates. - Parameter firstCorner: An `SCNVector3` representing the coordinates of the first corner of the triangle. - Parameter secondCorner: An `SCNVector3` representing the coordinates of the second corner of the triangle. - Parameter thirdCorner: An `SCNVector3` representing the coordinates of the third corner of the triangle. - Returns: An `SCNGeometry` object representing the triangle defined by the three points. */ public static func triangleFrom(firstCorner: SCNVector3, secondCorner: SCNVector3, thirdCorner: SCNVector3) -> SCNGeometry { let indices: [Int32] = [0, 1, 2] let source = SCNGeometrySource(vertices: [firstCorner, secondCorner, thirdCorner]) let element = SCNGeometryElement(indices: indices, primitiveType: .triangles) return SCNGeometry(sources: [source], elements: [element]) } /** Creates an `SCNNode` containing the two triangles defined by four sets of coordinates. - Parameter firstPosition: An `SCNVector3` representing the coordinates of the first corner. - Parameter secondPosition: An `SCNVector3` representing the coordinates of the second corner. - Parameter thirdPosition: An `SCNVector3` representing the coordinates of the third corner. - Parameter fourthPosition: An `SCNVector3` representing the coordinates of the fourth corner. - Parameter cornerInsetDistance: The distance to inset the corners of the plane from the vertices they represent (helpful in differentiating adjacent planes). Defaults to 0. - Parameter visible: A `Bool` indicating whether the plane should be visible. If `true`, the plane will be rendered with the provided color and opacity. If `false`, it will be rendered invisibly but occlude objects behind it. Defaults to `true`. - Parameter color: The color to render the plane as. Defaults to `UIColor.white`. - Parameter opacity: The opacity to render the plane with. Defaults to `0.1`. - Returns: An `SCNNode` containing the plane defined by the four corners provided. */ public static func createPlane(firstPosition: SCNVector3, secondPosition: SCNVector3, thirdPosition: SCNVector3, fourthPosition: SCNVector3, cornerInsetDistance: Float = 0, visible: Bool = true, color: UIColor = .white, opacity: CGFloat = 0.1) -> SCNNode { let (firstCorner, secondCorner, thirdCorner, fourthCorner) = cornersWithInset(firstPosition, secondPosition, thirdPosition, fourthPosition, insetDistance: cornerInsetDistance) let planeNode = SCNNode() let firstTriangle = triangleFrom(firstCorner: firstCorner, secondCorner: secondCorner, thirdCorner: thirdCorner) let firstTriangleNode = SCNNode(geometry: firstTriangle) if (visible) { firstTriangleNode.geometry?.firstMaterial?.diffuse.contents = color } else { firstTriangleNode.geometry?.firstMaterial?.colorBufferWriteMask = [] } firstTriangleNode.geometry?.firstMaterial?.isDoubleSided = true planeNode.addChildNode(firstTriangleNode) // We need the hypotenuse to determine which two corners to use for the second triangle var hypotenuse = (secondCorner, thirdCorner) var hypotenuseLength = distanceBetweenPositions(secondCorner, thirdCorner) // If another pair of points is separated by a larger distance, use that pair of points instead if (distanceBetweenPositions(firstCorner, secondCorner) > hypotenuseLength) { // Update the length so we can check against the third possible pair of points also hypotenuseLength = distanceBetweenPositions(firstCorner, secondCorner) hypotenuse = (firstCorner, secondCorner) } if (distanceBetweenPositions(firstCorner, thirdCorner) > hypotenuseLength) { // We don't need to update our length again here - this is the last check against it hypotenuse = (firstCorner, thirdCorner) } let secondTriangle = triangleFrom(firstCorner: hypotenuse.0, secondCorner: hypotenuse.1, thirdCorner: fourthCorner) let secondTriangleNode = SCNNode(geometry: secondTriangle) if (visible) { secondTriangleNode.geometry?.firstMaterial?.diffuse.contents = color } else { secondTriangleNode.geometry?.firstMaterial?.colorBufferWriteMask = [] } secondTriangleNode.geometry?.firstMaterial?.isDoubleSided = true planeNode.addChildNode(secondTriangleNode) planeNode.opacity = opacity planeNode.renderingOrder = -1 return planeNode } }
mit
2668543a20b2c1c8520782948754d106
51.782383
252
0.602434
5.650028
false
false
false
false
tgsala/HackingWithSwift
project28/project28/ViewController.swift
1
4504
// // ViewController.swift // project28 // // Created by g5 on 3/16/16. // Copyright © 2016 tgsala. All rights reserved. // import UIKit import LocalAuthentication class ViewController: UIViewController { @IBOutlet weak var secret: UITextView! override func viewDidLoad() { super.viewDidLoad() // adjustForKeyboard let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "adjustForKeyboard:", name: UIKeyboardWillHideNotification, object: nil) notificationCenter.addObserver(self, selector: "adjustForKeyboard:", name: UIKeyboardWillChangeFrameNotification, object: nil) notificationCenter.addObserver(self, selector: "saveSecretMessage", name: UIApplicationWillResignActiveNotification, object: nil) title = "Nothing to see here" } @IBAction func authenticateUser(sender: UIButton) { //self.unlockSecretMessage() let context = LAContext() var error: NSError? if context.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: &error) { //if true { let reason = "Identify yourself!" context.evaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { [unowned self] (success: Bool, authenticationError: NSError?) -> Void in dispatch_async(dispatch_get_main_queue()) { if success { self.unlockSecretMessage() } else { if let error = authenticationError { if error.code == LAError.UserFallback.rawValue { let ac = UIAlertController(title: "Passcode? Ha!", message: "It's Touch ID or nothing – sorry!", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(ac, animated: true, completion: nil) return } } let ac = UIAlertController(title: "Authentication failed", message: "Your fingerprint could not be verified; please try again.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(ac, animated: true, completion: nil) } } } } else { let ac = UIAlertController(title: "Touch ID not available", message: "Your device is not configured for Touch ID.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(ac, animated: true, completion: nil) } } func unlockSecretMessage() { secret.hidden = false title = "Secret stuff!" if let text = KeychainWrapper.stringForKey("SecretMessage") { secret.text = text } } func saveSecretMessage() { if !secret.hidden { KeychainWrapper.setString(secret.text, forKey: "SecretMessage") secret.resignFirstResponder() secret.hidden = true title = "Nothing to see here" } } func adjustForKeyboard(notification: NSNotification) { let userInfo = notification.userInfo! let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let keyboardViewEndFrame = view.convertRect(keyboardScreenEndFrame, fromView: view.window) if notification.name == UIKeyboardWillHideNotification { secret.contentInset = UIEdgeInsetsZero } else { secret.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0) } secret.scrollIndicatorInsets = secret.contentInset let selectedRange = secret.selectedRange secret.scrollRangeToVisible(selectedRange) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
unlicense
b7d178fb676b66a60a1fe29ce001e1c4
37.801724
152
0.587203
5.822768
false
false
false
false
gdamron/PaulaSynth
PaulaSynth/UserSettings.swift
1
2375
// // UserSettings.swift // AudioEngine2 // // Created by Grant Damron on 10/4/16. // Copyright © 2016 Grant Damron. All rights reserved. // import UIKit import Foundation class UserSettings: NSObject { static let sharedInstance = UserSettings() fileprivate enum Keys: String { case LowNote = "lowNote" case PolyOn = "polyphonyOn" case Scale = "scale" case Sound = "sound" case TabHidden = "tabHidden" } let tabHiddenThresh = 3 var lowNote = 48 { didSet { dirty = true } } var polyphonyOn = false { didSet { dirty = true } } var scale = Scale.Blues { didSet { dirty = true } } var tabHiddenCount = 0 { didSet { dirty = true tabHiddenCount = min(tabHiddenCount, tabHiddenThresh) } } var hideSettingsTab: Bool { return tabHiddenCount >= tabHiddenThresh } var sound = SynthSound.Square fileprivate var dirty = false open func save() { if (dirty) { let defaults = UserDefaults.standard defaults.set(lowNote, forKey: Keys.LowNote.rawValue) defaults.set(polyphonyOn, forKey: Keys.PolyOn.rawValue) defaults.set(scale.rawValue, forKey: Keys.Scale.rawValue) defaults.set(sound.name, forKey: Keys.Sound.rawValue) defaults.set(tabHiddenCount, forKey: Keys.TabHidden.rawValue) defaults.synchronize() dirty = false } } open func load() { let defaults = UserDefaults.standard if defaults.object(forKey: Keys.LowNote.rawValue) != nil { lowNote = defaults.integer(forKey: Keys.LowNote.rawValue) } // default value of false is acceptable polyphonyOn = defaults.bool(forKey: Keys.PolyOn.rawValue) // default vale of 0 is fine tabHiddenCount = defaults.integer(forKey: Keys.TabHidden.rawValue) if let val = defaults.string(forKey: Keys.Scale.rawValue), let s = Scale(rawValue: val) { scale = s } if let soundVal = defaults.string(forKey: Keys.Sound.rawValue) { sound = SynthSound(key: soundVal) } } }
apache-2.0
65b0d5826722bdd581c7e0d61a255fbb
25.087912
74
0.564448
4.38817
false
false
false
false
seanoshea/computer-science-in-swift
computer-science-in-swift/QuickSort.swift
1
2480
// Copyright (c) 2015-2016 Sean O'Shea. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation class QuickSort { func quickSort(_ items:inout [Int]) -> [Int] { let left:Int = 0 let right:Int = items.count - 1 return qs(&items, left:left, right:right) } func qs(_ items:inout [Int], left:Int = 0, right:Int) -> [Int] { var index:Int if items.count > 1 { index = partition(&items, left:left, right:right) if left < index - 1 { _ = qs(&items, left:left, right:index - 1) } if index < right { _ = qs(&items, left:index, right:right) } } return items } func partition(_ items:inout [Int], left:Int = 0, right:Int) -> Int { let index:Int = Int(Double((right + left) / 2)) let pivot = items[index] var i = left var j = right while i <= j { while items[i] < pivot { i = i + 1 } while items[j] > pivot { j = j - 1 } if i <= j { exchange(&items, i:i, j:j) i = i + 1 j = j - 1 } } return i } func exchange<T>(_ items:inout [T], i:Int, j:Int) { let temp = items[i] items[i] = items[j] items[j] = temp } }
mit
a55b5f3b6f5c0a92248f2f09e568c299
33.929577
80
0.578629
4.119601
false
false
false
false
benjaminsnorris/CloudKitReactor
Sources/FetchRecordZone.swift
1
1248
/* | _ ____ ____ _ | | |‾| ⚈ |-| ⚈ |‾| | | | | ‾‾‾‾| |‾‾‾‾ | | | ‾ ‾ ‾ */ import Foundation import Reactor import CloudKit public struct FetchRecordZone<U: State>: Command { public var zoneID: CKRecordZone.ID public var completion: ((Bool) -> Void)? public init(with zoneID: CKRecordZone.ID, completion: ((Bool) -> Void)? = nil) { self.zoneID = zoneID self.completion = completion } public func execute(state: U, core: Core<U>) { let operation = CKFetchRecordZonesOperation(recordZoneIDs: [zoneID]) operation.fetchRecordZonesCompletionBlock = { zonesDictionary, error in if let error = error { core.fire(event: CloudKitOperationUpdated(status: .errored(error), type: .fetch)) self.completion?(false) } else { let found = zonesDictionary?[self.zoneID] != nil core.fire(event: CloudKitOperationUpdated(status: .completed, type: .fetch)) self.completion?(found) } } operation.qualityOfService = .userInitiated CKContainer.default().privateCloudDatabase.add(operation) } }
mit
32e23e7e668e02109e823ce0f1291771
31.052632
97
0.568144
4.413043
false
false
false
false
dn-m/Collections
Collections/MutableTree.swift
1
6737
// // MutableTree.swift // Collections // // Created by James Bean on 1/16/17. // // /// Mutable Tree structure. public class MutableTree { /** Error thrown when doing bad things to a `MutableTree` objects. */ public enum Error: Swift.Error { /// Error thrown when trying to insert a MutableTree at an invalid index case insertionError /// Error thrown when trying to remove a MutableTree from an invalid index case removalError /// Error thrown when trying to insert a MutableTree at an invalid index case nodeNotFound } // MARK: - Instance Properties /// Parent `MutableTree`. The root of a tree has no parent. public weak var parent: MutableTree? /// Children `MutableTree` objects. public var children: [MutableTree] /// - returns: `true` if there are no children. Otherwise, `false`. public var isLeaf: Bool { return children.count == 0 } /// All leaves. public var leaves: [MutableTree] { func descendToGetLeaves(of node: MutableTree, result: inout [MutableTree]) { if node.isLeaf { result.append(node) } else { for child in node.children { descendToGetLeaves(of: child, result: &result) } } } var result: [MutableTree] = [] descendToGetLeaves(of: self, result: &result) return result } /// - returns: `true` if there is at least one child. Otherwise, `false`. public var isContainer: Bool { return children.count > 0 } /// - returns: `true` if there is no parent. Otherwise, `false`. public var isRoot: Bool { return parent == nil } /// - returns: `true` if there is no parent. Otherwise, `false`. public var root: MutableTree { func ascendToGetRoot(of node: MutableTree) -> MutableTree { guard let parent = node.parent else { return node } return ascendToGetRoot(of: parent) } return ascendToGetRoot(of: self) } /// Array of all MutableTree objects between (and including) `self` up to `root`. public var pathToRoot: [MutableTree] { func ascendToGetPathToRoot(of node: MutableTree, result: [MutableTree]) -> [MutableTree] { guard let parent = node.parent else { return result + node } return ascendToGetPathToRoot(of: parent, result: result + node) } return ascendToGetPathToRoot(of: self, result: []) } /// Height of node. public var height: Int { func descendToGetHeight(of node: MutableTree, result: Int) -> Int { if node.isLeaf { return result } return node.children .map { descendToGetHeight(of: $0, result: result + 1) } .reduce(0, max) } return descendToGetHeight(of: self, result: 0) } /// Height of containing tree. public var heightOfTree: Int { return root.height } /// Depth of node. public var depth: Int { func ascendToGetDepth(of node: MutableTree, depth: Int) -> Int { guard let parent = node.parent else { return depth } return ascendToGetDepth(of: parent, depth: depth + 1) } return ascendToGetDepth(of: self, depth: 0) } // MARK: - Initializers /** Create a `MutableTree`. */ public init(parent: MutableTree? = nil, children: [MutableTree] = []) { self.parent = parent self.children = children } // MARK: - Instance Methods /** Add the given `node` to `children`. */ public func addChild(_ node: MutableTree) { children.append(node) node.parent = self } /** Append the given `nodes` to `children`. */ public func addChildren(_ nodes: [MutableTree]) { nodes.forEach(addChild) } /** Insert the given `node` at the given `index` of `children`. - throws: `Error.insertionError` if `index` is out of bounds. */ public func insertChild(_ node: MutableTree, at index: Int) throws { if index > children.count { throw Error.insertionError } children.insert(node, at: index) node.parent = self } /** Remove the given `node` from `children`. - throws: `Error.removalError` if the given `node` is not held in `children`. */ public func removeChild(_ node: MutableTree) throws { guard let index = children.index(where: { $0 === node }) else { throw Error.nodeNotFound } try removeChild(at: index) } /** Remove the node at the given `index`. - throws: `Error.removalError` if `index` is out of bounds. */ public func removeChild(at index: Int) throws { if index >= children.count { throw Error.nodeNotFound } children.remove(at: index) } /** - returns: `true` if the given node is contained herein. Otherwise, `false`. */ public func hasChild(_ child: MutableTree) -> Bool { return children.any { $0 === child } } /** - returns: Child node at the given `index`, if present. Otherwise, `nil`. */ public func child(at index: Int) -> MutableTree? { guard children.indices.contains(index) else { return nil } return children[index] } /** - returns: Returns the leaf node at the given `index`, if present. Otherwise, `nil`. */ public func leaf(at index: Int) -> MutableTree? { guard index >= 0 && index < leaves.count else { return nil } return leaves[index] } /** - returns: `true` if the given node is a leaf. Otherwise, `false`. */ public func hasLeaf(_ node: MutableTree) -> Bool { return leaves.contains { $0 === node } } /** - returns: `true` if the given node is an ancestor. Otherwise, `false`. */ public func hasAncestor(_ node: MutableTree) -> Bool { return self === node ? false : pathToRoot.any { $0 === node } } /** - returns: Ancestor at the given distance, if present. Otherwise, `nil`. */ public func ancestor(at distance: Int) -> MutableTree? { guard distance < pathToRoot.count else { return nil } return pathToRoot[distance] } /** - returns: `true` if the given node is a descendent. Otherwise, `false`. */ public func hasDescendent(_ node: MutableTree) -> Bool { if isLeaf { return false } if hasChild(node) { return true } return children .map { $0.hasChild(node) } .filter { $0 == true } .count > 0 } }
mit
394fe1dee89d2e63e29eadb589dccce8
27.306723
98
0.583197
4.145846
false
false
false
false
swiftcodex/Swift-Radio-Pro
SwiftRadio/LogoShareView.swift
1
1022
// // LogoShareView.swift // SwiftRadio // // Created by Cameron Mcleod on 2019-07-12. // Copyright © 2019 matthewfecher.com. All rights reserved. // import UIKit class LogoShareView: UIView { @IBOutlet weak var albumArtImageView: UIImageView! @IBOutlet weak var radioShoutoutLabel: UILabel! @IBOutlet weak var trackTitleLabel: UILabel! @IBOutlet weak var trackArtistLabel: UILabel! @IBOutlet weak var logoImageView: UIImageView! class func instanceFromNib() -> LogoShareView { return UINib(nibName: "LogoShareView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! LogoShareView } func shareSetup(albumArt : UIImage, radioShoutout: String, trackTitle: String, trackArtist: String) { self.albumArtImageView.image = albumArt self.radioShoutoutLabel.text = radioShoutout self.trackTitleLabel.text = trackTitle self.trackArtistLabel.text = trackArtist self.logoImageView.image = UIImage(named: "logo") } }
mit
1d210cf9b1bfc3cd6eb09480f9fb65f8
33.033333
122
0.709109
4.150407
false
false
false
false
Rag0n/QuNotes
QuNotes/Note/NoteEvaluator.swift
1
6156
// // Created by Alexander Guschin on 13.10.2017. // Copyright (c) 2017 Alexander Guschin. All rights reserved. // import Foundation import Prelude import Core extension Note { struct Evaluator { let effects: [ViewEffect] let actions: [Action] let model: Model init(note: Core.Note.Meta, cells: [Core.Note.Cell], isNew: Bool) { effects = [] actions = [] model = Model(title: note.title, tags: note.tags, cells: cells, isNew: isNew) } fileprivate init(effects: [ViewEffect], actions: [Action], model: Model) { self.effects = effects self.actions = actions self.model = model } func evaluating(event: ViewEvent) -> Evaluator { var actions: [Action] = [] var effects: [ViewEffect] = [] var newModel = model switch event { case .didLoad: effects = [ .updateTitle(model.title), .showTags(model.tags) ] if model.isNew { effects += [.focusOnTitle] } case let .changeCellContent(newContent, index): guard index < model.cells.count else { break } let newCell = Core.Note.Cell(type: model.cells[index].type, data: newContent) newModel = model |> Model.lens.cells .~ model.cells.replacing(at: index, with: newCell) actions = [.updateCells(newModel.cells)] effects = [.updateCell(index: index, cells: viewModels(from: newModel))] case let .changeCellType(newType, index): guard index < model.cells.count else { break } let newCell = Core.Note.Cell(type: newType, data: model.cells[index].data) newModel = model |> Model.lens.cells .~ model.cells.replacing(at: index, with: newCell) actions = [.updateCells(newModel.cells)] effects = [.updateCell(index: index, cells: viewModels(from: newModel))] case .addCell: let newCell = Core.Note.Cell(type: .markdown, data: "") newModel = model |> Model.lens.cells .~ model.cells.appending(newCell) actions = [.updateCells(newModel.cells)] effects = [.addCell(index: model.cells.count, cells: viewModels(from: newModel))] case let .removeCell(index): newModel = model |> Model.lens.cells .~ model.cells.removing(at: index) actions = [.updateCells(newModel.cells)] effects = [.removeCell(index: index, cells: viewModels(from: newModel))] case let .changeTitle(newTitle): newModel = model |> Model.lens.title .~ newTitle actions = [.updateTitle(newTitle)] effects = [.updateTitle(newTitle)] case .delete: actions = [.deleteNote] case let .addTag(tag): newModel = model |> Model.lens.tags .~ model.tags.appending(tag) actions = [.addTag(tag)] effects = [.addTag(tag)] case let .removeTag(tag): newModel = model |> Model.lens.tags .~ model.tags.removing(tag) actions = [.removeTag(tag)] effects = [.removeTag(tag)] } return Evaluator(effects: effects, actions: actions, model: newModel) } func evaluating(event: CoordinatorEvent) -> Evaluator { var actions: [Action] = [] var effects: [ViewEffect] = [] var newModel = model switch event { case let .didLoadContent(content): newModel = model |> Model.lens.cells .~ content.cells effects = [.updateCells(viewModels(from: newModel))] case let .didDeleteNote(error): if let error = error { actions = [.showFailure(.deleteNote, reason: error.localizedDescription)] } else { actions = [.finish] } case let .didUpdateTitle(oldTitle, note, error): guard let error = error else { actions = [.didUpdateNote(note)] break } newModel = model |> Model.lens.title .~ oldTitle actions = [.showFailure(.updateTitle, reason: error.localizedDescription)] effects = [.updateTitle(oldTitle)] case let .didUpdateCells(oldCells, error): guard let error = error else { break } newModel = model |> Model.lens.cells .~ oldCells actions = [.showFailure(.updateContent, reason: error.localizedDescription)] effects = [.updateCells(viewModels(from: newModel))] case let .didAddTag(tag, note, error): guard let error = error else { actions = [.didUpdateNote(note)] break } newModel = model |> Model.lens.tags .~ model.tags.removing(tag) actions = [.showFailure(.addTag, reason: error.localizedDescription)] effects = [.removeTag(tag)] case let .didRemoveTag(tag, note, error): guard let error = error else { actions = [.didUpdateNote(note)] break } newModel = model |> Model.lens.tags .~ model.tags.appending(tag) actions = [.showFailure(.removeTag, reason: error.localizedDescription)] effects = [.addTag(tag)] } return Evaluator(effects: effects, actions: actions, model: newModel) } } } // MARK: - Private private extension Note { static func viewModels(from model: Model) -> [CellViewModel] { return model.cells.map(viewModelFromCell) } static func viewModelFromCell(_ cell: Core.Note.Cell) -> CellViewModel { return CellViewModel(content: cell.data, type: cell.type) } }
gpl-3.0
a20b801679804bdeb67c1e4e285cee5f
42.048951
103
0.538986
4.798129
false
false
false
false
byvapps/ByvManager-iOS
ByvManager/Classes/ByvKeychainManager.swift
1
1387
// // ByvKeychainManager.swift // ByvManager // // Created by Adrian Apodaca on 20/9/17. // import UIKit import JNKeychain class ByvKeychainManager: NSObject { static let sharedInstance = ByvKeychainManager() func getDeviceIdentifierFromKeychain() -> String { // try to get value from keychain var deviceUDID = self.keychain_valueForKey("keychainDeviceUDID") as? String if deviceUDID == nil { if let uuid = UIDevice.current.identifierForVendor?.uuidString { deviceUDID = uuid } else { deviceUDID = UUID().uuidString } // save new value in keychain self.keychain_setObject(deviceUDID! as AnyObject, forKey: "keychainDeviceUDID") } return deviceUDID! } // MARK: - Keychain func keychain_setObject(_ object: AnyObject, forKey: String) { let result = JNKeychain.saveValue(object, forKey: forKey) if !result { print("keychain saving: smth went wrong") } } func keychain_deleteObjectForKey(_ key: String) -> Bool { let result = JNKeychain.deleteValue(forKey: key) return result } func keychain_valueForKey(_ key: String) -> AnyObject? { let value = JNKeychain.loadValue(forKey: key) return value as AnyObject? } }
mit
2a2b2a664abcd03556541d613d47ba8b
27.895833
91
0.607066
4.5625
false
false
false
false
multinerd/Mia
Playgrounds/Global Functions Demo.playground/Sources/Date+Helpers.swift
1
1071
// // Date+Helpers.swift // test // // Created by Michael Hedaitulla on 2/4/18. // Copyright © 2018 Western Beef. All rights reserved. // import Foundation public class Constants { public static let SecondsInYear: TimeInterval = 31536000 public static let SecondsInLeapYear: TimeInterval = 31622400 public static let SecondsInMonth28: TimeInterval = 2419200 public static let SecondsInMonth29: TimeInterval = 2505600 public static let SecondsInMonth30: TimeInterval = 2592000 public static let SecondsInMonth31: TimeInterval = 2678400 public static let SecondsInWeek: TimeInterval = 604800 public static let SecondsInDay: TimeInterval = 86400 public static let SecondsInHour: TimeInterval = 3600 public static let SecondsInMinute: TimeInterval = 60 public static let MillisecondsInDay: TimeInterval = 86400000 public static let AllCalendarUnitFlags: Set<Calendar.Component> = [ .year, .quarter, .month, .weekOfYear, .weekOfMonth, .day, .hour, .minute, .second, .era, .weekday, .weekdayOrdinal, .weekOfYear ] }
mit
016365f43abb9ceac14931fafef1b3ac
40.153846
201
0.751402
4.246032
false
false
false
false
jum/Charts
ChartsDemo-iOS/Swift/Demos/HorizontalBarChartViewController.swift
2
3800
// // HorizontalBarChartViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // import UIKit import Charts class HorizontalBarChartViewController: DemoBaseViewController { @IBOutlet var chartView: HorizontalBarChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Horizontal Bar Char" self.options = [.toggleValues, .toggleIcons, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleAutoScaleMinMax, .toggleData, .toggleBarBorders] self.setup(barLineChartView: chartView) chartView.delegate = self chartView.drawBarShadowEnabled = false chartView.drawValueAboveBarEnabled = true chartView.maxVisibleCount = 60 let xAxis = chartView.xAxis xAxis.labelPosition = .bottom xAxis.labelFont = .systemFont(ofSize: 10) xAxis.drawAxisLineEnabled = true xAxis.granularity = 10 let leftAxis = chartView.leftAxis leftAxis.labelFont = .systemFont(ofSize: 10) leftAxis.drawAxisLineEnabled = true leftAxis.drawGridLinesEnabled = true leftAxis.axisMinimum = 0 let rightAxis = chartView.rightAxis rightAxis.enabled = true rightAxis.labelFont = .systemFont(ofSize: 10) rightAxis.drawAxisLineEnabled = true rightAxis.axisMinimum = 0 let l = chartView.legend l.horizontalAlignment = .left l.verticalAlignment = .bottom l.orientation = .horizontal l.drawInside = false l.form = .square l.formSize = 8 l.font = UIFont(name: "HelveticaNeue-Light", size: 11)! l.xEntrySpace = 4 // chartView.legend = l chartView.fitBars = true sliderX.value = 12 sliderY.value = 50 slidersValueChanged(nil) chartView.animate(yAxisDuration: 2.5) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value) + 1, range: UInt32(sliderY.value)) } func setDataCount(_ count: Int, range: UInt32) { let barWidth = 9.0 let spaceForBar = 10.0 let yVals = (0..<count).map { (i) -> BarChartDataEntry in let mult = range + 1 let val = Double(arc4random_uniform(mult)) return BarChartDataEntry(x: Double(i)*spaceForBar, y: val, icon: #imageLiteral(resourceName: "icon")) } let set1 = BarChartDataSet(entries: yVals, label: "DataSet") set1.drawIconsEnabled = false let data = BarChartData(dataSet: set1) data.setValueFont(UIFont(name:"HelveticaNeue-Light", size:10)!) data.barWidth = barWidth chartView.data = data } override func optionTapped(_ option: Option) { super.handleOption(option, forChartView: chartView) } // MARK: - Actions @IBAction func slidersValueChanged(_ sender: Any?) { sliderTextX.text = "\(Int(sliderX.value))" sliderTextY.text = "\(Int(sliderY.value))" self.updateChartData() } }
apache-2.0
cf574c4200d3dd1907144ffdcb8466a3
29.637097
113
0.582522
5.092493
false
false
false
false
KristopherGBaker/RubiParser
RubiParser/RubiNode.swift
1
1273
// // RubiNode.swift // RubiParser // // Created by Kris Baker on 12/19/16. // Copyright © 2016 Empyreal Night, LLC. All rights reserved. // import Foundation /// Represents a RubiDocument node. public enum RubiNode { /// The image type. case image(url: URL) /// The paragraph type. indirect case paragraph(children: [RubiNode]) /// The ruby type. case ruby(kanji: String, reading: String) /// The text type. case text(text: String) /// The word type. case word(text: String) } /// Implements the Equatable protocol for RubiNode. extension RubiNode: Equatable { public static func == (lhs: RubiNode, rhs: RubiNode) -> Bool { switch (lhs, rhs) { case (let .image(url1), let .image(url2)): return url1 == url2 case (let .ruby(kanji1, reading1), let .ruby(kanji2, reading2)): return kanji1 == kanji2 && reading1 == reading2 case (let .text(text1), let .text(text2)): return text1 == text2 case (let .word(word1), let .word(word2)): return word1 == word2 case (let .paragraph(children1), let .paragraph(children2)): return children1 == children2 default: return false } } }
mit
2e6b9bba39e6c582ba132851f136756a
22.555556
72
0.59434
3.763314
false
false
false
false
Coledunsby/TwitterClient
TwitterClient/ComposeViewController.swift
1
2820
// // ComposeViewController.swift // TwitterClient // // Created by Cole Dunsby on 2017-06-13. // Copyright © 2017 Cole Dunsby. All rights reserved. // import RxCocoa import RxKeyboard import RxSwift final class ComposeViewController: UIViewController { var viewModel: ComposeViewModelIO! private let disposeBag = DisposeBag() @IBOutlet private weak var textView: UITextView! @IBOutlet private weak var tweetButton: UIButton! @IBOutlet private weak var dismissButton: UIBarButtonItem! @IBOutlet private weak var charactersRemainingLabel: UILabel! @IBOutlet private weak var activityIndicatorView: UIActivityIndicatorView! @IBOutlet private weak var toolbarBottomConstraint: NSLayoutConstraint! // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // MARK: Inputs textView.rx.text .bind(to: viewModel.inputs.text) .disposed(by: disposeBag) tweetButton.rx.tap .bind(to: viewModel.inputs.tweet) .disposed(by: disposeBag) dismissButton.rx.tap .bind(to: viewModel.inputs.dismiss) .disposed(by: disposeBag) // MARK: Outputs viewModel.outputs.charactersRemaining .map(String.init) .drive(charactersRemainingLabel.rx.text) .disposed(by: disposeBag) viewModel.outputs.isValid .drive(tweetButton.rx.isEnabled) .disposed(by: disposeBag) viewModel.outputs.isLoading .bind(to: activityIndicatorView.rx.isAnimating) .disposed(by: disposeBag) viewModel.outputs.shouldDismiss .bind { [unowned self] in self.dismiss(animated: true) } .disposed(by: disposeBag) viewModel.outputs.errors .bind { [unowned self] error in self.present(UIAlertController.error(error), animated: true) } .disposed(by: disposeBag) // MARK: UI RxKeyboard.instance.visibleHeight .drive(onNext: { [unowned self] height in self.view.setNeedsLayout() UIView.animate(withDuration: 0) { self.toolbarBottomConstraint.constant = height self.view.layoutIfNeeded() } }) .disposed(by: disposeBag) tweetButton.layer.cornerRadius = 2.0 textView.text = "" textView.textContainer.lineFragmentPadding = 0 textView.textContainerInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) textView.becomeFirstResponder() } }
mit
ba1849fb2f94398d34fdd88a27afa8fc
29.978022
92
0.591699
5.259328
false
false
false
false
Bouke/Swift-PriorityQueue
PriorityQueueTests/PriorityQueueTests.swift
1
3194
// // Swift_PriorityQueueTests.swift // Swift-PriorityQueueTests // // Created by Bouke Haarsma on 12-02-15. // Copyright (c) 2015 Bouke Haarsma. All rights reserved. // import PriorityQueue import Foundation import XCTest class PriorityQueueTests: XCTestCase { func testSimple() { var queue = PriorityQueue<Int>(<) queue.push(10) queue.push(2) queue.push(3) queue.push(1) queue.push(2) queue.push(3) queue.push(9) queue.push(5) XCTAssertEqual(1, queue.next()!) XCTAssertEqual(2, queue.next()!) XCTAssertEqual(2, queue.next()!) XCTAssertEqual(3, queue.next()!) XCTAssertEqual(3, queue.next()!) XCTAssertEqual(5, queue.next()!) XCTAssertEqual(9, queue.next()!) XCTAssertEqual(10, queue.next()!) XCTAssertTrue(queue.next() == nil) queue.push(11) XCTAssertEqual(11, queue.remove(11) ?? -1) XCTAssertNil(queue.remove(11)) } func testRandom() { var queue = PriorityQueue<UInt32>(<) for var i = 0; i < 10000; i += 1 { queue.push(arc4random()) } var current: UInt32 = 0 for item in queue { XCTAssertGreaterThanOrEqual(item, current) current = item } } func testUpdate() { var queue = PriorityQueue<Item>({ $0.priority < $1.priority }) let items = [ Item(priority: 1), Item(priority: 2), Item(priority: 3), Item(priority: 4), ] items.map { queue.push($0) } items[3].priority = 0 XCTAssertTrue(queue.update(items[3]) == items[3]) XCTAssertEqual(Array(queue), [items[3], items[0], items[1], items[2]]) items.map { queue.push($0) } items[3].priority = 5 XCTAssertTrue(queue.update(items[3]) == items[3]) XCTAssertEqual(Array(queue), [items[0], items[1], items[2], items[3]]) } func testRemove() { var queue = PriorityQueue<Int>(<) (1...7).map { queue.push($0) } XCTAssertTrue(queue.remove(3) == 3) XCTAssertEqual(Array(queue), [1,2,4,5,6,7]) } func testPushPerformance() { measureMetrics(self.dynamicType.defaultPerformanceMetrics(), automaticallyStartMeasuring:false) { var queue = PriorityQueue<UInt32>(<) self.startMeasuring() for var i = 0; i < 10000; i += 1 { queue.push(arc4random()) } self.stopMeasuring() } } func testPopPerformance() { measureMetrics(self.dynamicType.defaultPerformanceMetrics(), automaticallyStartMeasuring:false) { var queue = PriorityQueue<UInt32>(<) for var i = 0; i < 1000; i += 1 { queue.push(arc4random()) } self.startMeasuring() for p in queue {} self.stopMeasuring() } } } private class Item { var priority: Int init(priority: Int) { self.priority = priority } } extension Item: Equatable { } private func == (lhs: Item, rhs: Item) -> Bool { return lhs === rhs }
mit
b837c05d28ae8c6c4227a8a4e47c8987
26.534483
105
0.554477
4.079183
false
true
false
false
ahalls/tenbyten
TenByTen/TenByTen/TenByTen/ViewController.swift
1
2585
// // ViewController.swift // TenByTen // // Created by Andrew Halls on 7/21/14. // Copyright (c) 2014 GaltSoft. All rights reserved. // import Foundation import UIKit class ViewController: UIViewController { @IBOutlet var imageView: UIImageView? @IBOutlet var headerLabel: UILabel? let managerImage = AFHTTPRequestOperationManager() let managerText = AFHTTPRequestOperationManager() let viewModel: ViewModel init(_viewModel:ViewModel) { self.viewModel = _viewModel super.init(nibName: "ViewController", bundle: nil) } func bindViewModel() { self.title = self.viewModel.title; self.viewModel.isExecuting?.subscribeNext() { (responseObject:AnyObject!) -> Void in if let isExecuting = responseObject as? Bool { if (isExecuting) { MMProgressHUD.show() } else { MMProgressHUD.dismiss() } } } self.viewModel.dateTitle?.subscribeNext() { (responseObject:AnyObject!) -> Void in if let date = responseObject as? NSDate { var fm = NSDateFormatter() fm.dateFormat = "MMMM dd, yyyy" self.headerLabel!.text = fm.stringFromDate( date) } } self.viewModel.image?.subscribeNext() { (responseObject:AnyObject!) -> Void in if let image = responseObject as? UIImage { self.imageView!.image = image; } } // self.viewModel.connectionErrors?.subscribeError() { // (responseObject:AnyObject!) -> Void in // if let error = responseObject as ? NSError { // let alert = UIAlertView(title: "Connection Error", message: error.description , delegate: nil, cancelButtonTitle: OK, otherButtonTitles: nil, nil) // alert.show() // } // } } // self.viewModel.connectionErrors.subscribeNext() // :^(NSError *error) { // UIAlertView *alert = // [[UIAlertView alloc] initWithTitle:@"Connection Error" // message:@"There was a problem reaching Flickr." // delegate:nil // cancelButtonTitle:@"OK" // otherButtonTitles:nil]; // [alert show]; // }]; override func viewDidLoad() { super.viewDidLoad() bindViewModel() } }
mit
51f74b42eec94fee9c068a4faee75fe8
27.406593
164
0.537331
5.068627
false
false
false
false
ru-kio/Hydra
FXHydra/FXNavigationController.swift
3
1192
// // FXNavigationController.swift // FXHydra // // Created by kioshimafx on 3/18/16. // Copyright © 2016 FXSolutions. All rights reserved. // import UIKit class FXNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() self.navigationBar.tintColor = UIColor ( red: 0.0, green: 0.8408, blue: 1.0, alpha: 1.0) self.navigationBar.barTintColor = UIColor(red: 20/255, green: 20/255, blue: 20/255, alpha: 1.0) self.navigationItem.titleView?.tintColor = UIColor.whiteColor() self.interactivePopGestureRecognizer!.enabled = true self.navigationBar.translucent = false let titleDict = [NSFontAttributeName : UIFont(name: "Avenir-Book", size: 20)!, NSForegroundColorAttributeName : UIColor.whiteColor()] self.navigationBar.titleTextAttributes = titleDict } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
mit
e21dfea559a66050c12e0044f330a9f0
29.538462
141
0.670865
4.841463
false
false
false
false
derekli66/Learning-Core-Audio-Swift-SampleCode
CH08_AUGraphInput-Swift/CH08-AUGraphInput/main.swift
1
20822
// // main.swift // CH08-AUGraphInput // // Created by LEE CHIEN-MING on 16/05/2017. // Copyright © 2017 derekli66. All rights reserved. // import Foundation import AudioToolbox import ApplicationServices // MARK: - Audio struct MyAUGraphPlayer { var streamFormat: AudioStreamBasicDescription? var graph: AUGraph? var inputUnit: AudioUnit? var outputUnit: AudioUnit? #if PART_II var speechUnit: AudioUnit? #endif var inputBuffer: UnsafeMutableAudioBufferListPointer? var ringBuffer: RingBufferWrapper? var firstInputSampleTime: Float64 = 0.0 var firstOutputSampleTime: Float64 = 0.0 var inToOutSampleTimeOffset: Float64 = 0.0 } let inputRenderProc: AURenderCallback = { (inRefCon: UnsafeMutableRawPointer, ioActionFlags: UnsafeMutablePointer<AudioUnitRenderActionFlags>, inTimeStamp: UnsafePointer<AudioTimeStamp>, inBusNumber: UInt32, inNumberFrames: UInt32, ioData: UnsafeMutablePointer<AudioBufferList>?) in debugPrint("InputRenderProc!") var player: MyAUGraphPlayer = inRefCon.bindMemory(to: MyAUGraphPlayer.self, capacity: 1).pointee // have we ever logged input timing? (for offset calculation) if (player.firstInputSampleTime < 0.0) { player.firstInputSampleTime = inTimeStamp.pointee.mSampleTime if (player.firstOutputSampleTime > -1.0) && (player.inToOutSampleTimeOffset < 0.0) { player.inToOutSampleTimeOffset = player.firstInputSampleTime - player.firstOutputSampleTime } } guard let inputUnit = player.inputUnit, let inputBuffer = player.inputBuffer, let ringBuffer = player.ringBuffer else { debugPrint("Could't get enough arguments for further process") return kAudioUnitErr_InvalidElement } // render into our buffer var inputProcErr: OSStatus = noErr inputProcErr = AudioUnitRender(inputUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, inputBuffer.unsafeMutablePointer) if (inputProcErr == noErr) { inputProcErr = StoreBuffer(ringBuffer, inputBuffer.unsafeMutablePointer, inNumberFrames, SampleTime(inTimeStamp.pointee.mSampleTime)) } return inputProcErr } let graphRenderProc: AURenderCallback = { (inRefCon: UnsafeMutableRawPointer, ioActionFlags: UnsafeMutablePointer<AudioUnitRenderActionFlags>, inTimeStamp: UnsafePointer<AudioTimeStamp>, inBusNumber: UInt32, inNumberFrames: UInt32, ioData: UnsafeMutablePointer<AudioBufferList>?) in var player: MyAUGraphPlayer = inRefCon.bindMemory(to: MyAUGraphPlayer.self, capacity: 1).pointee var audioTimeStamp = inTimeStamp.pointee if (player.firstOutputSampleTime < 0.0) { player.firstOutputSampleTime = audioTimeStamp.mSampleTime if (player.firstInputSampleTime > -1.0 && player.inToOutSampleTimeOffset < 0.0) { player.inToOutSampleTimeOffset = player.firstInputSampleTime - player.firstOutputSampleTime } } // copy samples out of ring buffer var outputProcError: OSStatus = noErr outputProcError = FetchBuffer(player.ringBuffer!, ioData, inNumberFrames, SampleTime(audioTimeStamp.mSampleTime + player.inToOutSampleTimeOffset)) debugPrint("fetched \(inNumberFrames) frames at time \(audioTimeStamp.mSampleTime)") return noErr } func CreateInputUnit(_ player: inout MyAUGraphPlayer) { // generate description that will match audio HAL var inputcd = AudioComponentDescription(componentType: kAudioUnitType_Output, componentSubType: kAudioUnitSubType_HALOutput, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0) let component: AudioComponent? = AudioComponentFindNext(nil, &inputcd) guard let comp = component else { debugPrint("can't get output unit") exit(-1) } CheckError(AudioComponentInstanceNew(comp, &player.inputUnit), "Couldn't open component for inputUnit") guard let inputUnit = player.inputUnit else { debugPrint("Cannot get input unit for initialization") exit(-1) } // Enable IO var disableFlag: UInt32 = 0 var enableFlag: UInt32 = 1 let outputBus: AudioUnitElement = 0 let inputBus: AudioUnitElement = 1 CheckError(AudioUnitSetProperty(inputUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, inputBus, &enableFlag, UInt32(MemoryLayout.size(ofValue: enableFlag))), "Couldn't enable input on IO unit") CheckError(AudioUnitSetProperty(inputUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, outputBus, &disableFlag, UInt32(MemoryLayout.size(ofValue: enableFlag))), "Couldn't disable output on I/O unit") // set device (osx only... iphone has only one device) var defaultDevice: AudioDeviceID = kAudioObjectUnknown var propertySize: UInt32 = UInt32(MemoryLayout.size(ofValue: defaultDevice)) var defaultDeviceProperty = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDefaultInputDevice, mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMaster) CheckError(AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &defaultDeviceProperty , 0, nil, &propertySize, &defaultDevice), "Couldn't get default input device") // set this defaultDevice as the input's property // kAudioUnitErr_InvalidPropertyValue if output is enabled on inputUnit CheckError(AudioUnitSetProperty(inputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, outputBus, &defaultDevice, UInt32(MemoryLayout.size(ofValue: defaultDevice))), "Couldn't set default device on IO unit") // use the stream format coming out of the AUHAL (should be de-interleaved) propertySize = UInt32(MemoryLayout<AudioStreamBasicDescription>.size) var inputBusOutputFormat = AudioStreamBasicDescription() CheckError(AudioUnitGetProperty(inputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, inputBus, &inputBusOutputFormat, &propertySize), "Couldn't get ASBD from input unit") player.streamFormat = inputBusOutputFormat // check the input device's stream format var deviceFormat = AudioStreamBasicDescription() CheckError(AudioUnitGetProperty(inputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, inputBus, &deviceFormat, &propertySize), "Couldn't get ASBD from input unit") debugPrint("Device rate \(deviceFormat.mSampleRate), graph rate \(String(describing: player.streamFormat?.mSampleRate))") player.streamFormat?.mSampleRate = deviceFormat.mSampleRate propertySize = UInt32(MemoryLayout<AudioStreamBasicDescription>.size) CheckError(AudioUnitSetProperty(inputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, inputBus, &player.streamFormat, propertySize), "Couldn't set ASBD on input unit") guard let streamFormat = player.streamFormat else { debugPrint("Cannot get stream format to set up output unit") exit(-1) } // allocate some buffers to hold samples between input and output callbacks // Get the size of the IO buffers var bufferSizeFrames: UInt32 = 0 propertySize = UInt32(MemoryLayout<UInt32>.size) CheckError(AudioUnitGetProperty(inputUnit, kAudioDevicePropertyBufferFrameSize, kAudioUnitScope_Global, 0, &bufferSizeFrames, &propertySize), "Couldn't get buffer frame size from input unit") let bufferSizeBytes = bufferSizeFrames * UInt32(MemoryLayout<Float32>.size) if (((player.streamFormat?.mFormatFlags)! & kAudioFormatFlagIsNonInterleaved) > 0) { let inputBuffer: UnsafeMutableAudioBufferListPointer = AudioBufferList.allocate(maximumBuffers: Int(streamFormat.mChannelsPerFrame)) player.inputBuffer = inputBuffer for var audioBuffer in inputBuffer { audioBuffer.mNumberChannels = 1 audioBuffer.mDataByteSize = bufferSizeBytes audioBuffer.mData = malloc(Int(bufferSizeBytes)) memset(audioBuffer.mData, 0, Int(audioBuffer.mDataByteSize)) } } else { debugPrint("format is interleaved") let inputBuffer: UnsafeMutableAudioBufferListPointer = AudioBufferList.allocate(maximumBuffers: 1) player.inputBuffer = inputBuffer player.inputBuffer?[0].mNumberChannels = streamFormat.mChannelsPerFrame player.inputBuffer?[0].mDataByteSize = bufferSizeBytes player.inputBuffer?[0].mData = malloc(Int(bufferSizeBytes)) memset(player.inputBuffer?[0].mData, 0, Int(bufferSizeBytes)) } // Allocate ring buffer that will hold data between the two audio devices player.ringBuffer = CreateRingBuffer() AllocateBuffer(player.ringBuffer!, Int32(streamFormat.mChannelsPerFrame), streamFormat.mBytesPerFrame, bufferSizeFrames * 3) // set render proc to supply samples from input unit var callbackStruct = AURenderCallbackStruct(inputProc: inputRenderProc, inputProcRefCon: UnsafeMutablePointer(&player)) CheckError(AudioUnitSetProperty(inputUnit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &callbackStruct, UInt32(MemoryLayout.size(ofValue: callbackStruct))), "Couldn't set input callback") CheckError(AudioUnitInitialize(inputUnit), "Couldn't initalize input unit") player.firstInputSampleTime = -1 player.inToOutSampleTimeOffset = -1 debugPrint("Bottom of CreateInputUnit()") } func CreateMyAUGraph(_ player: inout MyAUGraphPlayer) -> Void { // Create a new AUGraph CheckError(NewAUGraph(&player.graph), "NewAUGraph failed") guard let audioGraph = player.graph else { debugPrint("Cannot get audio graph") exit(-1) } var outputcd = AudioComponentDescription(componentType: kAudioUnitType_Output, componentSubType: kAudioUnitSubType_DefaultOutput, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0) let comp = AudioComponentFindNext(nil, &outputcd) if comp == nil { debugPrint("Can't get output unit") exit(-1) } // Adds a node with above description to the graph var outputNode: AUNode = 0 CheckError(AUGraphAddNode(audioGraph, &outputcd, &outputNode), "AUGraphAddNode[kAudioUnitSubType_DefaultOutput] failed") #if PART_II // Adds a mixer to the graph var mixercd = AudioComponentDescription(componentType: kAudioUnitType_Mixer, componentSubType: kAudioUnitSubType_StereoMixer, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0) var mixerNode: AUNode = 0 CheckError(AUGraphAddNode(audioGraph, &mixercd, &mixerNode), "AUGraphAddNode[kAudioUnitSubType_StereoMixer] failed") // Adds a node with above description to the graph var speechcd = AudioComponentDescription(componentType: kAudioUnitType_Generator, componentSubType: kAudioUnitSubType_SpeechSynthesis, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0) var speechNode: AUNode = 0 CheckError(AUGraphAddNode(audioGraph, &speechcd, &speechNode), "AUGraphAddNode[kAudioUnitSubType_AudioFilePlayer] failed") // Opening the graph opens all contained audio units but does not allocate any resources yet CheckError(AUGraphOpen(audioGraph), "AUGraphOpen failed") // Get the reference to the AudioUnit objects for the various nodes CheckError(AUGraphNodeInfo(audioGraph, outputNode, nil, &player.outputUnit), "AUGraphNodeInfo failed") CheckError(AUGraphNodeInfo(audioGraph, speechNode, nil, &player.speechUnit), "AUGraphNodeInfo failed") var mixerUnit: AudioUnit? CheckError(AUGraphNodeInfo(audioGraph, mixerNode, nil, &mixerUnit), "AUGraphNodeInfo failed") guard let mixerUnit_ = mixerUnit else { debugPrint("Cannot get mixer unit for audio graph") exit(-1) } // Set ASBDs here let propertySize: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size) // Set stream format on input scope of bus 0 because of the render callback will be plug in at this scope CheckError(AudioUnitSetProperty(mixerUnit_, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &player.streamFormat, propertySize), "Couldn't set stream format on mixer unit input scope of bus 0") // Set output stream format on speech unit and mixer unit to let stream format propagation happens CheckError(AudioUnitSetProperty(player.speechUnit!, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &player.streamFormat, propertySize), "Couldn't set stream format on speech unit bus 0") CheckError(AudioUnitSetProperty(mixerUnit_, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &player.streamFormat, propertySize), "Couldn't set stream format on mixer unit output scope of bus 0") // connections // mixer output scope / bus 0 to outputUnit input scope / bus 0 // mixer input scope / bus 0 to render callback (from ringbuffer, which in turn is from inputUnit) // mixer input scope / bus 1 to speech unit output scope / bus 0 CheckError(AUGraphConnectNodeInput(audioGraph, mixerNode, 0, outputNode, 0), "Couldn't connect mixer output(0) to outputNode (0)") CheckError(AUGraphConnectNodeInput(audioGraph, speechNode, 0, mixerNode, 1), "Couldn't connect speech synth unit output (0) to mixer input (1)") let referencePtr = withUnsafeMutablePointer(to: &player, { return UnsafeMutableRawPointer($0) }) var callbackStruct = AURenderCallbackStruct(inputProc: graphRenderProc, inputProcRefCon: referencePtr) AudioUnitSetProperty(mixerUnit_, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Global, 0, &callbackStruct, UInt32(MemoryLayout.size(ofValue: callbackStruct))) #else // opening the graph opens all contained audio units but does not allocate any resources yet CheckError(AUGraphOpen(audioGraph), "AUGraphOpen failed") // get the reference to the AudioUnit object for the output graph node CheckError(AUGraphNodeInfo(audioGraph, outputNode, nil, &player.outputUnit), "AUGraphNodeInfo failed") // set the stream format on the output unit's input scope let propertySize: Int = MemoryLayout<AudioStreamBasicDescription>.size CheckError(AudioUnitSetProperty(player.outputUnit!, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &player.streamFormat, UInt32(propertySize)), "Couldn't set stream format on output unit") let referencePtr = withUnsafeMutablePointer(to: &player, { return UnsafeMutableRawPointer($0) }) var callbackStruct = AURenderCallbackStruct(inputProc: graphRenderProc, inputProcRefCon: referencePtr) CheckError(AudioUnitSetProperty(player.outputUnit!, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Global, 0, &callbackStruct, UInt32(MemoryLayout.size(ofValue: callbackStruct))), "Couldn't set render callback on output unit") #endif // now initialize the graph (causes resources to be allocated) CheckError(AUGraphInitialize(audioGraph), "AUGraphInitialize failed") player.firstOutputSampleTime = -1 debugPrint("Bottom of CreateMyAUGraph") } #if PART_II func PrepareSpeechAU(_ player: inout MyAUGraphPlayer) -> Void { var chan: SpeechChannel? var propsize: UInt32 = UInt32(MemoryLayout<SpeechChannel>.size) guard let speechUnit = player.speechUnit else { debugPrint("There is no speech unit before preparation") exit(-1) } CheckError(AudioUnitGetProperty(speechUnit, kAudioUnitProperty_SpeechChannel, kAudioUnitScope_Global, 0, &chan, &propsize), "AudioFileGetProperty[kAudioUnitProperty_SpeechChannel] failed") if let chan = chan { let cfstring = "Learning Core Audio is not an easy job but keep reading any thing about Core Audio. In the end, you will get a full map of the all stuff about Core Audio API" as CFString SpeakCFString(chan, cfstring, nil) } } #endif // MARK: - Main var player: MyAUGraphPlayer = MyAUGraphPlayer() // Create the input unit CreateInputUnit(&player) // Build a graph with output unit CreateMyAUGraph(&player) #if PART_II // Configure the speech synthesizer PrepareSpeechAU(&player) #endif // Start playing CheckError(AudioOutputUnitStart(player.inputUnit!), "AudioOutputUnitStart failed") CheckError(AUGraphStart(player.graph!), "AUGraphStart failed") // Wait print("Capturing, presss <return> to stop") getchar() // clean up AUGraphStop(player.graph!) AUGraphUninitialize(player.graph!) AUGraphClose(player.graph!)
mit
4ac56af5d43f6c1c24315afc2824613d
41.929897
194
0.600259
5.595539
false
false
false
false
EaglesoftZJ/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/Cell/AABubbleLocationCell.swift
1
6940
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import MapKit private let mapWidth: CGFloat = 200 private let mapHeight: CGFloat = 160 open class AABubbleLocationCell: AABubbleCell { fileprivate let map = AAMapFastView(mapWidth: mapWidth, mapHeight: mapHeight) fileprivate let pin = UIImageView() fileprivate let timeBg = UIImageView() fileprivate let timeLabel = UILabel() fileprivate let statusView = UIImageView() fileprivate var bindedLat: Double? = nil fileprivate var bindedLon: Double? = nil public init(frame: CGRect) { super.init(frame: frame, isFullSize: false) timeBg.image = ActorSDK.sharedActor().style.statusBackgroundImage timeLabel.font = UIFont.italicSystemFont(ofSize: 11) timeLabel.textColor = appStyle.chatMediaDateColor statusView.contentMode = UIViewContentMode.center pin.image = UIImage.bundled("LocationPin") contentView.addSubview(map) map.addSubview(pin) contentView.addSubview(timeBg) contentView.addSubview(timeLabel) contentView.addSubview(statusView) contentInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1) map.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AABubbleLocationCell.mapDidTap))) map.isUserInteractionEnabled = true let longPressTap = UILongPressGestureRecognizer(target:self,action:#selector(AABubbleCell.longTap(tap:))) self.contentView.isUserInteractionEnabled = true self.contentView.addGestureRecognizer(longPressTap) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func mapDidTap() { let url = "http://maps.apple.com/?q=\(bindedLat!),\(bindedLon!)" // print("url: \(url)") UIApplication.shared.openURL(URL(string: url)!) } open override func bind(_ message: ACMessage, receiveDate: jlong, readDate: jlong, reuse: Bool, cellLayout: AACellLayout, setting: AACellSetting) { let layout = cellLayout as! AALocationCellLayout bindedLat = layout.latitude bindedLon = layout.longitude bubbleInsets = UIEdgeInsets( top: setting.clenchTop ? AABubbleCell.bubbleTopCompact : AABubbleCell.bubbleTop, left: 10 + (AADevice.isiPad ? 16 : 0), bottom: setting.clenchBottom ? AABubbleCell.bubbleBottomCompact : AABubbleCell.bubbleBottom, right: 10 + (AADevice.isiPad ? 16 : 0)) if (!reuse) { // Bind bubble if (self.isOut) { bindBubbleType(BubbleType.mediaOut, isCompact: false) } else { bindBubbleType(BubbleType.mediaIn, isCompact: false) } } map.bind(layout.latitude, longitude: layout.longitude) // Update time timeLabel.text = cellLayout.date // Update status if (isOut) { statusView.isHidden = false switch(message.messageState.toNSEnum()) { case .SENT: if message.sortDate <= readDate { self.statusView.image = appStyle.chatIconCheck2 self.statusView.tintColor = appStyle.chatStatusMediaRead } else if message.sortDate <= receiveDate { self.statusView.image = appStyle.chatIconCheck2 self.statusView.tintColor = appStyle.chatStatusMediaReceived } else { self.statusView.image = appStyle.chatIconCheck1 self.statusView.tintColor = appStyle.chatStatusMediaSent } case .ERROR: self.statusView.image = appStyle.chatIconError self.statusView.tintColor = appStyle.chatStatusMediaError break case .PENDING: self.statusView.image = appStyle.chatIconClock self.statusView.tintColor = appStyle.chatStatusMediaSending break default: self.statusView.image = appStyle.chatIconClock self.statusView.tintColor = appStyle.chatStatusMediaSending break } } else { statusView.isHidden = true } } open override func layoutContent(_ maxWidth: CGFloat, offsetX: CGFloat) { let insets = fullContentInsets let contentWidth = self.contentView.frame.width layoutBubble(mapWidth, contentHeight: mapHeight) if isOut { map.frame = CGRect(x: contentWidth - insets.right - mapWidth , y: insets.top, width: mapWidth, height: mapHeight) } else { map.frame = CGRect(x: insets.left, y: insets.top, width: mapWidth, height: mapHeight) } timeLabel.frame = CGRect(x: 0, y: 0, width: 1000, height: 1000) timeLabel.sizeToFit() let timeWidth = (isOut ? 23 : 0) + timeLabel.bounds.width let timeHeight: CGFloat = 20 timeLabel.frame = CGRect(x: map.frame.maxX - timeWidth - 18, y: map.frame.maxY - timeHeight - 6, width: timeLabel.frame.width, height: timeHeight) if (isOut) { statusView.frame = CGRect(x: timeLabel.frame.maxX, y: timeLabel.frame.minY, width: 23, height: timeHeight) } pin.frame = CGRect(x: (map.width - pin.image!.size.width)/2, y: (map.height / 2 - pin.image!.size.height), width: pin.image!.size.width, height: pin.image!.size.height) timeBg.frame = CGRect(x: timeLabel.frame.minX - 4, y: timeLabel.frame.minY - 1, width: timeWidth + 8, height: timeHeight + 2) } } open class AALocationCellLayout: AACellLayout { let latitude: Double let longitude: Double init(latitude: Double, longitude: Double, date: Int64, layouter: AABubbleLayouter) { self.latitude = latitude self.longitude = longitude super.init(height: mapHeight + 2, date: date, key: "location", layouter: layouter) } } open class AABubbleLocationCellLayouter: AABubbleLayouter { open func isSuitable(_ message: ACMessage) -> Bool { if (message.content is ACLocationContent) { return true } return false } open func buildLayout(_ peer: ACPeer, message: ACMessage) -> AACellLayout { let content = message.content as! ACLocationContent return AALocationCellLayout(latitude: Double(content.getLatitude()), longitude: Double(content.getLongitude()), date: Int64(message.date), layouter: self) } open func cellClass() -> AnyClass { return AABubbleLocationCell.self } }
agpl-3.0
72950d42150a7013ee6e80795d85b714
36.717391
162
0.614986
4.717879
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/SVGContext/SVGEffect/SVGFloodEffect.swift
1
2524
// // SVGFloodEffect.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // public struct SVGFloodEffect: SVGEffectElement { public var region: Rect = .null public var regionUnit: SVGEffect.RegionUnit = .objectBoundingBox public var color: AnyColor public var sources: [SVGEffect.Source] { return [] } public init(color: AnyColor = .black) { self.color = color } public func visibleBound(_ sources: [SVGEffect.Source: Rect]) -> Rect? { return nil } } extension SVGFloodEffect { private func create_color<C: ColorProtocol>(_ color: C) -> String { let color = color.convert(to: ColorSpace.sRGB, intent: .default) let red = UInt8((color.red * 255).clamped(to: 0...255).rounded()) let green = UInt8((color.green * 255).clamped(to: 0...255).rounded()) let blue = UInt8((color.blue * 255).clamped(to: 0...255).rounded()) return "rgb(\(red),\(green),\(blue))" } public var xml_element: SDXMLElement { var filter = SDXMLElement(name: "feFlood", attributes: ["flood-color": create_color(color)]) if self.color.opacity < 1 { filter.setAttribute(for: "flood-opacity", value: "\(Decimal(self.color.opacity).rounded(scale: 9))") } return filter } }
mit
f7d6d84bfe245423a59b5c0fe030007e
35.057143
112
0.658479
4.242017
false
false
false
false
myandy/shi_ios
shishi/UI/Share/MirrorLoaderLayer.swift
1
1698
// // MirrorLoaderLayer.swift // shishi // // Created by tb on 2017/7/30. // Copyright © 2017年 andymao. All rights reserved. // import UIKit class MirrorLoaderLayer: CALayer { public var image: UIImage? override init() { super.init() self.setupLayer() } override init(layer: Any) { super.init(layer: layer) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupLayer() { self.contentsScale = UIScreen.main.scale } override func draw(in ctx: CGContext) { guard let image = self.image else { return } let rotateImage = image.rotate(.downMirrored)! let drawHeight = self.frame.size.width * (image.size.height / image.size.width) let rowCount = Int(self.frame.size.height / drawHeight) + (Int(self.frame.size.height) % Int(drawHeight) == 0 ? 0 : 1) for index in 0..<rowCount { var drawImage = image let top = CGFloat(index) * drawHeight if index % 2 != 0 { // drawImage = UIImage(cgImage: drawImage.cgImage!, scale: drawImage.scale, orientation: .downMirrored) drawImage = rotateImage } let rect = CGRect(x: 0, y: top, width: self.frame.size.width, height: drawHeight) UIGraphicsPushContext(ctx) drawImage.draw(in: rect) UIGraphicsPopContext() // ctx.draw(drawImage.cgImage!, in: CGRect(x: 0, y: top, width: self.frame.size.width, height: drawHeight)) } } }
apache-2.0
7472c78c09a423569f7d9913971f5aa9
28.224138
126
0.565782
4.174877
false
false
false
false
gb-6k-house/YsSwift
Sources/Rabbit/ImageView+Target.swift
1
1862
/****************************************************************************** ** auth: liukai ** date: 2017/7 ** ver : 1.0 ** desc: Rabbit + Image ** Copyright © 2017年 尧尚信息科技(www.yourshares.cn). All rights reserved ******************************************************************************/ import Foundation #if YSSWIFT_DEBUG import YsSwift #endif import Result #if os(macOS) import Cocoa /// Alias for `NSImageView` public typealias ImageView = NSImageView #elseif os(iOS) || os(tvOS) import UIKit /// Alias for `UIImageView` public typealias ImageView = UIImageView #endif #if os(macOS) || os(iOS) || os(tvOS) /// Default implementation of `Target` protocol for `ImageView`. extension ImageView: Target { /// Displays an image on success. Runs `opacity` transition if /// the response was not from the memory cache. public func handle(response: Result<Image, YsSwift.RequestError>, isFromMemoryCache: Bool) { guard let image = response.value else { return } self.image = image if !isFromMemoryCache { let animation = CABasicAnimation(keyPath: "opacity") animation.duration = 0.25 animation.fromValue = 0 animation.toValue = 1 let layer: CALayer? = self.layer // Make compiler happy on macOS layer?.add(animation, forKey: "imageTransition") } } } #endif extension YSSwift where Base: ImageView { public func loadImage(with url: URL, placeholder placeholderImage: UIImage? = nil) { //set placehold image if let image = placeholderImage { self.base.image = image } //load image Rabbit.loadImage(with: url, into: self.base) } }
mit
2d00770fd0e7172ceb9a21438c569890
29.278689
100
0.554413
4.784974
false
false
false
false
SanctionCo/pilot-ios
pilot/PostsTableViewCell.swift
1
3250
// // HistoryTableViewCell.swift // pilot // // Created by Nick Eckert on 12/27/17. // Copyright © 2017 sanction. All rights reserved. // import UIKit class PostsTableViewCell: UITableViewCell { private var postIcon: UIImageView = { let icon = UIImageView() icon.translatesAutoresizingMaskIntoConstraints = false icon.contentMode = UIViewContentMode.scaleAspectFit return icon }() private var postText: UILabel = { let text = UILabel() text.translatesAutoresizingMaskIntoConstraints = false text.adjustsFontSizeToFitWidth = true text.lineBreakMode = NSLineBreakMode.byTruncatingTail text.sizeToFit() return text }() private var postDate: UILabel = { let date = UILabel() date.translatesAutoresizingMaskIntoConstraints = false date.adjustsFontSizeToFitWidth = true date.textColor = UIColor.TextGray date.font = date.font.withSize(13) date.numberOfLines = 1 date.lineBreakMode = .byClipping date.minimumScaleFactor = 0.1 date.sizeToFit() return date }() private var postTime: UILabel = { let time = UILabel() time.translatesAutoresizingMaskIntoConstraints = false time.textColor = UIColor.TextGray time.font = time.font.withSize(13) time.numberOfLines = 1 time.lineBreakMode = .byClipping time.minimumScaleFactor = 0.1 time.sizeToFit() return time }() var icon: UIImage? { didSet { self.postIcon.image = icon } } var message: String? { didSet { self.postText.text = message } } var date: String? { didSet { self.postDate.text = date } } var time: String? { didSet { self.postTime.text = time } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(postIcon) contentView.addSubview(postText) contentView.addSubview(postDate) contentView.addSubview(postTime) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() setupPost() } private func setupPost() { // Pin icon to the left of the cell postIcon.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 20).isActive = true postIcon.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true postIcon.heightAnchor.constraint(equalToConstant: 40).isActive = true postIcon.widthAnchor.constraint(equalToConstant: 40).isActive = true // Attach the post text to the top postText.leftAnchor.constraint(equalTo: postIcon.rightAnchor, constant: 20).isActive = true postText.topAnchor.constraint(equalTo: postIcon.topAnchor).isActive = true // Attach date below text postDate.leftAnchor.constraint(equalTo: postIcon.rightAnchor, constant: 20).isActive = true postDate.bottomAnchor.constraint(equalTo: postIcon.bottomAnchor).isActive = true // Attach the post time below the text on the right postTime.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -20).isActive = true postTime.bottomAnchor.constraint(equalTo: postIcon.bottomAnchor).isActive = true } }
mit
82746d3d3a380bcd1a4212a70172d92e
26.769231
100
0.71345
4.531381
false
false
false
false
xedin/swift
test/SILGen/enum_resilience.swift
8
10219
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift // RUN: %target-swift-emit-silgen -module-name enum_resilience -I %t -enable-library-evolution %s | %FileCheck %s import resilient_enum // Resilient enums are always address-only, and switches must include // a default case // CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience15resilientSwitchyy0c1_A06MediumOF : $@convention(thin) (@in_guaranteed Medium) -> () // CHECK: [[BOX:%.*]] = alloc_stack $Medium // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]] // CHECK-NEXT: [[METATYPE:%.+]] = value_metatype $@thick Medium.Type, [[BOX]] : $*Medium // CHECK-NEXT: switch_enum_addr [[BOX]] : $*Medium, case #Medium.Paper!enumelt: bb1, case #Medium.Canvas!enumelt: bb2, case #Medium.Pamphlet!enumelt.1: bb3, case #Medium.Postcard!enumelt.1: bb4, default bb5 // CHECK: bb1: // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb3: // CHECK-NEXT: [[INDIRECT_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]] // CHECK-NEXT: [[INDIRECT:%.*]] = load [take] [[INDIRECT_ADDR]] // CHECK-NEXT: [[PAYLOAD:%.*]] = project_box [[INDIRECT]] // CHECK-NEXT: destroy_value [[INDIRECT]] // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb4: // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]] // CHECK-NEXT: destroy_addr [[PAYLOAD_ADDR]] // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb5: // CHECK-NEXT: // function_ref // CHECK-NEXT: [[DIAGNOSE:%.+]] = function_ref @$ss27_diagnoseUnexpectedEnumCase // CHECK-NEXT: = apply [[DIAGNOSE]]<Medium>([[METATYPE]]) : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> Never // CHECK-NEXT: unreachable // CHECK: bb6: // CHECK-NOT: destroy_addr %0 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] func resilientSwitch(_ m: Medium) { switch m { case .Paper: () case .Canvas: () case .Pamphlet: () case .Postcard: () } } // CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience22resilientSwitchDefaultys5Int32V0c1_A06MediumOF : $@convention(thin) (@in_guaranteed Medium) -> Int32 { func resilientSwitchDefault(_ m: Medium) -> Int32 { // CHECK: switch_enum_addr %2 : $*Medium, case #Medium.Paper!enumelt: [[PAPER:[^ ]+]], case #Medium.Canvas!enumelt: [[CANVAS:[^ ]+]], default [[DEFAULT:[^ ]+]] switch m { // CHECK: [[PAPER]]: // CHECK: integer_literal $Builtin.IntLiteral, 0 case .Paper: return 0 // CHECK: [[CANVAS]]: // CHECK: integer_literal $Builtin.IntLiteral, 1 case .Canvas: return 1 // CHECK: [[DEFAULT]]: // CHECK: integer_literal $Builtin.IntLiteral, -1 default: return -1 } } // CHECK: end sil function '$s15enum_resilience22resilientSwitchDefaultys5Int32V0c1_A06MediumOF' // CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience26resilientSwitchUnknownCaseys5Int32V0c1_A06MediumOF : $@convention(thin) (@in_guaranteed Medium) -> Int32 { func resilientSwitchUnknownCase(_ m: Medium) -> Int32 { // CHECK: switch_enum_addr %2 : $*Medium, case #Medium.Paper!enumelt: [[PAPER:[^ ]+]], case #Medium.Canvas!enumelt: [[CANVAS:[^ ]+]], default [[DEFAULT:[^ ]+]] switch m { // CHECK: [[PAPER]]: // CHECK: integer_literal $Builtin.IntLiteral, 0 case .Paper: return 0 // CHECK: [[CANVAS]]: // CHECK: integer_literal $Builtin.IntLiteral, 1 case .Canvas: return 1 // CHECK: [[DEFAULT]]: // CHECK: integer_literal $Builtin.IntLiteral, -1 @unknown case _: return -1 } } // CHECK: end sil function '$s15enum_resilience26resilientSwitchUnknownCaseys5Int32V0c1_A06MediumOF' // CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience36resilientSwitchUnknownCaseExhaustiveys5Int32V0c1_A06MediumOF : $@convention(thin) (@in_guaranteed Medium) -> Int32 { func resilientSwitchUnknownCaseExhaustive(_ m: Medium) -> Int32 { // CHECK: switch_enum_addr %2 : $*Medium, case #Medium.Paper!enumelt: [[PAPER:[^ ]+]], case #Medium.Canvas!enumelt: [[CANVAS:[^ ]+]], case #Medium.Pamphlet!enumelt.1: [[PAMPHLET:[^ ]+]], case #Medium.Postcard!enumelt.1: [[POSTCARD:[^ ]+]], default [[DEFAULT:[^ ]+]] switch m { // CHECK: [[PAPER]]: // CHECK: integer_literal $Builtin.IntLiteral, 0 case .Paper: return 0 // CHECK: [[CANVAS]]: // CHECK: integer_literal $Builtin.IntLiteral, 1 case .Canvas: return 1 // CHECK: [[PAMPHLET]]: // CHECK: integer_literal $Builtin.IntLiteral, 2 case .Pamphlet: return 2 // CHECK: [[POSTCARD]]: // CHECK: integer_literal $Builtin.IntLiteral, 3 case .Postcard: return 3 // CHECK: [[DEFAULT]]: // CHECK: integer_literal $Builtin.IntLiteral, -1 @unknown case _: return -1 } } // Indirect enums are still address-only, because the discriminator is stored // as part of the value, so we cannot resiliently make assumptions about the // enum's size // CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience21indirectResilientEnumyy010resilient_A016IndirectApproachOF : $@convention(thin) (@in_guaranteed IndirectApproach) -> () func indirectResilientEnum(_ ia: IndirectApproach) {} public enum MyResilientEnum { case kevin case loki // CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience15MyResilientEnumOACycfC : $@convention(method) (@thin MyResilientEnum.Type) -> @out MyResilientEnum // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var MyResilientEnum }, var, name "self" // CHECK: [[SELF_TMP:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var MyResilientEnum } // CHECK: [[SELF_ADDR:%.*]] = project_box [[SELF_TMP]] : ${ var MyResilientEnum }, 0 // CHECK: [[NEW_SELF:%.*]] = enum $MyResilientEnum, #MyResilientEnum.loki!enumelt // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*MyResilientEnum // CHECK: assign [[NEW_SELF]] to [[ACCESS]] : $*MyResilientEnum // CHECK: end_access [[ACCESS]] : $*MyResilientEnum // CHECK: copy_addr [[SELF_ADDR]] to [initialization] %0 : $*MyResilientEnum // CHECK: destroy_value [[SELF_TMP]] : ${ var MyResilientEnum } // CHECK: return init() { self = .loki } // CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience15MyResilientEnumO9getAHorseACyFZ : $@convention(method) (@thin MyResilientEnum.Type) -> @out MyResilientEnum // CHECK: [[NEW_SELF:%.*]] = enum $MyResilientEnum, #MyResilientEnum.loki!enumelt // CHECK: store [[NEW_SELF]] to [trivial] %0 : $*MyResilientEnum // CHECK: return static func getAHorse() -> MyResilientEnum { return .loki } } public enum MoreHorses { case marshall(Int) case seuss(AnyObject) // CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience10MoreHorsesOACycfC : $@convention(method) (@thin MoreHorses.Type) -> @out MoreHorses // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var MoreHorses }, var, name "self" // CHECK: [[SELF_TMP:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var MoreHorses } // CHECK: [[SELF_ADDR:%.*]] = project_box [[SELF_TMP]] : ${ var MoreHorses }, 0 // CHECK: [[BUILTIN_INT:%.*]] = integer_literal $Builtin.IntLiteral, 0 // CHECK: [[INT_METATYPE:%.*]] = metatype $@thin Int.Type // CHECK: [[INT_CTOR:%.*]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [[PAYLOAD:%.*]] = apply [[INT_CTOR]]([[BUILTIN_INT]], [[INT_METATYPE]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [[NEW_SELF:%.*]] = enum $MoreHorses, #MoreHorses.marshall!enumelt.1, [[PAYLOAD]] : $Int // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*MoreHorses // CHECK: assign [[NEW_SELF]] to [[ACCESS]] : $*MoreHorses // CHECK: end_access [[ACCESS]] : $*MoreHorses // CHECK: copy_addr [[SELF_ADDR]] to [initialization] %0 : $*MoreHorses // CHECK: destroy_value [[SELF_TMP]] : ${ var MoreHorses } // CHECK: return init() { self = .marshall(0) } } public func referenceCaseConstructors() { _ = MoreHorses.marshall _ = MoreHorses.seuss } // CHECK-LABEL: sil [ossa] @$s15enum_resilience15resilientSwitchyyAA15MyResilientEnumOF : $@convention(thin) (@in_guaranteed MyResilientEnum) -> () // CHECK: [[ENUM:%.*]] = load [trivial] %0 // CHECK: switch_enum [[ENUM]] : $MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2 // CHECK: return public func resilientSwitch(_ e: MyResilientEnum) { switch e { case .kevin: () case .loki: () } } // CHECK-LABEL: sil [ossa] @$s15enum_resilience15resilientIfCaseySbAA15MyResilientEnumOF : $@convention(thin) (@in_guaranteed MyResilientEnum) -> Bool // CHECK: [[ENUM:%.*]] = load [trivial] %0 : $*MyResilientEnum // CHECK: switch_enum [[ENUM]] : $MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2 // CHECK: return public func resilientIfCase(_ e: MyResilientEnum) -> Bool { if case .kevin = e { return true } else { return false } } // Inlinable functions must lower the switch as if it came from outside the module // CHECK-LABEL: sil [serialized] [ossa] @$s15enum_resilience15inlinableSwitchyyAA15MyResilientEnumOF : $@convention(thin) (@in_guaranteed MyResilientEnum) -> () // CHECK: [[ENUM:%.*]] = alloc_stack $MyResilientEnum // CHECK: copy_addr %0 to [initialization] [[ENUM]] : $*MyResilientEnum // CHECK: switch_enum_addr [[ENUM]] : $*MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2, default bb3 // CHECK: return @inlinable public func inlinableSwitch(_ e: MyResilientEnum) { switch e { case .kevin: () case .loki: () } }
apache-2.0
4516a61f76ec7eefd14cdae25d30bb90
48.357488
267
0.65528
3.608972
false
false
false
false
Logicalshift/SwiftRebound
SwiftRebound/Binding/Bound.swift
1
10776
// // Bound.swift // SwiftRebound // // Created by Andrew Hunter on 10/07/2016. // // import Foundation /// /// Semaphore used to protect this value against races when being updated on multiple queues /// /// We don't hold the semaphore for long periods of time and bindings are not supposed to be used for bulk data storage (so /// very high performance is not a concern) so we share a single semaphore between all bindings instead of having one per /// binding. /// /// This has to be public otherwise the Swift optimiser decides we don't need this variable and removes it. Then it complains /// it's not present :-/ /// public let _bindingUpdateSemaphore = DispatchSemaphore(value: 1); /// /// Protocol implemented by objects that can be notified that they need to recalculate themselves /// public protocol Notifiable : class { /// /// Mark this item as having been changed /// /// The next time the value is resolved, it will register as a change and the observers will be called. /// func markAsChanged(); } /// /// Protocol implemented by objects that can notify other objects that it has changed /// public protocol Changeable : class { /// /// Calls a function any time this value is marked as changed /// func whenChangedNotify(_ target: Notifiable) -> Lifetime; } public extension Changeable { /// /// Calls a function any time this value is marked as changed /// public final func whenChanged(_ action: @escaping () -> ()) -> Lifetime { return whenChangedNotify(CallbackNotifiable(action: action)); } } /// /// A bound value represents a storage location whose changes can be observed by other objects. /// /// Bound values are the core of SwiftRebound. /// open class Bound<TBoundType> : Changeable, Notifiable { /// /// The value that's current bound to this object, or nil if it has been changed and needs recomputing /// internal var _currentValue: TBoundType? = nil; /// /// The actions that should be executed when this bound value is changed /// fileprivate var _actionsOnChanged: [NotificationWrapper] = []; /// /// nil, or a binding that is true if this item is bound to something or false if it is not /// fileprivate var _isBound: MutableBound<Bool>? = nil; /// /// Must be overridden by subclasses: can't be initialised directly /// internal init() { } /// /// Causes any observers to be notified that this object has changed /// internal final func notifyChange() { var needToTidy = false; // Synchronise access to the actions _bindingUpdateSemaphore.wait(); let actions = _actionsOnChanged; _bindingUpdateSemaphore.signal(); // Run any actions that result from this value being updated for notificationWrapper in actions { if let action = notificationWrapper.target { action.markAsChanged(); } else { needToTidy = true; } } if needToTidy { maybeDoneObserving(); } } /// /// Recomputes and rebinds the value associated with this object (even if it's not marked as being changed) /// public final func rebind() -> TBoundType { // Update the current value let currentValue = computeValue(); _bindingUpdateSemaphore.wait(); _currentValue = currentValue; _bindingUpdateSemaphore.signal(); return currentValue; } /// /// Returns true if the current value needs updating /// open func needsUpdate() -> Bool { return getCurrentValue() == nil; } /// /// Retrieves the current vaue of this bound value, or nil if it is currently unresolved /// public final func getCurrentValue() -> TBoundType? { _bindingUpdateSemaphore.wait(); let result = _currentValue; _bindingUpdateSemaphore.signal(); return result; } /// /// Ensures that the value associated with this binding has been resolved (if this item has been marked as /// changed, forces it to update) /// @inline(__always) public final func resolve() -> TBoundType { // Resolving a binding creates a dependency in the current context BindingContext.current?.addDependency(self); // Always update if this is flagged for an update if needsUpdate() { return rebind(); } // Also update if there is no current value // (this can occasionally happen due to a race condition, or because of the way needsUpdate is implemented in a subclass) if let currentValue = getCurrentValue() { return currentValue; } else { return rebind(); } } /// /// Mark this item as having been changed /// /// The next time the value is resolved, it will register as a change and the observers will be called. /// open func markAsChanged() { // Notify a change if we're currently resolved (otherwise, assume that the change is still pending and we don't need to notify again) _bindingUpdateSemaphore.wait(); if _currentValue != nil { _currentValue = nil; _bindingUpdateSemaphore.signal(); notifyChange(); } else { _bindingUpdateSemaphore.signal(); } } /// /// Reads the value that this object is bound to /// open var value: TBoundType { @inline(__always) get { return resolve(); } } /// /// Calls a function any time this value is marked as changed /// public final func whenChangedNotify(_ target: Notifiable) -> Lifetime { // Record this action so we can re-run it when the value changes let wrapper = NotificationWrapper(target: target); _bindingUpdateSemaphore.wait(); _actionsOnChanged.append(wrapper); let isFirstBinding = _actionsOnChanged.count == 1; _bindingUpdateSemaphore.signal(); // Perform actions if this is the first binding attached to this object if isFirstBinding { updateIsBound(); beginObserving(); } // Stop observing the action once the lifetime expires return CallbackLifetime(done: { wrapper.target = nil; self.maybeDoneObserving(); }); } /// /// Calls a function any time this value is changed. The function will be called at least once /// with the current value of this bound object /// public final func observe(_ action: @escaping (TBoundType) -> ()) -> Lifetime { var resolving = false; var resolveAgain = false; let performObservation = { if !resolving { // If we get a side-effect that causes this to need to be fired again, then do so iteratively rather than recursively repeat { resolveAgain = false; resolving = true; action(self.resolve()); resolving = false; } while (resolveAgain); } else { // Something is currently resolving this observable, cause it to run again resolveAgain = true; } }; // Call and resolve the action whenever this item is changed let lifetime = whenChanged(performObservation); // As soon as we start observing a value, call the action to generate the initial binding performObservation(); return lifetime; } /// /// Recomputes the value of this bound object and returns the result /// /// Subclasses must override this to describe how a bound value is updated /// internal func computeValue() -> TBoundType { fatalError("computeValue not implemented"); } /// /// Something has begun observing this object for changes /// open func beginObserving() { // Subclasses may override (eg if they want to add an observer) } /// /// All observers have finished their lifetime (called eagerly; normally observers are removed lazily) /// open func doneObserving() { // Subclasses may override (eg if they want to add an observer) } /// /// Updates the isBound value so it's current /// fileprivate func updateIsBound() { if let isBound = _isBound { _bindingUpdateSemaphore.wait(); let isNowBound = _actionsOnChanged.count > 0; _bindingUpdateSemaphore.signal(); // TODO: really need to set the value within the semaphore isBound.value = isNowBound; } } /// /// Check to see if all notifications are finished with and call doneObserving() if they are /// fileprivate func maybeDoneObserving() { // See if all the notifiers are finished with var allDone = true; // Check if we're done _bindingUpdateSemaphore.wait(); for notifier in _actionsOnChanged { if notifier.target != nil { allDone = false; break; } } // Clear out eagerly if all notifiers are finished with if allDone { _actionsOnChanged = []; } _bindingUpdateSemaphore.signal(); // Notify if we're finished if allDone { updateIsBound(); doneObserving(); } } /// /// Returns a binding that is set to true while this binding is being observed /// /// This can be used as an opportunity to detach or attach event handlers that update a particular value, by observing when it /// becomes true or false. /// open var isBound: Bound<Bool> { get { _bindingUpdateSemaphore.wait(); if let result = _isBound { // Use the existing isBound value _bindingUpdateSemaphore.signal(); return result; } else { // Create a new isBound value let result = Binding.create(false); _isBound = result; _bindingUpdateSemaphore.signal(); updateIsBound(); return result; } } } }
apache-2.0
0beb0f41605977656f6974613907e91d
30.41691
141
0.582498
5.126546
false
false
false
false
codefellows/sea-b23-iOS
AVFoundationCameraViewController.swift
1
2824
// // AVFoundationCameraViewController.swift // CFImageFilterSwift // // Created by Bradley Johnson on 9/22/14. // Copyright (c) 2014 Brad Johnson. All rights reserved. // import UIKit import AVFoundation import CoreMedia import CoreVideo import ImageIO import QuartzCore class AVFoundationCameraViewController: UIViewController { @IBOutlet weak var capturePreviewImageView: UIImageView! var stillImageOutput = AVCaptureStillImageOutput() override func viewDidLoad() { super.viewDidLoad() var captureSession = AVCaptureSession() captureSession.sessionPreset = AVCaptureSessionPresetPhoto var previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.frame = CGRectMake(0, 64, self.view.frame.size.width, CGFloat(self.view.frame.size.height * 0.6)) self.view.layer.addSublayer(previewLayer) var device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) var error : NSError? var input = AVCaptureDeviceInput.deviceInputWithDevice(device, error: &error) as AVCaptureDeviceInput! if input == nil { println("bad!") } captureSession.addInput(input) var outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG] self.stillImageOutput.outputSettings = outputSettings captureSession.addOutput(self.stillImageOutput) captureSession.startRunning() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func capturePressed(sender: AnyObject) { var videoConnection : AVCaptureConnection? for connection in self.stillImageOutput.connections { if let cameraConnection = connection as? AVCaptureConnection { for port in cameraConnection.inputPorts { if let videoPort = port as? AVCaptureInputPort { if videoPort.mediaType == AVMediaTypeVideo { videoConnection = cameraConnection break; } } } } if videoConnection != nil { break; } } self.stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(buffer : CMSampleBuffer!, error : NSError!) -> Void in var data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) var image = UIImage(data: data) self.capturePreviewImageView.image = image println(image.size) }) } }
mit
a7826ba3be18e5ed61bcc83bfeff0078
34.746835
168
0.644122
6.060086
false
false
false
false
ubiregiinc/UbiregiExtensionClient
Pod/Classes/UXCAPIClient.swift
1
5835
import Foundation import SMHTTPClient internal enum UXCNameResolutionResult { case ResolvedToAddress(sockaddr, Bool) case NotFound case Error } internal class UXCAPIClient { let hostname: String let port: UInt var _address: sockaddr? let _queue: dispatch_queue_t init(hostname: String, port: UInt, address: sockaddr?) { self.hostname = hostname self.port = port self._address = address self._queue = dispatch_queue_create("com.ubiregi.UXCAPIClient.queue", nil) } func async(block: dispatch_block_t) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block) } var address: sockaddr? { get { var a: sockaddr? dispatch_sync(self._queue) { a = self._address } return a } set(a) { dispatch_sync(self._queue) { self._address = a } } } func after(delay: NSTimeInterval, block: dispatch_block_t) { var d = delay if d <= 0 { d = 0.1 } let when = dispatch_time(DISPATCH_TIME_NOW, Int64(d * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { block() } } var defaultQueue: dispatch_queue_t { return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) } func sendRequest(path: String, query: [String: String], method: HttpMethod, timeout: NSTimeInterval, callback: (UXCAPIResponse) -> ()) { let startedAt = NSDate() async { self.resolveAddress(1) { result in switch result { case .ResolvedToAddress(let addr, let resolved): let request = HttpRequest(address: addr, path: self.pathWithQuery(path, query: query), method: method, header: self.defaultHeader(resolved, method: method)) self.after(timeout - NSDate().timeIntervalSinceDate(startedAt)) { request.abort() } request.run() switch request.status { case .Completed(let code, let header, let data): var h: [String: String] = [:] for (k,v) in header { h[k] = v } callback(UXCAPISuccessResponse(code: code, header: h, body: data)) case .Aborted: let error = NSError(domain: UXCConstants.ErrorDomain, code: UXCErrorCode.Timeout.rawValue, userInfo: nil) callback(UXCAPIErrorResponse(error: error)) case .Error(let e): print("UXCAPIClient.sendRequest: request results in error => \(e)") fallthrough default: let error = NSError(domain: UXCConstants.ErrorDomain, code: UXCErrorCode.ConnectionFailure.rawValue, userInfo: nil) callback(UXCAPIErrorResponse(error: error)) } default: let error = NSError(domain: UXCConstants.ErrorDomain, code: UXCErrorCode.NameResolution.rawValue, userInfo: nil) callback(UXCAPIErrorResponse(error: error)) } } } } func pathWithQuery(path: String, query: [String: String]) -> String { if query.isEmpty { return path } else { let q = try! query.map { (key, value) throws -> String in let escaped = value.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! return "\(key)=\(escaped)" }.joinWithSeparator("&") return path + "?" + q } } func defaultHeader(resolved: Bool, method: HttpMethod) -> [(String, String)] { var h = [ ("Connection", "close"), ("Content-Type", "application/json") ] if resolved { h.append(("Host", self.hostname)) } switch method { case .PATCH(let data): h.append(("Content-Length", String(data.length))) case .POST(let data): h.append(("Content-Length", String(data.length))) case .PUT(let data): h.append(("Content-Length", String(data.length))) default: break } return h } func resolveAddress(timeout: NSTimeInterval, callback: (UXCNameResolutionResult) -> ()) { let resolver = NameResolver(hostname: self.hostname, port: self.port) after(timeout) { resolver.abort() } resolver.run() switch resolver.status { case .Resolved: // resolver.results can not be empty, if successfuly resolved // Prefere IPv4 address let address = (!resolver.IPv4Results.isEmpty ? resolver.IPv4Results : resolver.IPv6Results).first! // Save sockaddr as cache self.address = address callback(.ResolvedToAddress(address, true)) case .Aborted: // Use cached address since name resolution failed if let addr = self.address { callback(.ResolvedToAddress(addr, false)) } else { callback(.NotFound) } default: if let addr = self.address { callback(.ResolvedToAddress(addr, false)) } else { callback(.Error) } } } }
mit
9c5eae5926e06d19f74ce028a80438d4
34.585366
176
0.526478
4.919899
false
false
false
false
Jgzhu/DouYUZhiBo-Swift
DouYUZhiBo-Swift/DouYUZhiBo-Swift/Classes/Home/Controller/HomeViewController.swift
1
3425
// // HomeViewController.swift // DouYuZhiBo-Swift // // Created by 江贵铸 on 2016/11/18. // Copyright © 2016年 江贵铸. All rights reserved. // import UIKit class HomeViewController: UIViewController { fileprivate lazy var pageTitleview: PageTitleView = { let TitleviewFrame = CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width, height: 44) let titles = ["推荐","游戏","娱乐","趣玩","测试"] let pageTitleview = PageTitleView(frame: TitleviewFrame, titles: titles) pageTitleview.delegate = self return pageTitleview }() fileprivate lazy var pageContentView: PageContentView = { let PCViewFrame = CGRect(x: 0, y: 64+44, width: UIScreen.main.bounds.width, height: self.view.frame.size.height-64-44-(self.tabBarController?.tabBar.frame.size.height)!) let RecommendVC = RecommendViewController() //RecommendVC.view.backgroundColor = UIColor.yellow let VC2 = UIViewController() VC2.view.backgroundColor = UIColor.blue let VC3 = UIViewController() VC3.view.backgroundColor = UIColor.cyan let VC4 = UIViewController() VC4.view.backgroundColor = UIColor.magenta let VC5 = UIViewController() VC5.view.backgroundColor = UIColor.purple let ContentVC: [UIViewController] = [RecommendVC,VC2,VC3,VC4,VC5] let PCView = PageContentView(frame: PCViewFrame, ContentVC: ContentVC) PCView.delegate = self return PCView }() override func viewDidLoad() { super.viewDidLoad() //更新UI SetUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension HomeViewController{ //更新UI fileprivate func SetUI(){ automaticallyAdjustsScrollViewInsets = false //设置导航栏 SetNavItem() //设置titleView view.addSubview(pageTitleview) //设置ContentView view.addSubview(pageContentView) } private func SetNavItem(){ //设置左侧Item navigationItem.leftBarButtonItem = UIBarButtonItem(imagename: "logo", hightImagename: "", size: CGSize.zero) //设置右侧Item let btnsize = CGSize(width: 40, height: 40) let historyItem = UIBarButtonItem(imagename: "image_my_history", hightImagename: "Image_my_history_click", size: btnsize) let searchItem = UIBarButtonItem(imagename: "btn_search", hightImagename: "btn_search_clicked", size: btnsize) let qrcodeItem = UIBarButtonItem(imagename: "Image_scan", hightImagename: "Image_scan_click", size: btnsize) navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem] } } extension HomeViewController:PageTitleViewDelegate{ func pageTitleViewClick(titleView: PageTitleView, selectIndex: Int) { print("\(selectIndex)") pageContentView.ScrollToPageContent(selectindex: selectIndex) } } extension HomeViewController:PageContentViewDelegate{ func PageContentScroll(souceIndex: Int, targetIndex: Int, progress: CGFloat) { pageTitleview.ScrollTitle(souceIndex: souceIndex, targetIndex: targetIndex, progress: progress) // print("原始\(souceIndex)----目标\(targetIndex)---比例\(progress)") } }
mit
7ed63f246dfc43783c6cc0d8d158704a
30.771429
177
0.669365
4.502024
false
false
false
false
kywix/iamsblog
macOS/macBitmoji/macBitmoji/Controllers/Login.swift
1
3824
// // macBitmoji Edition // // Login.swift // macBitmoji // // Created by Mario Esposito on 4/7/20. // import Cocoa class Login: NSViewController, AppMessages { @IBOutlet weak var username: NSTextField! @IBOutlet weak var password: NSSecureTextField! @IBOutlet weak var errorLabel: NSTextField! override func viewDidLoad() { super.viewDidLoad() AppHelper.shared.delegate = self let home = FileManager.default.homeDirectoryForCurrentUser let cacheFolder = "Pictures/macMoji" let picturesfolder = home.appendingPathComponent(cacheFolder) if AppHelper.shared.directoryExistsAtPath(picturesfolder.absoluteString) { let storyboardName = NSStoryboard.Name(stringLiteral: "Main") let storyboard = NSStoryboard(name: storyboardName, bundle: nil) let storyboardID = NSStoryboard.SceneIdentifier(stringLiteral: "CatalogID") if let emojiWindowController = storyboard.instantiateController(withIdentifier: storyboardID) as? Catalog { super.presentAsModalWindow(emojiWindowController) } // 3: close this window view.window?.close() } } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } @IBAction func login(_ sender: Any) { setupAccount() } func setupAccount() -> Void { // 2: get ID //AppHelper.shared.getBitmojiAccessToken(email: username.stringValue, password: password.stringValue) // 3: get avatar ID //AppHelper.shared.getAvatarID() // 4: cache images AppHelper.shared.getTemplates(matching: "") { (_: [Bits]) in self.showMessage(message: "gathering all your avatars...") // 5: go show images // let storyboardName = NSStoryboard.Name(stringLiteral: "Main") // let storyboard = NSStoryboard(name: storyboardName, bundle: nil) // let storyboardID = NSStoryboard.SceneIdentifier(stringLiteral: "CatalogID") // // if let emojiWindowController = storyboard.instantiateController(withIdentifier: storyboardID) as? Catalog { // super.presentAsModalWindow(emojiWindowController) // } } } // MARK: DELEGATES func showMessage(message: String) { DispatchQueue.main.async { AppHelper.shared.fadeViewInThenOut(view: self.errorLabel, delay: 5.0) self.errorLabel.stringValue = "ℹ️ \(message)" } } func showError(message: Error) { DispatchQueue.main.async { AppHelper.shared.fadeViewInThenOut(view: self.errorLabel, delay: 5.0) self.errorLabel.stringValue = "🤦🏻‍♀️ \(message.localizedDescription)" } } func loginState(state: ExecutionStatus) { AppHelper.shared.logInfo(whatToLog: "not implemented") } func bitMojiQuery(state: ExecutionStatus) { AppHelper.shared.logInfo(whatToLog: "not implemented") } func bitMojiQuery(state: ExecutionStatus, data: Bits) { //AppHelper.shared.logInfo(whatToLog: "not implemented") let AvatarUUID = UserDefaults.standard.string(forKey: AppKeys.AvatarUUID) var comicURL = URL(string: "\(EndPoints.BitStripsURL)/\(data.imoji[0].comicID)-\(AvatarUUID!)-v1.png") AppHelper.shared.loadFileSync(url: comicURL!) { (path, error) in guard error == nil else { print(error?.localizedDescription) return } AppHelper.shared.logInfo(whatToLog: "file downloaded in \(path)") } } }
mit
b4b44e08dd4c5b74aac09c758fdfe595
33.306306
121
0.614496
4.724566
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Home/Cells/News/NativeNewsViewController.swift
1
10872
// // NativeNewsViewController.swift // PennMobile // // Created by Kunli Zhang on 27/02/22. // Copyright © 2022 PennLabs. All rights reserved. // import Foundation import SwiftSoup import UIKit class NativeNewsViewController: UIViewController { var article: NewsArticle! let scrollView = UIScrollView() let contentView = UIStackView() let body = UILabel() let titleLabel = UILabel() let authorLabel = UILabel() let imageView = UIImageView() let imageCaptionView = UILabel() let readMoreButton = UIButton() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground prepareScrollView() prepareContentView() prepareTitleLabel() prepareAuthorLabel() prepareImageView() prepareBodyText() prepareReadMoreButton() } func prepareScrollView() { scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) NSLayoutConstraint.activate([ scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), scrollView.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor), scrollView.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor) ]) } func prepareContentView() { contentView.translatesAutoresizingMaskIntoConstraints = false contentView.axis = NSLayoutConstraint.Axis.vertical contentView.distribution = UIStackView.Distribution.equalSpacing contentView.alignment = UIStackView.Alignment.leading contentView.spacing = 16.0 scrollView.addSubview(contentView) NSLayoutConstraint.activate([ contentView.topAnchor.constraint(equalTo: scrollView.topAnchor), contentView.leadingAnchor.constraint(equalTo: scrollView.layoutMarginsGuide.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: scrollView.layoutMarginsGuide.trailingAnchor), contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor) ]) } func prepareTitleLabel() { titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.text = article.data.labsArticle.headline titleLabel.lineBreakMode = .byWordWrapping titleLabel.numberOfLines = 0 titleLabel.font = UIFont.preferredFont(forTextStyle: .title1, compatibleWith: .current) contentView.addArrangedSubview(titleLabel) NSLayoutConstraint.activate([ titleLabel.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor), titleLabel.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor) ]) } func prepareAuthorLabel() { authorLabel.translatesAutoresizingMaskIntoConstraints = false authorLabel.text = "" for author in article.data.labsArticle.authors { authorLabel.text! += author.name + ", " } if authorLabel.text != "" { authorLabel.text?.removeLast(2) } authorLabel.text! += " | " + article.data.labsArticle.published_at authorLabel.lineBreakMode = .byWordWrapping authorLabel.numberOfLines = 0 authorLabel.font = UIFont.preferredFont(forTextStyle: .headline, compatibleWith: .current) contentView.addArrangedSubview(authorLabel) NSLayoutConstraint.activate([ authorLabel.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor), authorLabel.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor) ]) } func prepareImageView() { imageView.kf.setImage(with: URL(string: article.data.labsArticle.dominantMedia.imageUrl)) imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFill imageView.translatesAutoresizingMaskIntoConstraints = false contentView.addArrangedSubview(imageView) _ = imageView.anchor(nil, left: contentView.layoutMarginsGuide.leftAnchor, bottom: nil, right: contentView.layoutMarginsGuide.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: contentView.layoutMarginsGuide.layoutFrame.width, heightConstant: contentView.layoutMarginsGuide.layoutFrame.width * 0.6) imageCaptionView.translatesAutoresizingMaskIntoConstraints = false imageCaptionView.text = "" for author in article.data.labsArticle.dominantMedia.authors { imageCaptionView.text! += author.name + ", " } if imageCaptionView.text != "" { imageCaptionView.text?.removeLast(2) } imageCaptionView.lineBreakMode = .byWordWrapping imageCaptionView.numberOfLines = 0 imageCaptionView.font = UIFont.preferredFont(forTextStyle: .caption1, compatibleWith: .current) contentView.addArrangedSubview(imageCaptionView) NSLayoutConstraint.activate([ imageCaptionView.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor), imageCaptionView.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor) ]) imageCaptionView.sizeToFit() } func prepareBodyText() { var bodyViews: [UIView] = [] let html = article.data.labsArticle.content if let doc = try? SwiftSoup.parse(html), let elements = doc.body()?.children() { for element in elements { switch element.tagName() { case "p": let paragraphTextView = UITextView() paragraphTextView.isScrollEnabled = false paragraphTextView.isEditable = false paragraphTextView.attributedText = try? element.html().htmlToAttributedString paragraphTextView.textColor = .label let subTag = element.children().first()?.tagName() if subTag == "em" && (try? element.children().first()?.html()) != "" { paragraphTextView.font = UIFont.preferredFont(forTextStyle: .headline, compatibleWith: .current) } else if subTag == "strong" && (try? element.children().first()?.html()) != "" { paragraphTextView.font = UIFont.preferredFont(forTextStyle: .title2, compatibleWith: .current) } else { paragraphTextView.font = UIFont.preferredFont(forTextStyle: .body, compatibleWith: .current) } bodyViews.append(paragraphTextView) case "figure": for subelement in element.children() { switch subelement.tagName() { case "img": let imageView = UIImageView() // Need to check how the source of the image is stored try? imageView.kf.setImage(with: URL(string: subelement.attr("src"))) imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFill imageView.translatesAutoresizingMaskIntoConstraints = false bodyViews.append(imageView) case "figcaption": let paragraphTextView = UITextView() paragraphTextView.isScrollEnabled = false paragraphTextView.isEditable = false paragraphTextView.attributedText = try? subelement.html().htmlToAttributedString paragraphTextView.textColor = .label paragraphTextView.font = UIFont.preferredFont(forTextStyle: .caption1, compatibleWith: .current) bodyViews.append(paragraphTextView) default: print("subelement default") } } default: print("default") } } } for bodyView in bodyViews { bodyView.translatesAutoresizingMaskIntoConstraints = false contentView.addArrangedSubview(bodyView) NSLayoutConstraint.activate([ bodyView.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor), bodyView.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor) ]) if bodyView is UIImageView { _ = bodyView.anchor(nil, left: contentView.layoutMarginsGuide.leftAnchor, bottom: nil, right: contentView.layoutMarginsGuide.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: contentView.layoutMarginsGuide.layoutFrame.width, heightConstant: contentView.layoutMarginsGuide.layoutFrame.width * 0.6) } bodyView.sizeToFit() } } func prepareReadMoreButton() { let dpLogo = UIImageView() dpLogo.image = UIImage(named: "dpPlusLogo") dpLogo.clipsToBounds = true dpLogo.contentMode = .scaleAspectFit dpLogo.translatesAutoresizingMaskIntoConstraints = false contentView.addArrangedSubview(dpLogo) _ = dpLogo.anchor(nil, left: contentView.layoutMarginsGuide.leftAnchor, bottom: nil, right: contentView.layoutMarginsGuide.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: contentView.layoutMarginsGuide.layoutFrame.width * 0.4, heightConstant: contentView.layoutMarginsGuide.layoutFrame.width * 0.4) readMoreButton.setTitle("Read more on DP+", for: .normal) contentView.addArrangedSubview(readMoreButton) readMoreButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .headline, compatibleWith: .current) readMoreButton.setTitleColor(.labelPrimary, for: .normal) readMoreButton.addTarget(self, action: #selector(readMore), for: .touchUpInside) NSLayoutConstraint.activate([ readMoreButton.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor), readMoreButton.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor), readMoreButton.centerXAnchor.constraint(equalTo: contentView.centerXAnchor) ]) } @objc func readMore() { if let url = URL(string: "itms-apps://apple.com/app/id1550818171"), UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) } } }
mit
098dbf849499200c4d1010ac491e92b8
49.799065
360
0.658357
5.841483
false
false
false
false
heshamsalman/OctoViewer
OctoViewerTests/APIKeysSpec.swift
1
1808
// // APIKeysSpec.swift // OctoViewer // // Created by Hesham Salman on 5/25/17. // Copyright © 2017 Hesham Salman // // 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 // // http://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 Quick import Nimble @testable import OctoViewer class APIKeysSpec: QuickSpec { override func spec() { var keys: APIKeys! describe("initializers") { context("default init") { beforeEach { keys = APIKeys() } it("assigns values from the bundle dictionary") { let clientId = Bundle.main.infoDictionary!["ClientId"] as! String let clientSecret = Bundle.main.infoDictionary!["ClientSecret"] as! String expect(keys.clientId).to(equal(clientId)) expect(keys.clientSecret).to(equal(clientSecret)) } } } describe("Response Stubbing") { var keys: APIKeys! context("when the response should be stubbed") { it("stubs when client id is short") { keys = APIKeys(clientId: ".", secret: "|") expect(keys.stubResponses).to(beTruthy()) } it("does not stub when client id is long") { keys = APIKeys() expect(keys.stubResponses).to(beFalsy()) } } context("when the response should not be stubbed") { } } } }
apache-2.0
c2e248afabb5fad20f898154ff087d54
26.8
83
0.636967
4.241784
false
false
false
false
do5/mcgen
template/swift/main.swift
1
941
import Foundation //инрерфейсы public protocol MyInterface { var property: String {get set}; func Do(); func GetString(name: String) -> String; } //константы let const1 = 0; let const2 = 1; public class ConstClass { public let const1 = 5; internal let const2 = 6; private let const3 = 7; } //перечисления enum Rank: Int { case Ace = 1 case Two = 3 case Three = 8 } //классы public class A { public var X: Int; public var Y: Double; init(){ self.X = 0; self.Y = 1.1; } public func Sum(a: Int, b: Int) -> Int{ return a + b; } } public class B: A, MyInterface{ override init() { self.property = "default"; super.init(); } public var property: String; public func Do() { } public func GetString(name: String) -> String{ return "Hello " + name; } } func main(){ let b = B(); print(b.GetString("AAA")); } main();
mit
b9607f099034cf189c43cb84a170e83b
12.907692
48
0.596239
3.033557
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/TinyConstraints/TinyConstraints/Classes/Constraints.swift
2
2392
// // MIT License // // Copyright (c) 2017 Robert-Hein Hooijmans <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if os(OSX) import AppKit #else import UIKit #endif public typealias Constraint = NSLayoutConstraint public typealias Constraints = [Constraint] public enum ConstraintRelation: Int { case equal = 0 case equalOrLess = -1 case equalOrGreater = 1 } public extension Collection where Iterator.Element == Constraint { func activate() { if let constraints = self as? Constraints { Constraint.activate(constraints) } } func deActivate() { if let constraints = self as? Constraints { Constraint.deactivate(constraints) } } } #if os(OSX) public extension Constraint { @objc func with(_ p: Constraint.Priority) -> Self { priority = p return self } func set(_ active: Bool) -> Self { isActive = active return self } } #else public extension Constraint { @objc func with(_ p: LayoutPriority) -> Self { priority = p return self } func set(_ active: Bool) -> Self { isActive = active return self } } #endif
mit
0b4a8cb21361bc5056a817deab96491d
27.47619
83
0.647575
4.487805
false
false
false
false
EZ-NET/ESGists
Sources/ESGists/API/Responses/ID.swift
1
796
// // ID.swift // ESGist // // Created by Tomohiro Kumagai on H27/07/20. // Copyright © 平成27年 EasyStyle G.K. All rights reserved. // import Himotoki import Ocean public struct ID { public var value:UInt64 public init(_ value:UInt64) { self.value = value } } extension ID { public init?(string:String) { guard let value = UInt64(string) else { return nil } self.value = value } } extension ID : Decodable { public static func decode(e: Extractor) throws -> ID { return try ID(UInt64.decode(e)) } } extension ID : CustomStringConvertible { public var description:String { return "\(self.value)" } } // MARK : Equatable extension ID : Equatable { } public func == (lhs:ID, rhs:ID) -> Bool { return lhs.value == rhs.value }
mit
6e99b230657886222b57f5062f9908f6
12.15
57
0.640051
3.094118
false
false
false
false
ustwo/US2MapperKit
Source/US2MapperKit/Validator/Validator.swift
1
2404
// // Validator.swift // US2MapperKit // // Created by Anton Doudarev on 7/17/15. // Copyright © 2015 Ustwo. All rights reserved. // import Foundation public class Validator { // MARK Validates that all the non-optional values were received or defaulted final class func validateResponse(forValues retrievedValues : Dictionary<String, Any>, mappedTo mappingConfiguration : Dictionary<String, Dictionary<String, AnyObject>>, forType className : String, withData data : Dictionary<String, AnyObject>) -> Bool { #if US2MAPPER_DEBUG var missingPropertyKeyArray = Array<String>() #endif // Validate that all non-optional properties have a value assigned for (propertyKey, propertyMapping) in mappingConfiguration { if let isPropertyNonOptional : AnyObject = propertyMapping[US2MapperNonOptionalKey] { if isPropertyNonOptional.boolValue == true { if let _ = retrievedValues[propertyKey] { // If value was mapped, continue with validation continue } else { #if US2MAPPER_DEBUG missingPropertyKeyArray.append(propertyKey) #else return false #endif } } } } #if US2MAPPER_DEBUG if (missingPropertyKeyArray.count > 0) { printDebugStatement(className, missingPropertyKeyArray: missingPropertyKeyArray, data : data) return false } #endif return true } // MARK Debug Enabled Methods final class func printDebugStatement(className : String, missingPropertyKeyArray : Array<String>, data : Dictionary<String, AnyObject>){ if (missingPropertyKeyArray.count > 0) { print("\n\n\(className) instance could not be parsed, missing values for the following non-optional properties:") for propertyKey in missingPropertyKeyArray { print("\n- \(propertyKey)") } print("\n\nResponse:\n\(data)\n\n") } } }
mit
26f6a58234106c80d9fac50acbba62ed
35.984615
140
0.545152
5.575406
false
false
false
false
juliensagot/JSNavigationController
ExampleStoryboard/ExampleStoryboard/ViewController.swift
1
2266
import AppKit import JSNavigationController private extension Selector { static let pushToNextViewController = #selector(ViewController.pushToNextViewController) static let popViewController = #selector(ViewController.popViewController) } class ViewController: JSViewController { // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() view.translatesAutoresizingMaskIntoConstraints = false view.wantsLayer = true view.layer?.backgroundColor = NSColor(deviceRed: 240/255, green: 240/255, blue: 240/255, alpha: 1.0).cgColor } override func viewDidAppear() { super.viewDidAppear() view.superview?.addConstraints(viewConstraints()) // NavigationBar (navigationBarVC as? BasicNavigationBarViewController)?.backButton?.target = self (navigationBarVC as? BasicNavigationBarViewController)?.backButton?.action = .popViewController (navigationBarVC as? BasicNavigationBarViewController)?.nextButton?.target = self (navigationBarVC as? BasicNavigationBarViewController)?.nextButton?.action = .pushToNextViewController } override func viewDidDisappear() { view.superview?.removeConstraints(viewConstraints()) } // MARK: - Layout fileprivate func viewConstraints() -> [NSLayoutConstraint] { let left = NSLayoutConstraint( item: view, attribute: .left, relatedBy: .equal, toItem: view.superview, attribute: .left, multiplier: 1.0, constant: 0.0 ) let right = NSLayoutConstraint( item: view, attribute: .right, relatedBy: .equal, toItem: view.superview, attribute: .right, multiplier: 1.0, constant: 0.0 ) let top = NSLayoutConstraint( item: view, attribute: .top, relatedBy: .equal, toItem: view.superview, attribute: .top, multiplier: 1.0, constant: 0.0 ) let bottom = NSLayoutConstraint( item: view, attribute: .bottom, relatedBy: .equal, toItem: view.superview, attribute: .bottom, multiplier: 1.0, constant: 0.0 ) return [left, right, top, bottom] } @objc func pushToNextViewController() { if let destinationViewController = destinationViewController { navigationController?.push(viewController: destinationViewController, animated: true) } } @objc func popViewController() { navigationController?.popViewController(animated: true) } }
mit
01469a25a784cd39aa6dd8527fa45bb5
32.323529
110
0.753751
4.18854
false
false
false
false
martinomamic/CarBooking
CarBooking/Models/Car/CDCar.swift
1
750
// // CDCar.swift // CarBooking // // Created by Martino Mamic on 29/07/2017. // Copyright © 2017 Martino Mamic. All rights reserved. // import CoreData import Foundation extension CDCar { func fromCar(car: Car) { id = Int16(car.id) name = car.name info = car.info shortInfo = car.shortInfo image = car.image } class func carToCDCar(car: Car)-> CDCar { let cdc = CDCar() cdc.id = Int16(car.id) cdc.name = car.name cdc.info = car.info cdc.image = car.image cdc.shortInfo = car.shortInfo return cdc } func toCar() -> Car { return Car(id: Int(id), name: name!, shortInfo: shortInfo!, info: info!, image: image!) } }
mit
728284d1aba7ddfdb0beabc6bdde28c2
21.029412
95
0.570093
3.34375
false
false
false
false
ochan1/OC-PublicCode
5. Intro-Optionals-Dictionaries-Playground-swift3/Optionals-Dictionaries.playground/Contents.swift
1
9937
/*: ![Make School Banner](./swift_banner.png) # Optionals in Swift ## Introduction to Optionals Sometimes, it's useful to express the fact that a variable may contain a value or no value at all. Swift allows us to do this with **optionals**. Optionals contain **either** a value **or** `nil` (meaning "no value"). Optionals are like boxes that may have something inside, or they may have nothing inside. Some languages, like Objective-C, Python and Java, allow a variable to be set to `nil` or `null` without its type expressly indicating that a value may be absent. Swift is much more strict about when variables can lack a value, and this is very helpful in avoiding bugs where we think we have a value when in fact we don't. Functions can return an optional to indicate when the operation has failed or they have no value to give back to you. We express the fact that a value is of optional type by putting a question mark (`?`) at the end of the type name. For example, here is how we declare a variable of type `Int?` (read as "optional `Int`"): */ var maybeAnInt: Int? = 15 //: Here, we have expressly given the variable a value of 15, but we could just as easily have assigned it `nil`: maybeAnInt = nil //: Now `maybeAnInt` is `nil`, which is to say it has _no value_. If `maybeAnInt` had just been of type Int, we could not have set it to `nil`. /*: ## Unwrapping an Optional When we retrieve the value from an optional, we say we "unwrap" it. This is like opening the box and seeing whether there's anything inside. We can test whether an optional has a value by comparing the whole thing to `nil`. If it is not equal to `nil`, it contains a value. Woo hoo! We can then safely use **force unwrapping** to get its value. Force unwrapping is done by putting an exclamation point (`!`) after the name of the variable we want to unwrap. This assures Swift that the optional contains a value and that it is therefore safe to read. If we're wrong, the code will crash. Here, we test whether `maybeAnInt` has a value and if it does, we rip open the box (force unwrap) and print its value. */ if maybeAnInt != nil { print("maybeAnInt contains a value, and it is \(maybeAnInt!)") } else { print("maybeAnInt does not contain a value") } /*: - experiment: Try changing the value of `maybeAnInt` from `nil` to something else above. Notice which message is printed depending on the value. */ /*: ## Optional Binding A more compact way of testing and acting on an optional value is **optional binding**, where we test for the presence of an object and, if it exists, we create a new variable for this object in a narrower scope. Here, we "bind" the value of `maybeAnInt` (if present) to a new constant named `definitelyAnInt`, which only exists inside the `if/else` block, and print it: */ if let definitelyAnInt = maybeAnInt { print("maybeAnInt contains a value, and it is \(definitelyAnInt)") } else { print("maybeAnInt does not contain a value") } /*: - experiment: Try changing the value of `maybeAnInt` again, and again take note that if it contains a value, the message indicates this and the local variable `definitelyAnInt` has the same value. If it doesn't contain a value, then `definitelyAnInt` won't be created. */ /*: ## Implicitly Unwrapped Optionals Sometimes we want to indicate that an optional will always have a value when we need to read it. For example, this happens when we separate the declaration of an optional from the first time we set its value. The first time we declare the optional, it won't have a value, but we'll set it before we use it. To support this scenario, we can declare a variable as an **implicitly unwrapped optional**. Implicitly unwrapped optionals are declared by placing an exclamation point (`!`) after the type to indicate that they **can** contain `nil`, but must always have a value when they are read: */ var alwaysAString: String! = nil /*: Notice that we initially assign `nil` to this implicitly unwrapped optional `String`. If we were to try to use it at this point, we would trigger a runtime error: */ //let stringLength = alwaysAString.characters.count /*: Try uncommenting the line above and seeing what happens. You will probably notice that the remainder of the Playground can no longer be evaluated. This is because the underlying process crashes when it attempts to access the variable. That's why we have to ensure that we never read an implicitly-unwrapped optional before setting its value. */ /*: Let's assign a value so the variable is no longer `nil`: */ alwaysAString = "Now I have a value!" //: Now, when we print this string, it is implicitly unwrapped to the `String` value it contains: print(alwaysAString) /*: The important takeaway here is that declaring a variable as implicitly unwrapped allows Swift to _automatically_ unwrap the value whenever it is used. This is the inverse of the usual situation: normally, we use the `!` to force-unwrap a value once we're sure it contains a value. With implicitly unwrapped optionals, we assert from the moment we declare the variable that it will _never_ be `nil` when it is used. That can save us a lot of typing (and visual clutter!) for variables that are accessed frequently. But it's important to be 100% sure that the variable is assigned before it's read the first time, because otherwise accessing it will result in crash. */ /*: ## Calling Methods on Optionals In order to call methods on optionals, you must first give Swift something that is non-optional, either through an implicitly unwrapped optional or by force unwrapping the optional where the method is called. Calling a method directly on an optional is a compile-time error. Uncomment the following line to see: */ //let intDescription = maybeAnInt.description // Value of optional type 'Int?' not unwrapped! /*: But we're programmers and we like working around the rules. You don't have to give Swift a non-optional if you use a technique called **optional chaining**. Chaining allows you to try to call a method on an optional, which calls the method if the optional has a value, and returns `nil` if it does not. Chaining is performed by placing a question mark between the variable name and the dot, parenthesis, or bracket that follows it: */ let optionalArray: [Int]? = [ 1, 2, 3, 4 ] let arrayLength = optionalArray?.count let firstElement = optionalArray?[0] /*: Placing a `?` after the name `optionalArray` will cause Swift to check whether the variable is `nil` before attempting to call `count` or access the array. The types of these expressions are optionals of the same type as the return type of method (so the call to `count`, which normally produces an `Int`, produces an `Int?` in this case). Phew! Still with us? - experiment: Set `optionalArray` to `nil` and observe how the output values change. */ /*: ## The Nil Coalescing Operator //: //: Sometimes we want to use a default value in the place of an optional when it turns out to be `nil`. For example, we might want to provide a placeholder name for an object when its own `name` property is `nil`, or use 0 if an integer is `nil`. //: (If you know Java, you may recognize this as similar to the "conditional", or "ternary" operator.) //: Swift provides a way to do this very compactly: the nil-coalescing operator (`??`). When the optional to the left of the operator has a value, that value becomes the value of the expression. When the optional is `nil`, the value of the expression is the value on the right of the operator. Let's look at an example: */ let optionalString: String? = nil let petName = optionalString ?? "Fido" //: So if `optionalString` is not nil, we'll set `petName` to the value of `optionalString`. If it is nil, we'll set `petName` to "Fido". /*: ## Recap In this Playground we have looked at some of the capabilities of optionals in Swift. Optionals are a fundamental part of Swift that allow us to be very clear about when variables contain values and when they do not. All of the rules associated with optionals can be confusing at first, but you will quickly gain an intuition by putting your knowledge into practice. The compiler will try to help you along the way, reminding you when you make mistakes. */ /*: ## Challenge Optionals are variables that may have a value but sometimes do not. This can occur more often than you would think! Anytime your app reaches out to internet, you can't be sure that you will get the results you are expecting. This values will always be an optional. Use the concepts covered in this section to test your knowledge and expand your skills. - callout(Challenge): You are writing an app that deals with usernames retreived from the internet. 1. Imagine your app will display a username if availble. If no user is signed in you can display their name. This might be a good place for an optional. Define a variable named `username`, and make it type `String?` (optional) 2. Print the value of `username`. You should get `nil`. 3. Set the value of `username` to any name. 4. Print `username` again. You should see something like: `Optional("Joe")` 5. Now that `username` has a value you can safely unwrap it with the `!`. Print the force unwrapped username. 6. Force unwrapping is a good habit! Print `username` with optional binding instead (`if let`). 7. Use the nil-coalescing operator to set the value of a variable to the value of `username`, or to `"Anonymous"` if `username` is `nil`. */ // Write your answers here: /*: ## Answers */ // Your answer should look similar to this /* var username: String? // 1 print(username) // 2 username = "Joe" // 3 print(username) // 4 print(username!) // 5 if let username = username { // 6 print(username) } let message = username ?? "Anonymous" // 7 */ /*: [Next](@next) */
mit
b96cbe9740b2a1f66177349744095eb9
59.224242
665
0.739056
4.266638
false
false
false
false
francisykl/PagingMenuController
Example/PagingMenuControllerDemo/UsersViewController.swift
4
2005
// // UsersViewController.swift // PagingMenuControllerDemo // // Created by Yusuke Kita on 5/10/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit class UsersViewController: UITableViewController { var users = [[String: AnyObject]]() class func instantiateFromStoryboard() -> UsersViewController { let storyboard = UIStoryboard(name: "MenuViewController", bundle: nil) return storyboard.instantiateViewController(withIdentifier: String(describing: self)) as! UsersViewController } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() let url = URL(string: "https://api.github.com/users") let request = URLRequest(url: url!) let session = URLSession(configuration: URLSessionConfiguration.default) let task = session.dataTask(with: request) { [weak self] data, response, error in let result = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [[String: AnyObject]] self?.users = result ?? [] DispatchQueue.main.async(execute: { () -> Void in self?.tableView.reloadData() }) } task.resume() } } extension UsersViewController { // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let user = users[(indexPath as NSIndexPath).row] cell.textLabel?.text = user["login"] as? String return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } }
mit
e769afadc9e640306dd631a8a7c06df0
32.416667
123
0.641895
5.127877
false
false
false
false
revealapp/Revert
Revert/Sources/VisualEffectViewController.swift
1
2279
// // Copyright © 2019 Itty Bitty Apps. All rights reserved. import UIKit final class VisualEffectViewController: RevertViewController { // MARK: - Types fileprivate enum Corner: CaseIterable { case bottomRight case topRight case bottomLeft case topLeft } // MARK: - UIViewController override var preferredFocusedView: UIView? { return self.scrollView } override func viewDidLoad() { super.viewDidLoad() #if os(tvOS) self.scrollView.panGestureRecognizer.allowedTouchTypes = [UITouch.TouchType.indirect.rawValue as NSNumber] #endif } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.scrollView.flashScrollIndicators() if !self.isAnimationLoaded { self.performMoveAnimation() self.isAnimationLoaded = true } } // MARK: - Private @IBOutlet private weak var scrollView: RevertFocusableScrollView! private var isAnimationLoaded = false private func performMoveAnimation() { self.move(to: Corner.allCases.makeIterator()) } private func move(to pathIterator: IndexingIterator<[Corner]>) { var pathIterator = pathIterator guard let corner = pathIterator.next() else { return } UIView.animate( withDuration: 6, animations: { self.scrollView.setContentOffset(self.scrollView.contentOffset(for: corner), animated: false) }, completion: { _ in self.move(to: pathIterator) } ) } } private extension UIScrollView { func contentOffset(for corner: VisualEffectViewController.Corner) -> CGPoint { switch corner { case .bottomRight: return CGPoint(x: rightEdge, y: bottomEdge) case .bottomLeft: return CGPoint(x: leftEdge, y: bottomEdge) case .topLeft: return CGPoint(x: leftEdge, y: topEdge) case .topRight: return CGPoint(x: rightEdge, y: topEdge) } } var bottomEdge: CGFloat { return self.contentSize.height - self.bounds.size.height + self.contentInset.top } var rightEdge: CGFloat { return self.contentSize.width - self.bounds.size.width + self.contentInset.left } var topEdge: CGFloat { return self.contentInset.top } var leftEdge: CGFloat { return self.contentInset.left } }
bsd-3-clause
69b50a1e976a04bea514563ec244cf70
22.244898
110
0.68964
4.423301
false
false
false
false
eliasbagley/Pesticide
debugdrawer/AppDelegate.swift
1
4024
// // AppDelegate.swift // debugdrawer // // Created by Elias Bagley on 11/21/14. // Copyright (c) 2014 Rocketmade. All rights reserved. // import UIKit import Alamofire @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var manager: Manager? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. #if DEBUG let threeFingerTap = UITapGestureRecognizer(target: self, action: Selector("threeFingerTap")) threeFingerTap.numberOfTouchesRequired = 3 self.window?.addGestureRecognizer(threeFingerTap) Pesticide.setWindow(self.window!) Pesticide.addProxy({ (config: NSURLSessionConfiguration) in self.manager = Alamofire.Manager(configuration: config) }) Pesticide.addHeader("Custom Controls") #endif var rootView = SampleViewController() if let window = self.window { window.rootViewController = rootView } return true } func makeNetworkRequest() { self.manager?.request(Router.ROOT).response { (request, response, data, error) in println(request) println(response) println(data) println(error) Pesticide.log("Network call success") } } #if DEBUG func threeFingerTap() { Pesticide.toggle() } #endif func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } enum Router: URLRequestConvertible { static let baseURLString = "http://httpbin.org" case ROOT var method: Alamofire.Method { switch self { case .ROOT: return .GET } } // MARK: URLRequestConvertible var URLRequest:NSURLRequest { let (path: String, parameters: [String: AnyObject]?) = { switch (self) { case .ROOT: return ("/", nil) } }() let URL = NSURL(string: Router.baseURLString)! let URLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path)) URLRequest.HTTPMethod = method.rawValue return URLRequest } }
mit
18d689dbe3c52840abb26519674fd495
34.298246
285
0.663519
5.47483
false
false
false
false
alessandrostone/RIABrowser
DemoApp/object/User.swift
1
745
// // User.swift // // Created by Yoshiyuki Tanaka on 2015/05/16. // Copyright (c) 2015 Yoshiyuki Tanaka. All rights reserved. // import UIKit import RealmSwift class User : Object { dynamic var id = NSUUID().UUIDString dynamic var name = "Taro" dynamic var age = 18 dynamic var height:Float = 172.4 dynamic var weight:Double = 60.2 dynamic var birthDay = NSDate() dynamic var profileImage = NSData(data: UIImagePNGRepresentation(UIImage(named: "sample_image"))) dynamic var favoriteMusic = NSData() dynamic var hasCar = true dynamic var favoriteBook = Book() let books = List<Book>() override static func primaryKey() -> String? { return "id" } } class Book : Object { dynamic var name = "book title" }
mit
87ace74b5ba7224561ef8292d78fbe2d
23.032258
99
0.692617
3.762626
false
false
false
false
open-telemetry/opentelemetry-swift
Tests/OpenTelemetrySdkTests/Trace/MultiSpanProcessorTests.swift
1
4134
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import OpenTelemetryApi @testable import OpenTelemetrySdk import XCTest class MultiSpanProcessorTest: XCTestCase { let spanProcessor1 = SpanProcessorMock() let spanProcessor2 = SpanProcessorMock() let readableSpan = ReadableSpanMock() override func setUp() { spanProcessor1.isStartRequired = true spanProcessor1.isEndRequired = true spanProcessor2.isStartRequired = true spanProcessor2.isEndRequired = true } func testEmpty() { let multiSpanProcessor = MultiSpanProcessor(spanProcessors: [SpanProcessor]()) multiSpanProcessor.onStart(parentContext: nil, span: readableSpan) multiSpanProcessor.onEnd(span: readableSpan) multiSpanProcessor.shutdown() } func testOneSpanProcessor() { let multiSpanProcessor = MultiSpanProcessor(spanProcessors: [spanProcessor1]) multiSpanProcessor.onStart(parentContext: nil, span: readableSpan) XCTAssert(spanProcessor1.onStartCalledSpan === readableSpan) multiSpanProcessor.onEnd(span: readableSpan) XCTAssert(spanProcessor1.onEndCalledSpan === readableSpan) multiSpanProcessor.forceFlush() XCTAssertTrue(spanProcessor1.forceFlushCalled) multiSpanProcessor.shutdown() XCTAssertTrue(spanProcessor1.shutdownCalled) } func testOneSpanProcessorNoRequeriments() { spanProcessor1.isStartRequired = false spanProcessor1.isEndRequired = false let multiSpanProcessor = MultiSpanProcessor(spanProcessors: [spanProcessor1]) multiSpanProcessor.onStart(parentContext: nil, span: readableSpan) XCTAssertFalse(multiSpanProcessor.isStartRequired) XCTAssertFalse(multiSpanProcessor.isEndRequired) multiSpanProcessor.onStart(parentContext: nil, span: readableSpan) XCTAssertFalse(spanProcessor1.onStartCalled) multiSpanProcessor.onEnd(span: readableSpan) XCTAssertFalse(spanProcessor1.onEndCalled) multiSpanProcessor.forceFlush() XCTAssertTrue(spanProcessor1.forceFlushCalled) multiSpanProcessor.shutdown() XCTAssertTrue(spanProcessor1.shutdownCalled) } func testTwoSpanProcessor() { let multiSpanProcessor = MultiSpanProcessor(spanProcessors: [spanProcessor1, spanProcessor2]) multiSpanProcessor.onStart(parentContext: nil, span: readableSpan) XCTAssert(spanProcessor1.onStartCalledSpan === readableSpan) XCTAssert(spanProcessor2.onStartCalledSpan === readableSpan) multiSpanProcessor.onEnd(span: readableSpan) XCTAssert(spanProcessor1.onEndCalledSpan === readableSpan) XCTAssert(spanProcessor2.onEndCalledSpan === readableSpan) multiSpanProcessor.forceFlush() XCTAssertTrue(spanProcessor1.forceFlushCalled) XCTAssertTrue(spanProcessor2.forceFlushCalled) multiSpanProcessor.shutdown() XCTAssertTrue(spanProcessor1.shutdownCalled) XCTAssertTrue(spanProcessor2.shutdownCalled) } func testTwoSpanProcessorDifferentRequirements() { spanProcessor1.isEndRequired = false spanProcessor2.isStartRequired = false let multiSpanProcessor = MultiSpanProcessor(spanProcessors: [spanProcessor1, spanProcessor2]) XCTAssertTrue(multiSpanProcessor.isStartRequired) XCTAssertTrue(multiSpanProcessor.isEndRequired) multiSpanProcessor.onStart(parentContext: nil, span: readableSpan) XCTAssert(spanProcessor1.onStartCalledSpan === readableSpan) XCTAssertFalse(spanProcessor2.onStartCalled) multiSpanProcessor.onEnd(span: readableSpan) XCTAssertFalse(spanProcessor1.onEndCalled) XCTAssert(spanProcessor2.onEndCalledSpan === readableSpan) multiSpanProcessor.forceFlush() XCTAssertTrue(spanProcessor1.forceFlushCalled) XCTAssertTrue(spanProcessor2.forceFlushCalled) multiSpanProcessor.shutdown() XCTAssertTrue(spanProcessor1.shutdownCalled) XCTAssertTrue(spanProcessor2.shutdownCalled) } }
apache-2.0
8478ee03cec693622e16a5836c311a66
38.371429
101
0.744315
5.004843
false
true
false
false
yzhou65/DSWeibo
DSWeibo/Classes/Home/Popover/PopoverAnimator.swift
1
4274
// // PopoverAnimator.swift // DSWeibo // // Created by Yue on 9/7/16. // Copyright © 2016 fda. All rights reserved. // import UIKit //定义敞亮保存通知的名称 let YZPopoverAnimatorWillShow = "YZPopoverAnimatorWillShow" let YZPopoverAnimatorWillDismiss = "YZPopoverAnimatorWillDismiss" class PopoverAnimator: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning { //记录当前是否是展开 var isPresent: Bool = false ///定义属性保存菜单的大小 var presentFrame = CGRectZero //实现代理方法,告诉系统谁来负责转场动画 //UIPresentationController是ios8推出的专门用于负责转场动画的 func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? { let pc = PopoverPresentationController(presentedViewController: presented, presentingViewController: presenting) //设置菜单的大小 pc.presentFrame = presentFrame return pc } // MARK: 只要实现了以下方法,那么系统自带的默认动画就没有了,所有东西都需要程序员手动实现 /** 展现view的时候调用,告诉系统谁来负责modal的展现动画 */ func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = true //发送通知,通知控制器即将展开 NSNotificationCenter.defaultCenter().postNotificationName(YZPopoverAnimatorWillShow, object: self) return self } /** 关闭view的时候调用,告诉系统谁来负责Modal的消失动画 */ func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = false //发送通知,通知控制器即将关闭 NSNotificationCenter.defaultCenter().postNotificationName(YZPopoverAnimatorWillDismiss, object: self) return self } //MARK: - UIViewControllerAnimatedTransitioning的方法 /** 返回动画时长 */ func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } /** 告诉系统执行怎样的动画,无论是展现还是消失都会调用这个方法 */ func animateTransition(transitionContext: UIViewControllerContextTransitioning) { if isPresent{ //展开动画 let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! toView.transform = CGAffineTransformMakeScale(1.0, 0.0) //注意:一定要将试图添加到容器 transitionContext.containerView()?.addSubview(toView) //设置锚点(从那个点开始展开view) toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0) //执行动画 UIView.animateWithDuration(transitionDuration(transitionContext), animations: { //清空transform toView.transform = CGAffineTransformIdentity }) { (_) in //动画执行完毕要告诉系统. 如果不写可能会导致未知错误 transitionContext.completeTransition(true) } } else { //关闭动画 let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! UIView.animateWithDuration(transitionDuration(transitionContext), animations: { //注意:犹豫CGFloat不准确的,所以如果写0.0会没有动画.因此在 fromView.transform = CGAffineTransformMakeScale(1.0, 0.00001) }, completion: { (_) in //动画执行完毕要告诉系统. 如果不写可能会导致未知错误 transitionContext.completeTransition(true) }) } } }
apache-2.0
fa83327469280e7c51972ac55f6b01a3
33.352381
219
0.665096
5.296623
false
false
false
false
SwifterSwift/SwifterSwift
Sources/SwifterSwift/CoreAnimation/CATransform3DExtensions.swift
1
9181
// CATransform3DExtensions.swift - Copyright 2020 SwifterSwift // swiftlint:disable identifier_name #if canImport(QuartzCore) import QuartzCore // MARK: - Equatable extension CATransform3D: Equatable { // swiftlint:disable missing_swifterswift_prefix /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. @inlinable public static func == (lhs: CATransform3D, rhs: CATransform3D) -> Bool { CATransform3DEqualToTransform(lhs, rhs) } // swiftlint:disable missing_swifterswift_prefix } // MARK: - Static Properties public extension CATransform3D { /// SwifterSwift: The identity transform: [1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1]. @inlinable static var identity: CATransform3D { CATransform3DIdentity } } // MARK: - Codable extension CATransform3D: Codable { // swiftlint:disable missing_swifterswift_prefix /// Creates a new instance by decoding from the given decoder. /// /// This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid. /// - Parameter decoder: The decoder to read data from. @inlinable public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() self.init(m11: try container.decode(CGFloat.self), m12: try container.decode(CGFloat.self), m13: try container.decode(CGFloat.self), m14: try container.decode(CGFloat.self), m21: try container.decode(CGFloat.self), m22: try container.decode(CGFloat.self), m23: try container.decode(CGFloat.self), m24: try container.decode(CGFloat.self), m31: try container.decode(CGFloat.self), m32: try container.decode(CGFloat.self), m33: try container.decode(CGFloat.self), m34: try container.decode(CGFloat.self), m41: try container.decode(CGFloat.self), m42: try container.decode(CGFloat.self), m43: try container.decode(CGFloat.self), m44: try container.decode(CGFloat.self)) } /// Encodes this value into the given encoder. /// /// If the value fails to encode anything, encoder will encode an empty keyed container in its place. /// /// This function throws an error if any values are invalid for the given encoder’s format. /// - Parameter encoder: The encoder to write data to. @inlinable public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(m11) try container.encode(m12) try container.encode(m13) try container.encode(m14) try container.encode(m21) try container.encode(m22) try container.encode(m23) try container.encode(m24) try container.encode(m31) try container.encode(m32) try container.encode(m33) try container.encode(m34) try container.encode(m41) try container.encode(m42) try container.encode(m43) try container.encode(m44) } // swiftlint:enable missing_swifterswift_prefix } // MARK: - Initializers public extension CATransform3D { /// SwifterSwift: Returns a transform that translates by `(tx, ty, tz)`. /// - Parameters: /// - tx: x-axis translation /// - ty: y-axis translation /// - tz: z-axis translation @inlinable init(translationX tx: CGFloat, y ty: CGFloat, z tz: CGFloat) { self = CATransform3DMakeTranslation(tx, ty, tz) } /// SwifterSwift: Returns a transform that scales by `(sx, sy, sz)`. /// - Parameters: /// - sx: x-axis scale /// - sy: y-axis scale /// - sz: z-axis scale @inlinable init(scaleX sx: CGFloat, y sy: CGFloat, z sz: CGFloat) { self = CATransform3DMakeScale(sx, sy, sz) } /// SwifterSwift: Returns a transform that rotates by `angle` radians about the vector `(x, y, z)`. /// /// If the vector has zero length the behavior is undefined. /// - Parameters: /// - angle: The angle of rotation /// - x: x position of the vector /// - y: y position of the vector /// - z: z position of the vector @inlinable init(rotationAngle angle: CGFloat, x: CGFloat, y: CGFloat, z: CGFloat) { self = CATransform3DMakeRotation(angle, x, y, z) } } // MARK: - Properties public extension CATransform3D { /// SwifterSwift: Returns `true` if the receiver is the identity transform. @inlinable var isIdentity: Bool { CATransform3DIsIdentity(self) } } // MARK: - Methods public extension CATransform3D { /// SwifterSwift: Translate the receiver by `(tx, ty, tz)`. /// - Parameters: /// - tx: x-axis translation /// - ty: y-axis translation /// - tz: z-axis translation /// - Returns: The translated matrix. @inlinable func translatedBy(x tx: CGFloat, y ty: CGFloat, z tz: CGFloat) -> CATransform3D { CATransform3DTranslate(self, tx, ty, tz) } /// SwifterSwift: Scale the receiver by `(sx, sy, sz)`. /// - Parameters: /// - sx: x-axis scale /// - sy: y-axis scale /// - sz: z-axis scale /// - Returns: The scaled matrix. @inlinable func scaledBy(x sx: CGFloat, y sy: CGFloat, z sz: CGFloat) -> CATransform3D { CATransform3DScale(self, sx, sy, sz) } /// SwifterSwift: Rotate the receiver by `angle` radians about the vector `(x, y, z)`. /// /// If the vector has zero length the behavior is undefined. /// - Parameters: /// - angle: The angle of rotation /// - x: x position of the vector /// - y: y position of the vector /// - z: z position of the vector /// - Returns: The rotated matrix. @inlinable func rotated(by angle: CGFloat, x: CGFloat, y: CGFloat, z: CGFloat) -> CATransform3D { CATransform3DRotate(self, angle, x, y, z) } /// SwifterSwift: Invert the receiver. /// /// Returns the original matrix if the receiver has no inverse. /// - Returns: The inverted matrix of the receiver. @inlinable func inverted() -> CATransform3D { CATransform3DInvert(self) } /// SwifterSwift: Concatenate `transform` to the receiver. /// - Parameter t2: The transform to concatenate on to the receiver /// - Returns: The concatenated matrix. @inlinable func concatenating(_ t2: CATransform3D) -> CATransform3D { CATransform3DConcat(self, t2) } /// SwifterSwift: Translate the receiver by `(tx, ty, tz)`. /// - Parameters: /// - tx: x-axis translation /// - ty: y-axis translation /// - tz: z-axis translation @inlinable mutating func translateBy(x tx: CGFloat, y ty: CGFloat, z tz: CGFloat) { self = CATransform3DTranslate(self, tx, ty, tz) } /// SwifterSwift: Scale the receiver by `(sx, sy, sz)`. /// - Parameters: /// - sx: x-axis scale /// - sy: y-axis scale /// - sz: z-axis scale @inlinable mutating func scaleBy(x sx: CGFloat, y sy: CGFloat, z sz: CGFloat) { self = CATransform3DScale(self, sx, sy, sz) } /// SwifterSwift: Rotate the receiver by `angle` radians about the vector `(x, y, z)`. /// /// If the vector has zero length the behavior is undefined. /// - Parameters: /// - angle: The angle of rotation /// - x: x position of the vector /// - y: y position of the vector /// - z: z position of the vector @inlinable mutating func rotate(by angle: CGFloat, x: CGFloat, y: CGFloat, z: CGFloat) { self = CATransform3DRotate(self, angle, x, y, z) } /// SwifterSwift: Invert the receiver. /// /// Returns the original matrix if the receiver has no inverse. @inlinable mutating func invert() { self = CATransform3DInvert(self) } /// SwifterSwift: Concatenate `transform` to the receiver. /// - Parameter t2: The transform to concatenate on to the receiver @inlinable mutating func concatenate(_ t2: CATransform3D) { self = CATransform3DConcat(self, t2) } } #if canImport(CoreGraphics) import CoreGraphics // MARK: - CGAffineTransform public extension CATransform3D { /// SwifterSwift: Returns true if the receiver can be represented exactly by an affine transform. @inlinable var isAffine: Bool { CATransform3DIsAffine(self) } /// SwifterSwift: Returns the affine transform represented by the receiver. /// /// If the receiver can not be represented exactly by an affine transform the returned value is undefined. @inlinable func affineTransform() -> CGAffineTransform { CATransform3DGetAffineTransform(self) } } #endif #endif
mit
7566b0aeb4afb0c4b62c4d5292c5e399
32.746324
130
0.622726
4.114299
false
false
false
false
Erin-Mounts/BridgeAppSDK
BridgeAppSDKTests/SBASurveyFactoryTests.swift
1
16268
// // SBASurveyFactoryTests.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import XCTest import BridgeAppSDK import ResearchKit class SBASurveyFactoryTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testFactory_CompoundSurveyQuestion_WithRule() { let inputStep: NSDictionary = [ "identifier" : "quiz", "type" : "compound", "items" : [ [ "identifier" : "question1", "type" : "boolean", "prompt" : "Are you older than 18?", "expectedAnswer" : true], [ "identifier" : "question2", "type" : "boolean", "prompt" : "Are you a US resident?", "expectedAnswer" : true], [ "identifier" : "question3", "type" : "boolean", "prompt" : "Can you read English?", "expectedAnswer" : true], ], "skipIdentifier" : "consent", "skipIfPassed" : true ] let step = SBASurveyFactory().createSurveyStepWithDictionary(inputStep) XCTAssertEqual(step.identifier, "quiz") guard let surveyStep = step as? SBASurveyFormStep else { XCTAssert(false, "\(step) is not of expected class type") return } XCTAssertEqual(surveyStep.skipToStepIdentifier, "consent") XCTAssertTrue(surveyStep.skipIfPassed) guard let formItems = surveyStep.formItems where formItems.count == 3 else { XCTAssert(false, "\(surveyStep.formItems) are not of expected count") return } } func testFactory_CompoundSurveyQuestion_NoRule() { let inputStep: NSDictionary = [ "identifier" : "quiz", "type" : "compound", "items" : [ [ "identifier" : "question1", "type" : "boolean", "prompt" : "Are you older than 18?"], [ "identifier" : "question2", "type" : "boolean", "text" : "Are you a US resident?"], [ "identifier" : "question3", "type" : "boolean", "prompt" : "Can you read English?"], ], ] let step = SBASurveyFactory().createSurveyStepWithDictionary(inputStep) XCTAssertEqual(step.identifier, "quiz") guard let surveyStep = step as? ORKFormStep else { XCTAssert(false, "\(step) is not of expected class type") return } XCTAssertEqual(surveyStep.formItems?.count, 3) guard let formItems = surveyStep.formItems where formItems.count == 3 else { return } XCTAssertEqual(formItems[0].text, "Are you older than 18?") XCTAssertEqual(formItems[1].text, "Are you a US resident?") XCTAssertEqual(formItems[2].text, "Can you read English?") } func testFactory_SubtaskSurveyQuestion_WithRule() { let inputStep: NSDictionary = [ "identifier" : "quiz", "type" : "subtask", "items" : [ [ "identifier" : "question1", "type" : "boolean", "prompt" : "I can share my data broadly or only with Sage?", "expectedAnswer" : true], [ "identifier" : "question2", "type" : "boolean", "prompt" : "My name is stored with my results?", "expectedAnswer" : false], [ "identifier" : "question3", "type" : "boolean", "prompt" : "I can leave the study at any time?", "expectedAnswer" : true], ], "skipIdentifier" : "consent", "skipIfPassed" : true ] let step = SBASurveyFactory().createSurveyStepWithDictionary(inputStep) XCTAssertEqual(step.identifier, "quiz") guard let surveyStep = step as? SBASurveySubtaskStep else { XCTAssert(false, "\(step) is not of expected class type") return } XCTAssertEqual(surveyStep.skipToStepIdentifier, "consent") XCTAssertTrue(surveyStep.skipIfPassed) guard let subtask = surveyStep.subtask as? ORKOrderedTask else { XCTAssert(false, "\(surveyStep.subtask) is not of expected class") return } XCTAssertEqual(subtask.steps.count, 3) } func testFactory_DirectNavigationRule() { let inputStep: NSDictionary = [ "identifier" : "ineligible", "prompt" : "You can't get there from here", "detailText": "Tap the button below to begin the consent process", "type" : "instruction", "nextIdentifier" : "exit" ] let step = SBASurveyFactory().createSurveyStepWithDictionary(inputStep) guard let surveyStep = step as? SBADirectNavigationStep else { XCTAssert(false, "\(step) is not of expected class type") return } XCTAssertEqual(surveyStep.identifier, "ineligible") XCTAssertEqual(surveyStep.text, "You can't get there from here") XCTAssertEqual(surveyStep.detailText, "Tap the button below to begin the consent process") XCTAssertEqual(surveyStep.nextStepIdentifier, "exit") } func testFactory_CompletionStep() { let inputStep: NSDictionary = [ "identifier" : "quizComplete", "title" : "Great Job!", "text" : "You answered correctly", "detailText": "Tap the button below to begin the consent process", "type" : "completion", ] let step = SBASurveyFactory().createSurveyStepWithDictionary(inputStep) guard let surveyStep = step as? ORKInstructionStep else { XCTAssert(false, "\(step) is not of expected class type") return } XCTAssertEqual(surveyStep.identifier, "quizComplete") XCTAssertEqual(surveyStep.title, "Great Job!") XCTAssertEqual(surveyStep.text, "You answered correctly") XCTAssertEqual(surveyStep.detailText, "Tap the button below to begin the consent process") } func testFactory_BooleanQuestion() { let inputStep: NSDictionary = [ "identifier" : "question1", "type" : "boolean", "prompt" : "Are you older than 18?", "expectedAnswer" : true ] let step = SBASurveyFactory().createSurveyStepWithDictionary(inputStep) XCTAssertEqual(step.identifier, "question1") guard let surveyStep = step as? ORKFormStep else { XCTAssert(false, "\(step) is not of expected class type") return } XCTAssertEqual(surveyStep.formItems?.count, 1) guard let formItem = surveyStep.formItems?.first as? SBASurveyFormItem, let _ = formItem.answerFormat as? ORKBooleanAnswerFormat else { XCTAssert(false, "\(surveyStep.formItems) is not of expected class type") return } XCTAssertNil(formItem.text) XCTAssertEqual(step.text, "Are you older than 18?") XCTAssertNotNil(formItem.rulePredicate) guard let navigationRule = formItem.rulePredicate else { return } let questionResult = ORKBooleanQuestionResult(identifier:formItem.identifier) questionResult.booleanAnswer = true XCTAssertTrue(navigationRule.evaluateWithObject(questionResult)) questionResult.booleanAnswer = false XCTAssertFalse(navigationRule.evaluateWithObject(questionResult)) } func testFactory_SingleChoiceQuestion() { let inputStep: NSDictionary = [ "identifier" : "question1", "type" : "singleChoiceText", "prompt" : "Question 1?", "items" : ["a", "b", "c"], "expectedAnswer" : "b" ] let step = SBASurveyFactory().createSurveyStepWithDictionary(inputStep) XCTAssertEqual(step.identifier, "question1") guard let surveyStep = step as? ORKFormStep else { XCTAssert(false, "\(step) is not of expected class type") return } XCTAssertEqual(surveyStep.formItems?.count, 1) guard let formItem = surveyStep.formItems?.first as? SBASurveyFormItem, let answerFormat = formItem.answerFormat as? ORKTextChoiceAnswerFormat else { XCTAssert(false, "\(surveyStep.formItems) is not of expected class type") return } XCTAssertNil(formItem.text) XCTAssertEqual(step.text, "Question 1?") XCTAssertNotNil(formItem.rulePredicate) XCTAssertEqual(answerFormat.style, ORKChoiceAnswerStyle.SingleChoice) XCTAssertEqual(answerFormat.textChoices.count, 3) XCTAssertEqual(answerFormat.textChoices.first!.text, "a") let firstValue = answerFormat.textChoices.first!.value as? String XCTAssertEqual(firstValue, "a") guard let navigationRule = formItem.rulePredicate else { return } let questionResult = ORKChoiceQuestionResult(identifier:formItem.identifier) questionResult.choiceAnswers = ["b"] XCTAssertTrue(navigationRule.evaluateWithObject(questionResult)) questionResult.choiceAnswers = ["c"] XCTAssertFalse(navigationRule.evaluateWithObject(questionResult)) } func testFactory_MultipleChoiceQuestion() { let inputStep: NSDictionary = [ "identifier" : "question1", "type" : "multipleChoiceText", "prompt" : "Question 1?", "items" : [ ["prompt" : "a", "value" : 0], ["prompt" : "b", "value" : 1, "detailText": "good"], ["prompt" : "c", "value" : 2, "exclusive": true]], ] let step = SBASurveyFactory().createSurveyStepWithDictionary(inputStep) XCTAssertEqual(step.identifier, "question1") guard let surveyStep = step as? ORKFormStep else { XCTAssert(false, "\(step) is not of expected class type") return } XCTAssertEqual(surveyStep.formItems?.count, 1) guard let formItem = surveyStep.formItems?.first, let answerFormat = formItem.answerFormat as? ORKTextChoiceAnswerFormat else { XCTAssert(false, "\(surveyStep.formItems) is not of expected class type") return } XCTAssertNil(formItem.text) XCTAssertEqual(step.text, "Question 1?") XCTAssertEqual(answerFormat.style, ORKChoiceAnswerStyle.MultipleChoice) XCTAssertEqual(answerFormat.textChoices.count, 3) let choiceA = answerFormat.textChoices[0] XCTAssertEqual(choiceA.text, "a") XCTAssertEqual(choiceA.value as? Int, 0) XCTAssertFalse(choiceA.exclusive) let choiceB = answerFormat.textChoices[1] XCTAssertEqual(choiceB.text, "b") XCTAssertEqual(choiceB.value as? Int, 1) XCTAssertEqual(choiceB.detailText, "good") XCTAssertFalse(choiceB.exclusive) let choiceC = answerFormat.textChoices[2] XCTAssertEqual(choiceC.text, "c") XCTAssertEqual(choiceC.value as? Int, 2) XCTAssertTrue(choiceC.exclusive) } func testFactory_TextChoice() { let inputStep: NSDictionary = [ "identifier": "purpose", "title": "What is the purpose of this study?", "type": "singleChoiceText", "items":[ ["text" :"Understand the fluctuations of Parkinson disease symptoms", "value" : true], ["text" :"Treating Parkinson disease", "value": false], ], "expectedAnswer": true, ] let step = SBASurveyFactory().createSurveyStepWithDictionary(inputStep) XCTAssertEqual(step.identifier, "purpose") guard let surveyStep = step as? ORKFormStep else { XCTAssert(false, "\(step) is not of expected class type") return } XCTAssertEqual(surveyStep.formItems?.count, 1) guard let formItem = surveyStep.formItems?.first as? SBASurveyFormItem, let answerFormat = formItem.answerFormat as? ORKTextChoiceAnswerFormat else { XCTAssert(false, "\(surveyStep.formItems) is not of expected class type") return } XCTAssertNil(formItem.text) XCTAssertEqual(answerFormat.style, ORKChoiceAnswerStyle.SingleChoice) XCTAssertEqual(answerFormat.textChoices.count, 2) if (answerFormat.textChoices.count != 2) { return } XCTAssertEqual(answerFormat.textChoices.first!.text, "Understand the fluctuations of Parkinson disease symptoms") let firstValue = answerFormat.textChoices.first!.value as? Bool XCTAssertEqual(firstValue, true) XCTAssertEqual(answerFormat.textChoices.last!.text, "Treating Parkinson disease") let lastValue = answerFormat.textChoices.last!.value as? Bool XCTAssertEqual(lastValue, false) XCTAssertNotNil(formItem.rulePredicate) guard let navigationRule = formItem.rulePredicate else { return } let questionResult = ORKChoiceQuestionResult(identifier:formItem.identifier) questionResult.choiceAnswers = [true] XCTAssertTrue(navigationRule.evaluateWithObject(questionResult)) questionResult.choiceAnswers = [false] XCTAssertFalse(navigationRule.evaluateWithObject(questionResult)) } }
bsd-3-clause
53ce981804ca1ead395163e718ecfe34
38.772616
121
0.596545
5.182224
false
false
false
false
ben-ng/swift
test/ClangImporter/objc_bridging_custom.swift
1
18233
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -I %S/../Inputs/ObjCBridging %S/../Inputs/ObjCBridging/Appliances.swift -module-name Appliances -o %t // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -I %S/../Inputs/ObjCBridging -I %t -parse-as-library -verify %s // REQUIRES: objc_interop import Appliances import Foundation func checkThatBridgingIsWorking(fridge: Refrigerator) { let bridgedFridge = fridge as APPRefrigerator // no-warning _ = bridgedFridge as Refrigerator // no-warning } class Base : NSObject { func test(a: Refrigerator, b: Refrigerator) -> Refrigerator? { // expected-note {{potential overridden instance method 'test(a:b:)' here}} return nil } func testGeneric(a: ManufacturerInfo<NSString>, b: ManufacturerInfo<NSString>) -> ManufacturerInfo<NSString>? { // expected-note {{potential overridden instance method 'testGeneric(a:b:)' here}} {{none}} return nil } class func testInout(_: inout Refrigerator) {} // expected-note {{potential overridden class method 'testInout' here}} func testUnmigrated(a: NSRuncingMode, b: Refrigerator, c: NSCoding) {} // expected-note {{potential overridden instance method 'testUnmigrated(a:b:c:)' here}} func testPartialMigrated(a: NSRuncingMode, b: Refrigerator) {} // expected-note {{potential overridden instance method 'testPartialMigrated(a:b:)' here}} func testAny(a: Any, b: Any) -> Any? {} // expected-note {{potential overridden instance method 'testAny(a:b:)' here}} subscript(a a: Refrigerator, b b: Refrigerator) -> Refrigerator? { // expected-note {{potential overridden subscript 'subscript(a:b:)' here}} {{none}} return nil } subscript(generic a: ManufacturerInfo<NSString>, b b: ManufacturerInfo<NSString>) -> ManufacturerInfo<NSString>? { // expected-note {{potential overridden subscript 'subscript(generic:b:)' here}} {{none}} return nil } init?(a: Refrigerator, b: Refrigerator) {} // expected-note {{potential overridden initializer 'init(a:b:)' here}} {{none}} init?(generic: ManufacturerInfo<NSString>, b: ManufacturerInfo<NSString>) {} // expected-note {{potential overridden initializer 'init(generic:b:)' here}} {{none}} init(singleArgument: Refrigerator) {} // expected-note {{potential overridden initializer 'init(singleArgument:)' here}} {{none}} // FIXME: expected-note@+1 {{getter for 'prop' declared here}} var prop: Refrigerator // expected-note {{attempt to override property here}} // FIXME: expected-note@+1 {{getter for 'propGeneric' declared here}} var propGeneric: ManufacturerInfo<NSString> // expected-note {{attempt to override property here}} } class Sub : Base { // expected-note@+1 {{type does not match superclass instance method with type '(Refrigerator, Refrigerator) -> Refrigerator?'}} {{25-40=Refrigerator}} {{45-61=Refrigerator?}} {{66-81=Refrigerator}} override func test(a: APPRefrigerator, b: APPRefrigerator?) -> APPRefrigerator { // expected-error {{method does not override any method from its superclass}} {{none}} return a } // expected-note@+1 {{type does not match superclass instance method with type '(ManufacturerInfo<NSString>, ManufacturerInfo<NSString>) -> ManufacturerInfo<NSString>?'}} {{32-62=ManufacturerInfo<NSString>}} {{67-98=ManufacturerInfo<NSString>?}} {{103-133=ManufacturerInfo<NSString>}} override func testGeneric(a: APPManufacturerInfo<AnyObject>, b: APPManufacturerInfo<AnyObject>?) -> APPManufacturerInfo<AnyObject> { // expected-error {{method does not override any method from its superclass}} {{none}} return a } // expected-note@+1 {{type does not match superclass class method with type '(inout Refrigerator) -> ()'}} {{36-57=inout Refrigerator}} override class func testInout(_: inout APPRefrigerator) {} // expected-error {{method does not override any method from its superclass}} {{none}} override func testUnmigrated(a: NSObject, b: NSObject, c: NSObject) {} // expected-error {{method does not override any method from its superclass}} {{none}} // expected-note@+1 {{type does not match superclass instance method with type '(NSRuncingMode, Refrigerator) -> ()'}} {{53-68=Refrigerator}} override func testPartialMigrated(a: NSObject, b: APPRefrigerator) {} // expected-error {{method does not override any method from its superclass}} {{none}} // expected-note@+1 {{type does not match superclass instance method with type '(Any, Any) -> Any?'}} {{28-37=Any}} {{42-52=Any?}} {{57-66=Any}} override func testAny(a: AnyObject, b: AnyObject?) -> AnyObject {} // expected-error {{method does not override any method from its superclass}} // expected-note@+1 {{type does not match superclass subscript with type '(Refrigerator, Refrigerator) -> Refrigerator?'}} {{27-42=Refrigerator}} {{49-65=Refrigerator?}} {{70-85=Refrigerator}} override subscript(a a: APPRefrigerator, b b: APPRefrigerator?) -> APPRefrigerator { // expected-error {{subscript does not override any subscript from its superclass}} {{none}} return a } // expected-note@+1 {{type does not match superclass subscript with type '(ManufacturerInfo<NSString>, ManufacturerInfo<NSString>) -> ManufacturerInfo<NSString>?'}} {{33-63=ManufacturerInfo<NSString>}} {{70-101=ManufacturerInfo<NSString>?}} {{106-136=ManufacturerInfo<NSString>}} override subscript(generic a: APPManufacturerInfo<AnyObject>, b b: APPManufacturerInfo<AnyObject>?) -> APPManufacturerInfo<AnyObject> { // expected-error {{subscript does not override any subscript from its superclass}} {{none}} return a } // expected-note@+1 {{type does not match superclass initializer with arguments '(a: Refrigerator, b: Refrigerator)'}} {{20-35=Refrigerator}} {{40-56=Refrigerator?}} override init(a: APPRefrigerator, b: APPRefrigerator?) {} // expected-error {{initializer does not override a designated initializer from its superclass}} // expected-note@+1 {{type does not match superclass initializer with arguments '(generic: ManufacturerInfo<NSString>, b: ManufacturerInfo<NSString>)'}} {{28-58=ManufacturerInfo<NSString>}} {{63-94=ManufacturerInfo<NSString>?}} override init(generic a: APPManufacturerInfo<AnyObject>, b: APPManufacturerInfo<AnyObject>?) {} // expected-error {{initializer does not override a designated initializer from its superclass}} // expected-note@+1 {{type does not match superclass initializer with argument '(singleArgument: Refrigerator)'}} {{33-48=Refrigerator}} override init(singleArgument: APPRefrigerator) {} // expected-error {{initializer does not override a designated initializer from its superclass}} // FIXME: expected-error@+2 {{getter for 'prop' with Objective-C selector 'prop' conflicts with getter for 'prop' from superclass 'Base' with the same Objective-C selector}} // expected-note@+1 {{type does not match superclass var with type 'Refrigerator'}} {{22-37=Refrigerator}} override var prop: APPRefrigerator { // expected-error {{property 'prop' with type 'APPRefrigerator' cannot override a property with type 'Refrigerator'}} return super.prop as APPRefrigerator } // FIXME: expected-error@+2 {{getter for 'propGeneric' with Objective-C selector 'propGeneric' conflicts with getter for 'propGeneric' from superclass 'Base' with the same Objective-C selector}} // expected-note@+1 {{type does not match superclass var with type 'ManufacturerInfo<NSString>'}} {{29-59=ManufacturerInfo<NSString>}} override var propGeneric: APPManufacturerInfo<AnyObject> { // expected-error {{property 'propGeneric' with type 'APPManufacturerInfo<AnyObject>' cannot override a property with type 'ManufacturerInfo<NSString>'}} return super.prop // expected-error {{return type}} } } protocol TestProto { func test(a: Refrigerator, b: Refrigerator) -> Refrigerator? // expected-note {{protocol requires}} func testGeneric(a: ManufacturerInfo<NSString>, b: ManufacturerInfo<NSString>) -> ManufacturerInfo<NSString>? // expected-note {{protocol requires}} static func testInout(_: inout Refrigerator) // expected-note {{protocol requires}} func testUnmigrated(a: NSRuncingMode, b: Refrigerator, c: NSCoding) // expected-note {{protocol requires}} func testPartialMigrated(a: NSRuncingMode, b: Refrigerator) // expected-note {{protocol requires}} subscript(a a: Refrigerator, b b: Refrigerator) -> Refrigerator? { get } // expected-note {{protocol requires}} subscript(generic a: ManufacturerInfo<NSString>, b b: ManufacturerInfo<NSString>) -> ManufacturerInfo<NSString>? { get } // expected-note {{protocol requires}} init?(a: Refrigerator, b: Refrigerator) // expected-note {{protocol requires}} init?(generic: ManufacturerInfo<NSString>, b: ManufacturerInfo<NSString>) // expected-note {{protocol requires}} init(singleArgument: Refrigerator) // expected-note {{protocol requires}} var prop: Refrigerator? { get } // expected-note {{protocol requires}} var propGeneric: ManufacturerInfo<NSString>? { get } // expected-note {{protocol requires}} } class TestProtoImpl : NSObject, TestProto { // expected-error {{type 'TestProtoImpl' does not conform to protocol 'TestProto'}} // expected-note@+1 {{candidate has non-matching type '(APPRefrigerator, APPRefrigerator?) -> APPRefrigerator'}} {{16-31=Refrigerator}} {{36-52=Refrigerator?}} {{57-72=Refrigerator}} func test(a: APPRefrigerator, b: APPRefrigerator?) -> APPRefrigerator { return a } // expected-note@+1 {{candidate has non-matching type '(APPManufacturerInfo<AnyObject>, APPManufacturerInfo<AnyObject>?) -> APPManufacturerInfo<AnyObject>'}} {{23-53=ManufacturerInfo<NSString>}} {{58-89=ManufacturerInfo<NSString>?}} {{94-124=ManufacturerInfo<NSString>}} func testGeneric(a: APPManufacturerInfo<AnyObject>, b: APPManufacturerInfo<AnyObject>?) -> APPManufacturerInfo<AnyObject> { return a } // expected-note@+1 {{candidate has non-matching type '(inout APPRefrigerator) -> ()'}} {{27-48=inout Refrigerator}} class func testInout(_: inout APPRefrigerator) {} // expected-note@+1 {{candidate has non-matching type '(NSObject, NSObject, NSObject) -> ()'}} func testUnmigrated(a: NSObject, b: NSObject, c: NSObject) {} // expected-note@+1 {{candidate has non-matching type '(NSObject, APPRefrigerator) -> ()'}} {{44-59=Refrigerator}} func testPartialMigrated(a: NSObject, b: APPRefrigerator) {} // expected-note@+1 {{candidate has non-matching type '(APPRefrigerator, APPRefrigerator?) -> APPRefrigerator'}} {{18-33=Refrigerator}} {{40-56=Refrigerator?}} {{61-76=Refrigerator}} subscript(a a: APPRefrigerator, b b: APPRefrigerator?) -> APPRefrigerator { return a } // expected-note@+1 {{candidate has non-matching type '(APPManufacturerInfo<AnyObject>, APPManufacturerInfo<AnyObject>?) -> APPManufacturerInfo<AnyObject>'}} {{24-54=ManufacturerInfo<NSString>}} {{61-92=ManufacturerInfo<NSString>?}} {{97-127=ManufacturerInfo<NSString>}} subscript(generic a: APPManufacturerInfo<AnyObject>, b b: APPManufacturerInfo<AnyObject>?) -> APPManufacturerInfo<AnyObject> { return a } // expected-note@+1 {{candidate has non-matching type '(a: APPRefrigerator, b: APPRefrigerator?)'}} {{11-26=Refrigerator}} {{31-47=Refrigerator?}} init(a: APPRefrigerator, b: APPRefrigerator?) {} // expected-note@+1 {{candidate has non-matching type '(generic: APPManufacturerInfo<AnyObject>, b: APPManufacturerInfo<AnyObject>?)'}} {{19-49=ManufacturerInfo<NSString>}} {{54-85=ManufacturerInfo<NSString>?}} init(generic a: APPManufacturerInfo<AnyObject>, b: APPManufacturerInfo<AnyObject>?) {} // expected-note@+1 {{candidate has non-matching type '(singleArgument: APPRefrigerator)'}} {{24-39=Refrigerator}} init(singleArgument: APPRefrigerator) {} // expected-note@+1 {{candidate has non-matching type 'APPRefrigerator?'}} {{13-29=Refrigerator?}} {{none}} var prop: APPRefrigerator? { return nil } // expected-note@+1 {{candidate has non-matching type 'APPManufacturerInfo<AnyObject>?'}} {{20-51=ManufacturerInfo<NSString>?}} var propGeneric: APPManufacturerInfo<AnyObject>? { return nil } } @objc protocol TestObjCProto { @objc optional func test(a: Refrigerator, b: Refrigerator) -> Refrigerator? // expected-note {{here}} {{none}} @objc optional func testGeneric(a: ManufacturerInfo<NSString>, b: ManufacturerInfo<NSString>) -> ManufacturerInfo<NSString>? // expected-note {{here}} {{none}} @objc optional func testUnmigrated(a: NSRuncingMode, b: Refrigerator, c: NSCoding) // expected-note {{here}} {{none}} @objc optional func testPartialMigrated(a: NSRuncingMode, b: Refrigerator) // expected-note {{here}} {{none}} @objc optional subscript(a a: Refrigerator) -> Refrigerator? { get } // expected-note {{here}} {{none}} @objc optional subscript(generic a: ManufacturerInfo<NSString>) -> ManufacturerInfo<NSString>? { get } // expected-note {{here}} {{none}} @objc optional var prop: Refrigerator? { get } // expected-note {{here}} {{none}} @objc optional var propGeneric: ManufacturerInfo<NSString>? { get } // expected-note {{here}} {{none}} } class TestObjCProtoImpl : NSObject, TestObjCProto { // expected-note@+2 {{private}} expected-note@+2 {{@nonobjc}} expected-note@+2 {{extension}} // expected-note@+1 {{candidate has non-matching type '(APPRefrigerator, APPRefrigerator?) -> APPRefrigerator'}} {{16-31=Refrigerator}} {{36-52=Refrigerator?}} {{57-72=Refrigerator}} func test(a: APPRefrigerator, b: APPRefrigerator?) -> APPRefrigerator { // expected-warning {{instance method 'test(a:b:)' nearly matches optional requirement 'test(a:b:)' of protocol 'TestObjCProto'}} return a } // expected-note@+2 {{private}} expected-note@+2 {{@nonobjc}} expected-note@+2 {{extension}} // expected-note@+1 {{candidate has non-matching type '(APPManufacturerInfo<AnyObject>, APPManufacturerInfo<AnyObject>?) -> APPManufacturerInfo<AnyObject>'}} {{23-53=ManufacturerInfo<NSString>}} {{58-89=ManufacturerInfo<NSString>?}} {{94-124=ManufacturerInfo<NSString>}} func testGeneric(a: APPManufacturerInfo<AnyObject>, b: APPManufacturerInfo<AnyObject>?) -> APPManufacturerInfo<AnyObject> { // expected-warning {{instance method 'testGeneric(a:b:)' nearly matches optional requirement 'testGeneric(a:b:)' of protocol 'TestObjCProto'}} {{none}} return a } // expected-note@+2 {{private}} expected-note@+2 {{@nonobjc}} expected-note@+2 {{extension}} // expected-note@+1 {{candidate has non-matching type '(NSObject, NSObject, NSObject) -> ()'}} {{none}} func testUnmigrated(a: NSObject, b: NSObject, c: NSObject) {} // expected-warning {{instance method 'testUnmigrated(a:b:c:)' nearly matches optional requirement 'testUnmigrated(a:b:c:)' of protocol 'TestObjCProto'}} // expected-note@+2 {{private}} expected-note@+2 {{@nonobjc}} expected-note@+2 {{extension}} // expected-note@+1 {{candidate has non-matching type '(NSObject, APPRefrigerator) -> ()'}} {{44-59=Refrigerator}} func testPartialMigrated(a: NSObject, b: APPRefrigerator) {} // expected-warning {{instance method 'testPartialMigrated(a:b:)' nearly matches optional requirement 'testPartialMigrated(a:b:)' of protocol 'TestObjCProto'}} {{none}} // expected-note@+2 {{private}} expected-note@+2 {{@nonobjc}} expected-note@+2 {{extension}} // expected-note@+1 {{candidate has non-matching type '(APPRefrigerator?) -> APPRefrigerator'}} {{18-34=Refrigerator?}} {{39-54=Refrigerator}} subscript(a a: APPRefrigerator?) -> APPRefrigerator { // expected-warning {{subscript 'subscript(a:)' nearly matches optional requirement 'subscript(a:)' of protocol 'TestObjCProto'}} {{none}} // expected-note@-1 {{here}} return a! } // expected-note@+2 {{private}} expected-note@+2 {{@nonobjc}} expected-note@+2 {{extension}} // expected-note@+1 {{candidate has non-matching type '(APPManufacturerInfo<AnyObject>?) -> APPManufacturerInfo<AnyObject>'}} {{24-55=ManufacturerInfo<NSString>?}} {{60-90=ManufacturerInfo<NSString>}} subscript(generic a: APPManufacturerInfo<AnyObject>?) -> APPManufacturerInfo<AnyObject> { // expected-warning {{subscript 'subscript(generic:)' nearly matches optional requirement 'subscript(generic:)' of protocol 'TestObjCProto'}} {{none}} // expected-error@-1 {{subscript getter with Objective-C selector 'objectForKeyedSubscript:' conflicts with previous declaration with the same Objective-C selector}} return a! } // expected-note@+2 {{private}} expected-note@+2 {{@nonobjc}} expected-note@+2 {{extension}} // expected-note@+1 {{candidate has non-matching type 'APPRefrigerator?'}} {{13-29=Refrigerator?}} var prop: APPRefrigerator? { // expected-warning {{var 'prop' nearly matches optional requirement 'prop' of protocol 'TestObjCProto'}} {{none}} return nil } // expected-note@+2 {{private}} expected-note@+2 {{@nonobjc}} expected-note@+2 {{extension}} // expected-note@+1 {{candidate has non-matching type 'APPManufacturerInfo<AnyObject>?'}} {{20-51=ManufacturerInfo<NSString>?}} var propGeneric: APPManufacturerInfo<AnyObject>? { // expected-warning {{var 'propGeneric' nearly matches optional requirement 'propGeneric' of protocol 'TestObjCProto'}} {{none}} return nil } } // Check explicit conversions for bridged generic types. // rdar://problem/27539951 func testExplicitConversion(objc: APPManufacturerInfo<NSString>, swift: ManufacturerInfo<NSString>) { // Bridging to Swift let _ = objc as ManufacturerInfo<NSString> let _ = objc as ManufacturerInfo<NSNumber> // expected-error{{cannot convert value of type 'APPManufacturerInfo<NSString>' to type 'ManufacturerInfo<NSNumber>' in coercion}} let _ = objc as ManufacturerInfo<NSObject> // expected-error{{cannot convert value of type 'APPManufacturerInfo<NSString>' to type 'ManufacturerInfo<NSObject>' in coercion}} // Bridging to Objective-C let _ = swift as APPManufacturerInfo<NSString> let _ = swift as APPManufacturerInfo<NSNumber> // expected-error{{cannot convert value of type 'ManufacturerInfo<NSString>' to type 'APPManufacturerInfo<NSNumber>' in coercion}} let _ = swift as APPManufacturerInfo<NSObject> // expected-error{{cannot convert value of type 'ManufacturerInfo<NSString>' to type 'APPManufacturerInfo<NSObject>' in coercion}} }
apache-2.0
8e5b17ec5dfd63043e4fb298b46fc4bd
78.969298
286
0.729666
4.527688
false
true
false
false
cruinh/CuriosityPhotos
CuriosityRover/PhotoCollectionViewController.swift
1
4178
// // PhotoCollectionViewController.swift // CuriosityRover // // Created by Matt Hayes on 3/4/16. // // import UIKit 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 } } fileprivate func > <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class PhotoCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var collectionView: UICollectionView! var refreshControl: UIRefreshControl? var parsedServiceData: CuriosityRoverData? override func viewDidLoad() { super.viewDidLoad() refreshControl = UIRefreshControl() refreshControl!.tintColor = self.spinner.color refreshControl!.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl!.addTarget(self, action: #selector(PhotoCollectionViewController.refresh), for: UIControlEvents.valueChanged) collectionView!.addSubview(refreshControl!) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setNeedsStatusBarAppearanceUpdate() } func refresh() { parsedServiceData = nil collectionView.reloadData() spinner.startAnimating() CuriosityRoverDataService().getData() { [weak self] (JSON, error) -> Void in guard error == nil else { print ("PhotoCollectionViewController.viewDidLoad: \(error)") ; return } guard self != nil else { print("PhotoCollectionViewController.viewDidLoad : self was nil on return") ; return } print("[--PARSING JSON--]...") self!.parsedServiceData = CuriosityRoverData(JSON: JSON) DispatchQueue.main.async(execute: { () -> Void in print("[--RELOADING COLLECTION VIEW--]...") self!.collectionView.reloadData() print("[--STOPPING SPINNER--]...") self!.spinner.stopAnimating() self!.refreshControl?.endRefreshing() }) } } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let parsedServiceData = parsedServiceData else { return 0 } if parsedServiceData.photos.count > 0 { return parsedServiceData.photos.count } else { return 1 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard parsedServiceData?.photos.count > 0 else { return collectionView.dequeueReusableCell(withReuseIdentifier: "NoResultsCell", for: indexPath) } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CuriosityPhotoCell", for: indexPath) as! CuriosityPhotoCell if let photoInfo = parsedServiceData?.photos[(indexPath as NSIndexPath).row], let img_src = photoInfo.img_src { cell.photoInfo = photoInfo cell.populate(withImage: img_src) } else { cell.photoInfo = nil cell.imageView.image = nil cell.spinner.stopAnimating() print("error: no url for cell image at row \((indexPath as NSIndexPath).row)") } return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let senderCell = sender as? CuriosityPhotoCell, let destinationController = segue.destination as? UINavigationController, let destinationPhotoController = destinationController.topViewController as? PhotoViewController { destinationPhotoController.photoInfo = senderCell.photoInfo } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
mit
a3a03aff3517382d0c4b290a629e7bd9
32.15873
135
0.64696
5.1644
false
false
false
false
exponent/exponent
ios/versioned/sdk44/ExpoModulesCore/Swift/Records/Field.swift
2
3182
/** Property wrapper for `Record`'s data members that takes part in the process of serialization to and deserialization from the dictionary. */ @propertyWrapper public final class Field<Type>: AnyFieldInternal { /** The wrapped value. */ public var wrappedValue: Type /** Field's key in the dictionary, which by default is a label of the wrapped property. Sadly, property wrappers don't receive properties' label, so we must wait until it's assigned by `Record`. */ internal var key: String? { return options.first { $0.rawValue == FieldOption.keyed("").rawValue }?.key } /** Additional options of the field, such is if providing the value is required (`FieldOption.required`). */ internal var options: Set<FieldOption> = Set() /** Whether the generic field type accepts `nil` values. We can't check it directly with `Optional` because it has associated type, but all optionals implement non-generic `ExpressibleByNilLiteral` protocol. */ internal var isOptional: Bool { return Type.self is ExpressibleByNilLiteral.Type } /** Initializes the field with given value and customized key. */ public init(wrappedValue: Type, _ options: FieldOption...) { self.wrappedValue = wrappedValue self.options = Set(options) } /** Alternative default initializer implementation. It's not possible yet to pass an array as variadic arguments, so we also need to pass an array as a single argument. */ public init(wrappedValue: Type, _ options: [FieldOption]) { self.wrappedValue = wrappedValue self.options = Set(options) } /** A hacky way to accept optionals without explicit assignment to `nil`. Normally, we would have to do `@Field var s: String? = nil` but this init with generic constraint allows us to just do `@Field var s: String?`. */ public init(wrappedValue: Type = nil) where Type: ExpressibleByNilLiteral { self.wrappedValue = wrappedValue } public init(wrappedValue: Type = nil, _ options: FieldOption...) where Type: ExpressibleByNilLiteral { self.wrappedValue = wrappedValue self.options = Set(options) } /** Returns wrapped value as `Any?` to conform to type-erased `AnyField` protocol. */ public func get() -> Any { return wrappedValue } /** Sets the wrapped value with a value of `Any` type. */ internal func set(_ newValue: Any?) throws { if newValue == nil && (!isOptional || options.contains(.required)) { throw FieldRequiredError(fieldKey: key!) } if let value = newValue as? Type { wrappedValue = value return } throw FieldInvalidTypeError(fieldKey: key!, value: newValue, desiredType: Type.self) } } internal struct FieldRequiredError: CodedError { let fieldKey: String var description: String { "Value for field `\(fieldKey)` is required, got `nil`" } } internal struct FieldInvalidTypeError: CodedError { let fieldKey: String let value: Any? let desiredType: Any.Type var description: String { "Cannot cast value `\(String(describing: value!))` (\(type(of: value!))) for field `\(fieldKey)` (\(String(describing: desiredType)))" } }
bsd-3-clause
fbf007915a65394d9bd6d17044753fd6
31.141414
138
0.694217
4.38292
false
false
false
false
SteveBarnegren/TweenKit
TweenKit/TweenKit/Easing.swift
1
5193
// // Easing.swift // TweenKit // // Created by Steve Barnegren on 17/03/2017. // Copyright © 2017 Steve Barnegren. All rights reserved. // import Foundation let kPERIOD: Double = 0.3 let M_PI_X_2: Double = Double.pi * 2.0 /** The easing (timing function) that an animation should use */ public enum Easing: Int { // Linear case linear // Sine case sineIn case sineOut case sineInOut // Exponential case exponentialIn case exponentialOut case exponentialInOut // Back case backIn case backOut case backInOut // Bounce case bounceIn case bounceOut case bounceInOut // Elastic case elasticIn case elasticOut case elasticInOut public func apply(t: Double) -> Double { switch self { // **** Linear **** case .linear: return t // **** Sine **** case .sineIn: return -1.0 * cos(t * (Double.pi/2)) + 1.0 case .sineOut: return sin(t * (Double.pi/2)) case .sineInOut: return -0.5 * (cos(Double.pi*t) - 1.0) // **** Exponential **** case .exponentialIn: return (t==0.0) ? 0.0 : pow(2.0, 10.0 * (t/1.0 - 1.0)) - 1.0 * 0.001; case .exponentialOut: return (t==1.0) ? 1.0 : (-pow(2.0, -10.0 * t/1.0) + 1.0); case .exponentialInOut: var t = t t /= 0.5; if (t < 1.0) { t = 0.5 * pow(2.0, 10.0 * (t - 1.0)) } else { t = 0.5 * (-pow(2.0, -10.0 * (t - 1.0) ) + 2.0); } return t; // **** Back **** case .backIn: let overshoot = 1.70158 return t * t * ((overshoot + 1.0) * t - overshoot); case .backOut: let overshoot = 1.70158 var t = t t = t - 1.0; return t * t * ((overshoot + 1.0) * t + overshoot) + 1.0; case .backInOut: let overshoot = 1.70158 * 1.525 var t = t t = t * 2.0; if (t < 1.0) { return (t * t * ((overshoot + 1.0) * t - overshoot)) / 2.0; } else { t = t - 2.0; return (t * t * ((overshoot + 1.0) * t + overshoot)) / 2.0 + 1.0; } // **** Bounce **** case .bounceIn: var newT = t if(t != 0.0 && t != 1.0) { newT = 1.0 - bounceTime(t: 1.0 - t) } return newT; case .bounceOut: var newT = t; if(t != 0.0 && t != 1.0) { newT = bounceTime(t: t) } return newT; case .bounceInOut: let newT: Double if( t == 0.0 || t == 1.0) { newT = t; } else if (t < 0.5) { var t = t t = t * 2.0; newT = (1.0 - bounceTime(t: 1.0-t) ) * 0.5 } else { newT = bounceTime(t: t * 2.0 - 1.0) * 0.5 + 0.5 } return newT; // **** Elastic **** case .elasticIn: var newT = 0.0 if (t == 0.0 || t == 1.0) { newT = t } else { var t = t let s = kPERIOD / 4.0; t = t - 1; newT = -pow(2, 10 * t) * sin( (t-s) * M_PI_X_2 / kPERIOD); } return newT; case .elasticOut: var newT = 0.0 if (t == 0.0 || t == 1.0) { newT = t } else { let s = kPERIOD / 4; newT = pow(2.0, -10.0 * t) * sin( (t-s) * M_PI_X_2 / kPERIOD) + 1 } return newT case .elasticInOut: var newT = 0.0; if( t == 0.0 || t == 1.0 ) { newT = t; } else { var t = t t = t * 2.0; let s = kPERIOD / 4; t = t - 1.0; if( t < 0 ) { newT = -0.5 * pow(2, 10.0 * t) * sin((t - s) * M_PI_X_2 / kPERIOD); } else{ newT = pow(2, -10.0 * t) * sin((t - s) * M_PI_X_2 / kPERIOD) * 0.5 + 1.0; } } return newT; } } // Helpers func bounceTime(t: Double) -> Double { var t = t if (t < 1.0 / 2.75) { return 7.5625 * t * t } else if (t < 2.0 / 2.75) { t -= 1.5 / 2.75 return 7.5625 * t * t + 0.75 } else if (t < 2.5 / 2.75) { t -= 2.25 / 2.75 return 7.5625 * t * t + 0.9375 } t -= 2.625 / 2.75 return 7.5625 * t * t + 0.984375 } }
mit
ba6e3178f5f7b122f706de2e56cf269f
24.326829
93
0.347843
3.539196
false
false
false
false
inquisitiveSoft/UIView-ConstraintAdditions
Constraint Additions Test/ViewController.swift
1
1747
// // ViewController.swift // Constraint Additions Test // // Created by Harry Jordan on 20/07/2014. // Released under the MIT license: http://opensource.org/licenses/mit-license.php // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. view.backgroundColor = UIColor.whiteColor() let blueView = UIView(frame: CGRect(x: 40.0, y: 40.0, width: 100.0, height: 100.0)) blueView.setTranslatesAutoresizingMaskIntoConstraints(false) blueView.backgroundColor = UIColor(red: 0.3, green: 0.3, blue: 0.6, alpha: 1.0) view.addSubview(blueView) var constraints = blueView.fillView(view) if let leftConstraint = constraints[NSLayoutAttribute.Leading] { println(leftConstraint) leftConstraint.constant = 40.0 } let orangeView = UIView(frame: CGRect(x: 20.0, y: 20.0, width: 200.0, height: 200.0)) orangeView.setTranslatesAutoresizingMaskIntoConstraints(false) orangeView.backgroundColor = UIColor.orangeColor() blueView.addSubview(orangeView) constraints = blueView.addConstraints( views: ["orange" : orangeView], horizontalFormat: "|-[orange]-|", verticalFormat:"|-[orange]-|" ) let greenView = UIView(frame: CGRect(x: 20.0, y: 20.0, width: 200.0, height: 200.0)) greenView.setTranslatesAutoresizingMaskIntoConstraints(false) greenView.backgroundColor = UIColor.greenColor() blueView.addSubview(greenView) greenView.addConstraints(views: ["greenView" : greenView], horizontalFormat:"[greenView(100)]", verticalFormat:"[greenView(100)]") constraints = view.centerView(greenView, relativeToView: blueView, xAxis: true, yAxis: true) } }
mit
908fe72e1958c495f696668b23aaaf60
31.351852
132
0.729823
3.83114
false
false
false
false
Ceroce/SwiftRay
SwiftRay/SwiftRay/main.swift
1
4891
// // main.swift // SwiftRay // // Created by Renaud Pradenc on 22/11/2016. // Copyright © 2016 Céroce. All rights reserved. // import Foundation // Size of the generated image let Width = 400 let Height = 266 // The number of rounds of rendering. // Each round generates a Sample (= an image with float components), which is accumulated to the previous samples using a weighted average. The more samples, the less noisy is the final image. Of course, rendering time is linear with the number of samples. let Samples = 100 // Maximum number of scattered rays. // When a ray hits an object, a scattered ray is emitted in the direction symetric to the incoming ray, relative to the normal of the object at the point hit, and so on, until no object is hit (= the ray "falls" into the sky). This may potentially never end, so we set a maximum count of scattered rays. In practice, this does not have much impact neither on the rendering time nor the quality, so you should keep the defaut value. let DepthMax = 50 func backgroundColor(ray: Ray) -> Vec3 { let unitDir = normalize(ray.direction) let t = 0.5 * (unitDir.y + 1.0) let white = Vec3(1.0, 1.0, 1.0) let blue = Vec3(0.5, 0.7, 1.0) return mix(white, blue, t) } func color(ray: Ray, world: [Hitable], depth: Int) -> Vec3 { guard depth < DepthMax else { return backgroundColor(ray: ray) } guard let intersection = closestHit(ray: ray, hitables: world) else { return backgroundColor(ray: ray) } guard let (secondaryRay, attenuation) = intersection.material.scatteredRay(ray: ray, intersection: intersection) else { return backgroundColor(ray: ray) } return attenuation * color(ray: secondaryRay, world: world, depth: depth+1) } func toneMap(color: PixelRGB32) -> PixelRGBU8 { let gamma: Float = 2.0 let invGamma = 1.0/gamma return PixelRGBU8(r: powf(color.r, invGamma), g: powf(color.g, invGamma), b: powf(color.b, invGamma)) } // *** Main *** // Scenes are currently described using structs conforming to the Scene protocol. // Since this is Swift code, the inconvenient is that Scene must be added to the project and compiled. // We could define an other format (e.g. based on JSON), but then it would need be parsed, and we would not have Xcode's autocompletion to help us! let scene = BigAndSmallSpheresScene(aspectRatio: Float(Width)/Float(Height)) print("SwiftRay") // The final image is saved on the Desktop. This is OK on the Mac. let imagePath = "~/Desktop/Image.png" let url = URL(fileURLWithPath: NSString(string: imagePath).expandingTildeInPath) print("Generating image (\(Width) by \(Height)) at \(imagePath)") let startDate = Date() let bitmap = Bitmap(width: Width, height: Height) let accumulator = ImageAccumulator() // This save() function takes a sample, accumulates it to the previous samples, applies tone mapping then saves it as PNG. func save(image: Image) { let accumulatedImage = accumulator.accumulate(image: image) bitmap.generate { (x, y) -> PixelRGBU8 in return toneMap(color: accumulatedImage.pixelAt(x: x, y: y)) } if !bitmap.writePng(url: url) { print("Error saving image at \(imagePath).") } } func printProgress(sampleIndex: Int, sampleCount:Int) { let progress = (Float(sampleIndex+1)/Float(sampleCount))*100.0 print("Sample \(sampleIndex+1)/\(sampleCount) (\(progress) %)") } // To take best advantage of multiple cores, one sample ought to be rendered on each core. let raytracingQueue = OperationQueue() raytracingQueue.name = "com.ceroce.SwiftRay Raytracing" raytracingQueue.maxConcurrentOperationCount = 4 // Parallel queue. Set this to the number of cores of your Mac. let imageSavingQueue = OperationQueue() imageSavingQueue.name = "com.ceroce.SwiftRay Image Saving" imageSavingQueue.maxConcurrentOperationCount = 1 // Serial queue var samplesRendered = 0; for _ in 0..<Samples { raytracingQueue.addOperation { let image = Image(width: Width, height: Height) image.generate { (x, y) -> PixelRGB32 in let s = (Float(x)+random01()) / Float(Width) let t = 1.0 - (Float(y)+random01()) / Float(Height) let ray = scene.camera.ray(s: s, t: t) let col = color(ray: ray, world: scene.hitables, depth: 0) return PixelRGB32(r: col.x, g: col.y, b: col.z) } imageSavingQueue.addOperation { save(image: image) printProgress(sampleIndex: samplesRendered, sampleCount: Samples) samplesRendered += 1 } } } // Wait for all operations to finish while samplesRendered == 0 || (raytracingQueue.operationCount > 0) || (imageSavingQueue.operationCount > 0) { } let renderingDuration = Date().timeIntervalSince(startDate) print("Image rendered in \(renderingDuration) s.")
mit
bd882e07fc32a4844f8bedeaaee2890c
36.899225
431
0.691143
3.763664
false
false
false
false
bryx-inc/BRYXBanner
Tests/BRYXBannerTests/MockBanner.swift
1
1534
// // MockBanner.swift // BRYXBanner // // Created by Anthony Miller on 11/12/15. // import UIKit import BRYXBanner private let MockBannerShownNotificationName = NSNotification.Name("MockBannerShownNotification") /// This mock banner can be used in place of a `Banner` in unit tests in order to verify that it will be displayed. public class MockBanner: Banner { /// The view that the banner is shown in. Captured from the `view` parameter in the `show(view: duration:)` method var viewForBanner: UIView? override public func show(_ view: UIView? = MockBanner.topWindow(), duration: TimeInterval? = nil) { viewForBanner = view NotificationCenter.default.post(name: MockBannerShownNotificationName, object: self) } } /// `MockBannerVerifier` can be used to verify that a `MockBanner` was shown in unit tests. This object will recieve notifications when a `MockBanner` is shown and capture the shown banner. public class MockBannerVerifier: NSObject { /// The last banner that was shown var bannerShown: MockBanner? override init() { super.init() NotificationCenter.default.addObserver( self, selector: #selector(bannerShown(notification:)), name: MockBannerShownNotificationName, object: nil ) } deinit { NotificationCenter.default.removeObserver(self) } @objc func bannerShown(notification: NSNotification) { if let banner = notification.object as? MockBanner { bannerShown = banner } } }
mit
cce47b16bdb9ea64e6cf4c4272bc1e7e
27.407407
189
0.705997
4.345609
false
false
false
false
ahmetkgunay/AKGPushAnimator
Source/AKGInteractionAnimator.swift
1
2307
// // AKGInteractionAnimator.swift // AKGPushAnimatorDemo // // Created by AHMET KAZIM GUNAY on 30/04/2017. // Copyright © 2017 AHMET KAZIM GUNAY. All rights reserved. // import UIKit public class AKGInteractionAnimator: UIPercentDrivenInteractiveTransition { var navigationController: UINavigationController! var shouldCompleteTransition = false public var transitionInProgress = false public func attachToViewController(_ viewController: UIViewController) { navigationController = viewController.navigationController addGestureRecognizer(viewController.view) } fileprivate func addGestureRecognizer(_ view: UIView) { let panGesture = UIPanGestureRecognizer(target: self, action: #selector(AKGInteractionAnimator.handlePanGesture(_:))) panGesture.delegate = self view.addGestureRecognizer(panGesture) } @objc func handlePanGesture(_ gestureRecognizer: UIPanGestureRecognizer) { let viewTranslation = gestureRecognizer.translation(in: gestureRecognizer.view?.superview) let velocity : CGPoint = gestureRecognizer.velocity(in: gestureRecognizer.view) switch gestureRecognizer.state { case .began: transitionInProgress = true navigationController.popViewController(animated: true) case .changed: var const = CGFloat(viewTranslation.x / UIScreen.main.bounds.width * 1.0) const = min(1.0, max(0.0, const)) shouldCompleteTransition = const > 0.5 || velocity.x > UIScreen.main.bounds.width update(const) case .cancelled, .ended: transitionInProgress = false if !shouldCompleteTransition || gestureRecognizer.state == .cancelled { cancel() } else { finish() } default: print("Swift switch must be exhaustive, thus the default") } } } extension AKGInteractionAnimator : UIGestureRecognizerDelegate { private func gestureRecognizerShouldBegin(_ gestureRecognizer: UIPanGestureRecognizer) -> Bool { let velocity : CGPoint = gestureRecognizer.velocity(in: gestureRecognizer.view) return fabs(velocity.x) > fabs(velocity.y) && fabs(velocity.x) > 0; } }
mit
d03e0876731bb27de4504b047514d797
37.433333
125
0.679532
5.325635
false
false
false
false
ja-mes/experiments
Old/Random/To Do List/To Do List/FirstViewController.swift
1
1724
// // FirstViewController.swift // To Do List // // Created by James Brown on 11/26/15. // Copyright © 2015 James Brown. All rights reserved. // import UIKit var toDoList = [String]() class FirstViewController: UIViewController, UITableViewDelegate { @IBOutlet var toDoListTable: UITableView! override func viewDidLoad() { super.viewDidLoad() if NSUserDefaults.standardUserDefaults().objectForKey("toDoList") != nil { toDoList = NSUserDefaults.standardUserDefaults().objectForKey("toDoList") as! [String] } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return toDoList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") cell.textLabel?.text = toDoList[indexPath.row] return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { toDoList.removeAtIndex(indexPath.row) NSUserDefaults.standardUserDefaults().setObject(toDoList, forKey: "toDoList") toDoListTable.reloadData() } } override func viewDidAppear(animated: Bool) { toDoListTable.reloadData() } }
mit
234857ea7384aa79ed43d9c7280c6133
28.706897
148
0.662217
5.630719
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/YPImagePicker/Source/Filters/Video/YPVideoView.swift
2
4573
// // YPVideoView.swift // YPImagePicker // // Created by Nik Kov || nik-kov.com on 18.04.2018. // Copyright © 2018 Yummypets. All rights reserved. // import UIKit import Stevia import AVFoundation /// A video view that contains video layer, supports play, pause and other actions. /// Supports xib initialization. public class YPVideoView: UIView { public let playImageView = UIImageView(image: nil) internal let playerView = UIView() internal let playerLayer = AVPlayerLayer() internal var previewImageView = UIImageView() public var player: AVPlayer { guard playerLayer.player != nil else { return AVPlayer() } playImageView.image = YPConfig.icons.playImage return playerLayer.player! } public override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } internal func setup() { let singleTapGR = UITapGestureRecognizer(target: self, action: #selector(singleTap)) singleTapGR.numberOfTapsRequired = 1 addGestureRecognizer(singleTapGR) // Loop playback addReachEndObserver() playerView.alpha = 0 playImageView.alpha = 0.8 playerLayer.videoGravity = .resizeAspect previewImageView.contentMode = .scaleAspectFit sv( previewImageView, playerView, playImageView ) previewImageView.fillContainer() playerView.fillContainer() playImageView.centerInContainer() playerView.layer.addSublayer(playerLayer) } override public func layoutSubviews() { super.layoutSubviews() playerLayer.frame = playerView.frame } @objc internal func singleTap() { pauseUnpause() } @objc public func playerItemDidReachEnd(_ note: Notification) { player.actionAtItemEnd = .none player.seek(to: CMTime.zero) player.play() } } // MARK: - Video handling extension YPVideoView { /// The main load video method public func loadVideo<T>(_ item: T) { var player: AVPlayer switch item.self { case let video as YPMediaVideo: player = AVPlayer(url: video.url) case let url as URL: player = AVPlayer(url: url) case let playerItem as AVPlayerItem: player = AVPlayer(playerItem: playerItem) default: return } playerLayer.player = player playerView.alpha = 1 } /// Convenience func to pause or unpause video dependely of state public func pauseUnpause() { (player.rate == 0.0) ? play() : pause() } /// Mute or unmute the video public func muteUnmute() { player.isMuted = !player.isMuted } public func play() { player.play() showPlayImage(show: false) addReachEndObserver() } public func pause() { player.pause() showPlayImage(show: true) } public func stop() { player.pause() player.seek(to: CMTime.zero) showPlayImage(show: true) removeReachEndObserver() } public func deallocate() { playerLayer.player = nil playImageView.image = nil } } // MARK: - Other API extension YPVideoView { public func setPreviewImage(_ image: UIImage) { previewImageView.image = image } /// Shows or hide the play image over the view. public func showPlayImage(show: Bool) { UIView.animate(withDuration: 0.1) { self.playImageView.alpha = show ? 0.8 : 0 } } public func addReachEndObserver() { NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd(_:)), name: .AVPlayerItemDidPlayToEndTime, object: nil) } /// Removes the observer for AVPlayerItemDidPlayToEndTime. Could be needed to implement own observer public func removeReachEndObserver() { NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil) } }
mit
5c369852df4461727440147071d17d56
27.04908
104
0.575678
5.125561
false
false
false
false
lukhnos/LuceneSearchDemo-iOS
LuceneSearchDemo/ViewController.swift
1
6371
// // ViewController.swift // LuceneSearchDemo // // Copyright (c) 2015 Lukhnos Liu. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate { let cellReuseID = "DocumentCell" var foundDocuments: [Any] = [] @IBOutlet var searchBar: UISearchBar! @IBOutlet var infoView: UIView! @IBOutlet var activityIndicator: UIActivityIndicatorView! @IBOutlet var infoLabel: UILabel! @IBOutlet var linkButton: UIButton! @IBOutlet var tableView: UITableView! @IBOutlet var reindexButtonItem: UIBarButtonItem! enum State { case Welcome, Searching, NoResult, HasResults, RebuildingIndex } var state: State = .NoResult { didSet { updateUIState() } } override func viewDidLoad() { super.viewDidLoad() state = .Welcome tableView.register(UINib(nibName: cellReuseID, bundle: nil), forCellReuseIdentifier: cellReuseID) tableView.rowHeight = 128; searchBar.autocapitalizationType = UITextAutocapitalizationType.none } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !FileManager.default.fileExists(atPath: Document.indexRootPath()) { rebuildAction() } if let selectedIndexPath = tableView.indexPathForSelectedRow { tableView.deselectRow(at: selectedIndexPath, animated: false) } } @IBAction func moreInfoAction() { UIApplication.shared.open(URL(string: "https://lukhnos.org/mobilelucene/app-ios")!, options: [:], completionHandler: nil) } @IBAction func rebuildAction() { reindexButtonItem.isEnabled = false state = .RebuildingIndex searchBar.text = "" searchBar.resignFirstResponder() searchBar.isHidden = true foundDocuments = [] tableView.reloadData() Document.rebuildIndex({ self.state = .Welcome self.searchBar.isHidden = false self.reindexButtonItem.isEnabled = true }) } func updateUIState() { let hideInfo: Bool switch (state) { case .Welcome: hideInfo = false activityIndicator.stopAnimating() infoLabel.isHidden = false infoLabel.text = NSLocalizedString("Search with Lucene", comment: ""); linkButton.isHidden = false case .Searching: hideInfo = false activityIndicator.startAnimating() infoLabel.isHidden = true infoLabel.text = "" linkButton.isHidden = true case .NoResult: hideInfo = false activityIndicator.stopAnimating() infoLabel.isHidden = false infoLabel.text = NSLocalizedString("No Results", comment: ""); linkButton.isHidden = true case .HasResults: hideInfo = true activityIndicator.stopAnimating() infoLabel.isHidden = true infoLabel.text = ""; linkButton.isHidden = true case .RebuildingIndex: hideInfo = false activityIndicator.startAnimating() infoLabel.isHidden = false infoLabel.text = NSLocalizedString("Indexing Reviews…", comment: ""); linkButton.isHidden = true } infoView.isHidden = hideInfo tableView.isHidden = !hideInfo } var text = NSMutableString() func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() state = .Searching if let t = searchBar.text { text.setString(t) } DispatchQueue.global(qos: .default).async { if let docs = Document.search(self.text) { self.foundDocuments = docs } else { self.foundDocuments = [] } DispatchQueue.main.async { if self.foundDocuments.count > 0 { self.state = .HasResults } else { self.state = .NoResult } self.tableView.setContentOffset(CGPoint.zero, animated: false) self.tableView.reloadData() } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return foundDocuments.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseID, for: indexPath) as! DocumentCell let doc = foundDocuments[indexPath.row] as! Document cell.configureCell(doc) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "showDetail", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let selectedIndexPath = tableView.indexPathForSelectedRow { let doc = foundDocuments[selectedIndexPath.row] as! Document let controller = segue.destination as! DetailsViewController controller.document = doc } } }
mit
9f1b2ee60e9764039614ed72e084820f
33.994505
129
0.641231
5.276719
false
false
false
false
cdmx/MiniMancera
miniMancera/Model/Option/WhistlesVsZombies/SonicBoom/MOptionWhistlesVsZombiesSonicBoomItemStrategyMoving.swift
1
1010
import Foundation class MOptionWhistlesVsZombiesSonicBoomItemStrategyMoving:MGameStrategy<MOptionWhistlesVsZombiesSonicBoomItem, MOptionWhistlesVsZombies> { private var startingTime:TimeInterval? private let kDuration:TimeInterval = 0.6 override func update( elapsedTime:TimeInterval, scene:ViewGameScene<MOptionWhistlesVsZombies>) { if let startingTime:TimeInterval = self.startingTime { let deltaTime:TimeInterval = elapsedTime - startingTime if deltaTime > kDuration { guard let viewRelease:VOptionWhistlesVsZombiesSonicRelease = model.viewRelease else { return } viewRelease.endRelease() } } else { startingTime = elapsedTime model.viewBoom?.shoot() } } }
mit
45a3ef00cbbe7c236530a0ba9b3e809b
26.297297
110
0.549505
6.3125
false
false
false
false
kaishin/ImageScout
Demo/Demo-Mac/ViewController.swift
1
943
import Cocoa import ImageScout class ViewController: NSViewController { let scout = ImageScout() let jpgPath = Bundle.main.url(forResource: "scout", withExtension: "jpg") let pngPath = Bundle.main.url(forResource: "scout", withExtension: "png") let gifPath = Bundle.main.url(forResource: "scout", withExtension: "gif") @IBOutlet weak var jpgLabel: NSTextField! @IBOutlet weak var pngLabel: NSTextField! @IBOutlet weak var gifLabel: NSTextField! override func viewDidLoad() { super.viewDidLoad() scoutImage(with: jpgPath!, label: jpgLabel) scoutImage(with: pngPath!, label: pngLabel) scoutImage(with: gifPath!, label: gifLabel) } private func scoutImage(with URL: Foundation.URL, label: NSTextField) -> () { scout.scoutImage(atURL: URL) { error, size, type in DispatchQueue.main.async { label.stringValue = "\(Int(size.width))x\(Int(size.height)), \(type.rawValue.uppercased())" } } } }
mit
b6d45ff45a920262af6ff6944d381032
33.925926
126
0.709438
3.833333
false
false
false
false
XLabKC/Badger
Badger/Badger/NotificationManager.swift
1
7568
import UIKit class NotificationManager: NotificationPopupDelegate { private let AnimationDuration: NSTimeInterval = 0.5 private var activePopup: NotificationPopup? private var pendingNotifications: [RemoteNotification] = [] private var showingNotification = false init() { } func notify(notification: [NSObject: AnyObject]) { if let type = notification["type"] as? String { switch type { case "new_task": return self.createNewTaskNote(notification) case "completed_task": return self.createCompletedTaskNote(notification) case "new_status": return self.createNewStatusNote(notification) default: println("Unknown notification type: \(type)") } } } @objc func notificationPopupDismissed(popup: NotificationPopup) { let delegate = UIApplication.sharedApplication().delegate as! AppDelegate let window = delegate.window! UIView.animateWithDuration(self.AnimationDuration, animations: { _ in popup.frame = CGRect(x: 0, y: window.frame.height, width: window.frame.width, height: 72.0) }, completion: { completed in popup.removeFromSuperview() // Show the next notification if any. if !self.pendingNotifications.isEmpty { let note = self.pendingNotifications.removeAtIndex(0) self.show(note) } }) } @objc func notificationPopupSelected(popup: NotificationPopup) { if let notification = popup.getNotification() { if let revealVC = RevealManager.sharedInstance().revealVC { if let vc = NotificationManager.createViewControllerFromNotification(notification.raw) { revealVC.setFrontViewController(vc, animated: true) } } } self.notificationPopupDismissed(popup) } private func show(notification: RemoteNotification) { let delegate = UIApplication.sharedApplication().delegate as! AppDelegate let window = delegate.window! let popup = NotificationPopup.createFromNib() popup.delegate = self popup.setNotification(notification) popup.frame = CGRect(x: 0, y: window.frame.height, width: window.frame.width, height: 72.0) window.addSubview(popup) UIView.animateWithDuration(self.AnimationDuration, animations: { _ in let y = window.frame.height - popup.frame.height popup.frame = CGRect(x: 0, y: y, width: window.frame.width, height: 72.0) }, completion: { completed in popup.startTimer() }) self.activePopup = popup } private func enqueueNotification(notification: RemoteNotification) { if self.showingNotification { self.pendingNotifications.append(notification) } else { self.show(notification) } } private func createNewTaskNote(notification: [NSObject: AnyObject]) { let uid = UserStore.sharedInstance().getAuthUid() let authorUid = notification["author"] as! String let taskId = notification["task"] as! String User.createRef(authorUid).observeSingleEventOfType(.Value, withBlock: { snapshot in if snapshot != nil { let author = User.createFromSnapshot(snapshot) as! User TaskStore.tryGetTask(uid, id: taskId, startWithActive: true, withBlock: { maybeTask in if let task = maybeTask { let content = "New Task: \(task.title)" let note = RemoteNotification(type: "new_task", content: content, uid: authorUid, raw: notification) self.enqueueNotification(note) } }) } }) } private func createCompletedTaskNote(notification: [NSObject: AnyObject]) { let owner = notification["owner"] as! String let taskId = notification["task"] as! String TaskStore.tryGetTask(owner, id: taskId, startWithActive: false, withBlock: { maybeTask in if let task = maybeTask { let content = "Completed: \(task.title)" let note = RemoteNotification(type: "completed_task", content: content, uid: owner, raw: notification) self.enqueueNotification(note) } }) } private func createNewStatusNote(notification: [NSObject: AnyObject]) { let uid = notification["uid"] as! String User.createRef(uid).observeSingleEventOfType(.Value, withBlock: { snapshot in if snapshot != nil { let user = User.createFromSnapshot(snapshot) as! User let content = "\(user.fullName) is now \(user.statusText.lowercaseString)." let note = RemoteNotification(type: "new_status", content: content, uid: uid, raw: notification) self.enqueueNotification(note) } }) } class func createProfileViewController(uid: String) -> UINavigationController { let storyboard = UIStoryboard(name: "Main", bundle: nil) let nav = storyboard.instantiateViewControllerWithIdentifier("ProfileNavigationViewController") as! UINavigationController if let profileVC = nav.topViewController as? ProfileViewController { profileVC.setUid(uid) } return nav } class func createTaskDetailViewController(owner: String, id: String, active: Bool) -> UIViewController? { let storyboard = UIStoryboard(name: "Main", bundle: nil) let nav = NotificationManager.createProfileViewController(owner) let taskDetail = storyboard.instantiateViewControllerWithIdentifier("TaskDetailViewController") as! TaskDetailViewController taskDetail.setTask(owner, id: id, active: active) nav.pushViewController(taskDetail, animated: false) return nav } class func createViewControllerFromNotification(notification: [NSObject: AnyObject]) -> UIViewController? { if let type = notification["type"] as? String { switch type { case "new_task": if let taskId = notification["task"] as? String { let owner = UserStore.sharedInstance().getAuthUid() return NotificationManager.createTaskDetailViewController(owner, id: taskId, active: true) } break case "completed_task": if let taskId = notification["task"] as? String { if let owner = notification["owner"] as? String { return NotificationManager.createTaskDetailViewController(owner, id: taskId, active: false) } } break case "new_status": if let uid = notification["uid"] as? String { return NotificationManager.createProfileViewController(uid) } default: break } } return nil } } class RemoteNotification { let type: String let content: String let uid: String let timestamp = NSDate() let raw: [NSObject: AnyObject] init(type: String, content: String, uid: String, raw: [NSObject: AnyObject]) { self.type = type self.content = content self.uid = uid self.raw = raw } }
gpl-2.0
110283629e6ebea69f8066fe98a89015
39.260638
132
0.610333
5.176471
false
false
false
false
etoledom/Heyou
Heyou/Classes/Elements/ButtonElement.swift
1
1196
extension Heyou { public enum ButtonStyle { case main case normal } } public extension Heyou { @objc class Button: NSObject, Element { public typealias Handler = ((Button) -> Void) public let text: String public let style: Heyou.ButtonStyle let handler: Handler? public init(text: String, style: Heyou.ButtonStyle, handler: Handler? = nil) { self.text = text self.style = style self.handler = handler } public func renderize() -> UIView { let button = UIButton(type: .system) button.heightAnchor.constraint(equalToConstant: Heyou.Style.normalButtonHeight).isActive = true button.setTitle(text, for: UIControl.State.normal) button.addTarget(self, action: #selector(onButtonTap), for: .touchUpInside) switch style { case .main: Heyou.StyleDefaults.styleMainButton(button) default: Heyou.StyleDefaults.styleNormalButton(button) } return button } @objc func onButtonTap() { handler?(self) } } }
mit
918500684fdcd1559347d1b716b4d407
28.9
107
0.574415
4.76494
false
false
false
false
KrishMunot/swift
test/SILGen/toplevel.swift
1
3241
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s | FileCheck %s func markUsed<T>(_ t: T) {} @noreturn func trap() { fatalError() } // CHECK-LABEL: sil @main // CHECK: bb0({{%.*}} : $Int32, {{%.*}} : $UnsafeMutablePointer<UnsafeMutablePointer<Int8>>): // -- initialize x // CHECK: alloc_global @_Tv8toplevel1xSi // CHECK: [[X:%[0-9]+]] = global_addr @_Tv8toplevel1xSi : $*Int // CHECK: integer_literal $Builtin.Int2048, 999 // CHECK: store {{.*}} to [[X]] var x = 999 func print_x() { markUsed(x) } // -- assign x // CHECK: integer_literal $Builtin.Int2048, 0 // CHECK: assign {{.*}} to [[X]] // CHECK: [[PRINT_X:%[0-9]+]] = function_ref @_TF8toplevel7print_xFT_T_ : // CHECK: apply [[PRINT_X]] x = 0 print_x() // <rdar://problem/19770775> Deferred initialization of let bindings rejected at top level in playground // CHECK: alloc_global @_Tv8toplevel5countSi // CHECK: [[COUNTADDR:%[0-9]+]] = global_addr @_Tv8toplevel5countSi : $*Int // CHECK-NEXT: [[COUNTMUI:%[0-9]+]] = mark_uninitialized [var] [[COUNTADDR]] : $*Int let count: Int // CHECK: cond_br if x == 5 { count = 0 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE:bb[0-9]+]] } else { count = 10 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE]] } // CHECK: [[MERGE]]: // CHECK: load [[COUNTMUI]] markUsed(count) var y : Int func print_y() { markUsed(y) } // -- assign y // CHECK: alloc_global @_Tv8toplevel1ySi // CHECK: [[Y1:%[0-9]+]] = global_addr @_Tv8toplevel1ySi : $*Int // CHECK: [[Y:%[0-9]+]] = mark_uninitialized [var] [[Y1]] // CHECK: assign {{.*}} to [[Y]] // CHECK: [[PRINT_Y:%[0-9]+]] = function_ref @_TF8toplevel7print_yFT_T_ y = 1 print_y() // -- treat 'guard' vars as locals // CHECK-LABEL: function_ref toplevel.A.__allocating_init // CHECK: switch_enum {{%.+}} : $Optional<A>, case #Optional.some!enumelt.1: [[SOME_CASE:.+]], default // CHECK: [[SOME_CASE]]([[VALUE:%.+]] : $A): // CHECK: store [[VALUE]] to [[BOX:%.+]] : $*A // CHECK-NOT: release // CHECK: [[SINK:%.+]] = function_ref @_TF8toplevel8markUsedurFxT_ // CHECK-NOT: release // CHECK: apply [[SINK]]<A>({{%.+}}) class A {} guard var a = Optional(A()) else { trap() } markUsed(a) // CHECK: alloc_global @_Tv8toplevel21NotInitializedIntegerSi // CHECK-NEXT: [[VARADDR:%[0-9]+]] = global_addr @_Tv8toplevel21NotInitializedIntegerSi // CHECK-NEXT: [[VARMUI:%[0-9]+]] = mark_uninitialized [var] [[VARADDR]] : $*Int // CHECK-NEXT: mark_function_escape [[VARMUI]] : $*Int // <rdar://problem/21753262> Bug in DI when it comes to initialization of global "let" variables let NotInitializedInteger : Int func fooUsesUninitializedValue() { _ = NotInitializedInteger } fooUsesUninitializedValue() NotInitializedInteger = 10 fooUsesUninitializedValue() // CHECK: [[RET:%[0-9]+]] = struct $Int32 // CHECK: return [[RET]] // CHECK-LABEL: sil hidden @_TF8toplevel7print_xFT_T_ // CHECK-LABEL: sil hidden @_TF8toplevel7print_yFT_T_ // CHECK: sil hidden @_TF8toplevel13testGlobalCSEFT_Si // CHECK-NOT: global_addr // CHECK: %0 = global_addr @_Tv8toplevel1xSi : $*Int // CHECK-NOT: global_addr // CHECK: return func testGlobalCSE() -> Int { // We should only emit one global_addr in this function. return x + x }
apache-2.0
b215c774024aab27c4752e51ecd01d18
25.137097
104
0.634681
3.09847
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressNotificationServiceExtension/Sources/Tracks/Tracks+ServiceExtension.swift
1
3619
import Foundation /// Characterizes the types of service extension events we're interested in tracking. /// The raw value corresponds to the event name in Tracks. /// /// - launched: the service extension was successfully entered & launched /// - discarded: the service extension launched, but encountered an unsupported notification type /// - failed: the service extension failed to retrieve the payload /// - assembled: the service extension successfully prepared content /// private enum ServiceExtensionEvents: String { case launched = "notification_service_extension_launched" case discarded = "notification_service_extension_discarded" case failed = "notification_service_extension_failed" case assembled = "notification_service_extension_assembled" case malformed = "notification_service_extension_malformed_payload" case timedOut = "notification_service_extension_timed_out" } // MARK: - Supports tracking notification service extension events. extension Tracks { /// Tracks the successful launch of the notification service extension. /// /// - Parameter wpcomAvailable: `true` if an OAuth token exists, `false` otherwise func trackExtensionLaunched(_ wpcomAvailable: Bool) { let properties = [ "is_configured_dotcom": wpcomAvailable ] trackEvent(ServiceExtensionEvents.launched, properties: properties as [String: AnyObject]?) } /// Tracks that a notification type was discarded due to lack of support. /// It will still be delivered as before, but not as a rich notification. /// /// - Parameter notificationType: the value of the `note_id` from the APNS payload func trackNotificationDiscarded(notificationType: String) { let properties = [ "type": notificationType ] trackEvent(ServiceExtensionEvents.discarded, properties: properties as [String: AnyObject]?) } /// Tracks the failure to retrieve a notification via the REST API. /// /// - Parameters: /// - notificationIdentifier: the value of the `note_id` from the APNS payload /// - errorDescription: description of the error encountered, ideally localized func trackNotificationRetrievalFailed(notificationIdentifier: String, errorDescription: String) { let properties = [ "note_id": notificationIdentifier, "error": errorDescription ] trackEvent(ServiceExtensionEvents.failed, properties: properties as [String: AnyObject]?) } /// Tracks the successful retrieval & assembly of a rich notification. func trackNotificationAssembled() { trackEvent(ServiceExtensionEvents.assembled) } /// Tracks the unsuccessful unwrapping of push notification payload data. func trackNotificationMalformed(hasToken: Bool, notificationBody: String) { let properties: [String: AnyObject] = [ "have_token": hasToken as AnyObject, "content": notificationBody as AnyObject ] trackEvent(ServiceExtensionEvents.malformed, properties: properties) } /// Tracks the timeout of service extension processing. func trackNotificationTimedOut() { trackEvent(ServiceExtensionEvents.timedOut) } /// Utility method to capture an event & submit it to Tracks. /// /// - Parameters: /// - event: the event to track /// - properties: any accompanying metadata private func trackEvent(_ event: ServiceExtensionEvents, properties: [String: AnyObject]? = nil) { track(event.rawValue, properties: properties) } }
gpl-2.0
25b4de2f004a912aef3128d4b02023d1
41.576471
102
0.702404
5.068627
false
false
false
false
nekowen/GeoHex3.swift
Sources/GeoHex3Swift/GeoHex3.swift
1
22093
// // GeoHex3.swift // // Created by nekowen on 2017/03/30. // License: MIT License // import Foundation import CoreLocation public class GeoHex3 { public static let VERSION = "3.2" /// Hexを取得する /// Get the hexdata /// /// - Parameters: /// - latitude: latitude ex): 35.12345 /// - longitude: longitude ex): 140.12345 /// - level: hexlevel ex): 7 /// - Returns: hex public class func getZone(latitude: Double, longitude: Double, level: Int) -> Zone { let xy = self.getXY(latitude: latitude, longitude: longitude, level: level) return self.getZone(x: xy.x, y: xy.y, level: level) } /// HexcodeからHexを取得する /// Get the hex from hexcode /// /// - Parameter code: Hexcode ex): XM1234567 /// - Returns: hex public class func getZone(code: String) -> Zone { let xy = self.getXY(code: code) let level = code.length - 2 return self.getZone(x: xy.x, y: xy.y, level: level) } /// XYクラスからHexを取得する /// Get the hex from XYclass /// /// - Parameters: /// - xy: Position /// - level: hexlevel ex): 7 /// - Returns: hex public class func getZone(xy: XY, level: Int) -> Zone { return self.getZone(x: xy.x, y: xy.y, level: level) } /// XY位置からHexを取得する /// Get the hex from position /// /// - Parameters: /// - x: positionX ex): 12345 /// - y: positionY ex): 54321 /// - level: hexlevel level ex): 7 /// - Returns: hex public class func getZone(x: Int, y: Int, level: Int) -> Zone { return self.getZone(x: Double(x), y: Double(y), level: level) } /// 緯度軽度からHexを取得する /// Get the hex from coordinate /// /// - Parameters: /// - coordinate: location /// - level: hexlevel level ex): 7 /// - Returns: hex public class func getZone(coordinate: CLLocationCoordinate2D, level: Int) -> Zone { return self.getZone(latitude: coordinate.latitude, longitude: coordinate.longitude, level: level) } /// エリアからHex配列を取得する /// Get the hexArray from area /// /// - Parameters: /// - southWest: southWest coord /// - northEast: northEast coord /// - level: hexlevel /// - buffer: bufferArea /// - Returns: zone public class func getZone(southWest: CLLocationCoordinate2D, northEast: CLLocationCoordinate2D, level: Int, buffer: Bool) -> [Zone] { guard let xys = self.getXY(min_lat: southWest.latitude, min_lon: southWest.longitude, max_lat: northEast.latitude, max_lon: northEast.longitude, level: level, buffer: buffer) else { return [] } return xys.map { self.getZone(xy: $0, level: level) } } } extension GeoHex3 { fileprivate static let H_BASE = 20037508.34 fileprivate static let H_DEG = Double.pi * (30.0/180.0) fileprivate static let H_K = tan(H_DEG) fileprivate static let H_KEY = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" class func getZone(x: Double, y: Double, level: Int) -> Zone { let h_size = self.hexSize(level: level) var h_x = x var h_y = y let unit_x = 6 * h_size let unit_y = 6 * h_size * self.H_K let h_lat = (self.H_K * h_x * unit_x + h_y * unit_y) / 2.0 let h_lon = (h_lat - h_y * unit_y) / self.H_K let z_loc = self.xy2loc(x: h_lon, y: h_lat) var z_loc_x = z_loc.longitude let z_loc_y = z_loc.latitude let max_hsteps = pow(3.0, level + 2).doubleValue let hsteps = abs(h_x - h_y) if hsteps == max_hsteps { if h_x > h_y { swap(&h_x, &h_y) } z_loc_x = -180.0 } let h_code = self.encode(x: h_x, y: h_y, z_loc_x: z_loc_x, z_loc_y: z_loc_y, level: level) return Zone(coordinate: CLLocationCoordinate2D(latitude: z_loc_y, longitude: z_loc_x), xy: XY(x: x, y: y), code: h_code) } /// 緯度軽度からXYクラスを取得する /// Get the XYclass from coordinate /// /// - Parameters: /// - latitude: 緯度 /// - longitude: 軽度 /// - level: hexlevel /// - Returns: XYclass public class func getXY(latitude: Double, longitude: Double, level: Int) -> XY { let h_size = self.hexSize(level: level) let z_xy = self.loc2xy(latitude: latitude, longitude: longitude) let latitude_grid = z_xy.y let longitude_grid = z_xy.x let unit_x = 6 * h_size let unit_y = 6 * h_size * self.H_K let h_pos_x = (longitude_grid + latitude_grid / self.H_K) / unit_x let h_pos_y = (latitude_grid - self.H_K * longitude_grid) / unit_y let h_x_0 = floor(h_pos_x) let h_y_0 = floor(h_pos_y) let h_x_q: Double = h_pos_x - h_x_0 let h_y_q: Double = h_pos_y - h_y_0 var h_x: Double = round(h_pos_x) var h_y: Double = round(h_pos_y) if h_y_q > -h_x_q + 1.0 { if ((h_y_q < 2.0 * h_x_q) && (h_y_q > 0.5 * h_x_q)) { h_x = h_x_0 + 1.0 h_y = h_y_0 + 1.0 } } else if h_y_q < -h_x_q + 1.0 { if (h_y_q > (2.0 * h_x_q) - 1.0) && (h_y_q < (0.5 * h_x_q) + 0.5) { h_x = h_x_0 h_y = h_y_0 } } return self.adjustXY(x: h_x, y: h_y, level: level) } /// HexcodeからXYを取得する /// Get the XYclass from hexcode /// /// - Parameter code: hexcode /// - Returns: XYclass public class func getXY(code: String) -> XY { let level: Int = code.length - 2 var h_x: Double = 0.0 var h_y: Double = 0.0 var h_dec9 = String(self.H_KEY.index(character: code[0]) * 30 + self.H_KEY.index(character: code[1])) + code.substring(from: 2) if h_dec9.count > 2 && String(h_dec9[0]).match(pattern: "[15]") && String(h_dec9[1]).match(pattern: "[^125]") && String(h_dec9[2]).match(pattern: "[^125]") { if h_dec9[0] == "5" { h_dec9 = "7" + h_dec9.substring(from: 1) } else if h_dec9[0] == "1" { h_dec9 = "3" + h_dec9.substring(from: 1) } } var d9xlen = h_dec9.length let repeatlen = level + 3 - d9xlen h_dec9 = String(repeating: "0", count: repeatlen) + h_dec9 d9xlen += repeatlen var h_dec3 = "" (0 ..< d9xlen).forEach { (index) in if let dec9i = Int(h_dec9[index]) { let h_dec0 = String(dec9i, radix: 3) if h_dec0.length == 1 { h_dec3 += "0" } h_dec3 += h_dec0 } else { h_dec3 += "00" } } let h_dec3half = h_dec3.length / 2 var h_decx: [String] = Array(repeating: "", count: h_dec3half) var h_decy: [String] = Array(repeating: "", count: h_dec3half) (0 ..< h_dec3half).forEach { (index) in h_decx[index] = h_dec3.substring(from: index * 2, length: 1) h_decy[index] = h_dec3.substring(from: index * 2 + 1, length: 1) } (0 ..< level + 3).forEach { (index) in let h_pow = pow(3.0, level + 2 - index).doubleValue let h_ix = Int(h_decx[index]) ?? 0 let h_iy = Int(h_decy[index]) ?? 0 if h_ix == 0 { h_x -= h_pow } else if h_ix == 2 { h_x += h_pow } if h_iy == 0 { h_y -= h_pow } else if h_iy == 2 { h_y += h_pow } } return self.adjustXY(x: h_x, y: h_y, level: level) } fileprivate class func adjustXY(x: Double, y: Double, level: Int) -> XY { var x = x var y = y let max_hsteps = pow(3, level + 2).doubleValue let hsteps = abs(x - y) if hsteps == max_hsteps && x > y { swap(&x, &y) } else if hsteps > max_hsteps { let diff = hsteps - max_hsteps let diff_x = floor(diff / 2.0) let diff_y = diff - diff_x var edge_x: Double = 0.0 var edge_y: Double = 0.0 if x > y { edge_x = x - diff_x edge_y = y + diff_y swap(&edge_x, &edge_y) x = edge_x + diff_x y = edge_y - diff_y } else if y > x { edge_x = x + diff_x edge_y = y - diff_y swap(&edge_x, &edge_y) x = edge_x - diff_x y = edge_y + diff_y } } return XY(x: x, y: y) } class func hexSize(level: Int) -> Double { return self.H_BASE / pow(3.0, Double(level) + 3) } class func loc2xy(latitude: Double, longitude: Double) -> XY { let x = longitude * H_BASE / 180.0 var y = log(tan((90.0 + latitude) * Double.pi / 360.0)) / (Double.pi / 180.0) y *= H_BASE / 180.0 return XY(x: x, y: y) } class func xy2loc(x: Double, y: Double) -> CLLocationCoordinate2D { var latitude = (y / H_BASE) * 180.0 let longitude = (x / H_BASE) * 180.0 latitude = 180.0 / Double.pi * (2.0 * atan(exp(latitude * Double.pi / 180.0)) - Double.pi / 2.0) return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } fileprivate class func encode(x: Double, y: Double, z_loc_x: Double, z_loc_y: Double, level: Int) -> String { var h_code: String = "" var code3_x: [Int] = Array(repeating: 0, count: level+3) var code3_y: [Int] = Array(repeating: 0, count: level+3) var mod_x = x var mod_y = y (0 ..< level + 3).forEach { (index) in let h_pow = pow(3.0, level + 2 - index).doubleValue if mod_x >= ceil(h_pow / 2.0) { code3_x[index] = 2 mod_x -= h_pow } else if mod_x <= -ceil(h_pow / 2.0) { code3_x[index] = 0 mod_x += h_pow } else { code3_x[index] = 1 } if mod_y >= ceil(h_pow / 2.0) { code3_y[index] = 2 mod_y -= h_pow } else if mod_y <= -ceil(h_pow / 2.0) { code3_y[index] = 0 mod_y += h_pow } else { code3_y[index] = 1 } if index == 2 && (z_loc_x == -180 || z_loc_x >= 0) { if code3_x[0] == 2 && code3_y[0] == 1 && code3_x[1] == code3_y[1] && code3_x[2] == code3_y[2] { code3_x[0] = 1 code3_y[0] = 2 } else if code3_x[0] == 1 && code3_y[0] == 0 && code3_x[1] == code3_y[1] && code3_x[2] == code3_y[2] { code3_x[0] = 0 code3_y[0] = 1 } } } var index = 0 code3_x.forEach { (value) in let code3 = Int("\(value)\(code3_y[index])", radix: 3) ?? 0 h_code += "\(code3)" index += 1 } let h_2 = h_code.substring(from: 3) let h_1 = Int(h_code.substring(from: 0, length: 3)) ?? 0 let h_a1 = Int(floor(Double(h_1 / 30))) let h_a2 = h_1 % 30 return self.H_KEY.substring(from: h_a1, length: 1) + self.H_KEY.substring(from: h_a2, length: 1) + h_2 } } extension GeoHex3 { class func getXY(min_lat: Double, min_lon: Double, max_lat: Double, max_lon: Double, level: Int, buffer: Bool) -> [XY]? { struct HexEdge { var l: Int var r: Int var t: Int var b: Int } let base_steps = (pow(3, level + 2) * 2).integerValue var min_lat = (min_lat > max_lat ? max_lat : min_lat) var max_lat = (min_lat < max_lat ? max_lat : min_lat) var min_lon = min_lon var max_lon = max_lon if buffer { let min_xy = self.loc2xy(latitude: min_lat, longitude: min_lon) let max_xy = self.loc2xy(latitude: max_lat, longitude: max_lon) let x_len = max_lon >= min_lon ? abs(max_xy.x - min_xy.x) : abs(self.H_BASE + max_xy.x - min_xy.x + self.H_BASE) let y_len = abs(max_xy.y - min_xy.y) let min_coord = self.xy2loc(x: (min_xy.x - x_len/2).truncatingRemainder(dividingBy: self.H_BASE*2), y: min_xy.y - y_len / 2) let max_coord = self.xy2loc(x: (max_xy.x - x_len/2).truncatingRemainder(dividingBy: self.H_BASE*2), y: max_xy.y - y_len / 2) min_lon = min_coord.longitude.truncatingRemainder(dividingBy: 360.0) max_lon = max_coord.longitude.truncatingRemainder(dividingBy: 360.0) min_lat = min_coord.latitude < -85.051128514 ? -85.051128514 : min_coord.latitude max_lat = max_coord.latitude > 85.051128514 ? 85.051128514 : max_coord.latitude min_lon = x_len * 2 >= self.H_BASE * 2 ? -180 : min_lon max_lon = x_len * 2 >= self.H_BASE * 2 ? 180 : max_lon } let zone_tl = self.getZone(latitude: max_lat, longitude: min_lon, level: level) let zone_bl = self.getZone(latitude: min_lat, longitude: min_lon, level: level) let zone_br = self.getZone(latitude: min_lat, longitude: max_lon, level: level) let zone_tr = self.getZone(latitude: max_lat, longitude: max_lon, level: level) let h_size = zone_br.hexSize let bl_xy = self.loc2xy(latitude: zone_bl.latitude, longitude: zone_bl.longitude) let bl_cl = self.xy2loc(x: bl_xy.x - h_size, y: bl_xy.y).longitude let bl_cr = self.xy2loc(x: bl_xy.x + h_size, y: bl_xy.y).longitude let br_xy = self.loc2xy(latitude: zone_br.latitude, longitude: zone_br.longitude) let br_cl = self.xy2loc(x: br_xy.x - h_size, y: br_xy.y).longitude let br_cr = self.xy2loc(x: br_xy.x + h_size, y: br_xy.y).longitude let s_steps = self.getXSteps(minlon: min_lon, maxlon: max_lon, min: zone_bl, max: zone_br) let w_steps = self.getYSteps(lon: min_lon, min: zone_bl, max: zone_tl) let n_steps = self.getXSteps(minlon: min_lon, maxlon: max_lon, min: zone_tl, max: zone_tr) let e_steps = self.getYSteps(lon: max_lon, min: zone_br, max: zone_tr) var edge: HexEdge = HexEdge(l: 0, r: 0, t: 0, b: 0) if s_steps == n_steps && s_steps >= base_steps { edge.l = 0 edge.r = 0 } else { if min_lon > 0 && zone_bl.longitude == -180 { let m_lon = min_lon - 360 if bl_cr < m_lon { edge.l = 1 } if bl_cl > m_lon { edge.l = -1 } } else { if bl_cr < min_lon { edge.l = 1 } if bl_cl > min_lon { edge.l = -1 } } if max_lon > 0 && zone_br.longitude == -180 { let m_lon = max_lon - 360 if br_cr < m_lon { edge.r = 1 } if br_cl > m_lon { edge.r = -1 } } else { if br_cr < max_lon { edge.r = 1 } if br_cl > max_lon { edge.r = -1 } } } if zone_bl.latitude > min_lat { edge.b += 1 } if zone_tl.latitude > max_lat { edge.t += 1 } let s_list = self.getX(min: zone_bl.position, xsteps: s_steps, edge: edge.b) let w_list = self.getY(min: zone_bl.position, ysteps: w_steps, edge: edge.l) guard let w_list_last = w_list.last, let s_list_last = s_list.last else { return nil } let tl_end = XY(x: w_list_last.x, y: w_list_last.y) let br_end = XY(x: s_list_last.x, y: s_list_last.y) let n_list = self.getX(min: tl_end, xsteps: n_steps, edge: edge.t) let e_list = self.getY(min: br_end, ysteps: e_steps, edge: edge.r) return self.merge(xys: s_list + w_list + n_list + e_list, level: level) } fileprivate class func getX(min: XY, xsteps: Int, edge: Int) -> [XY] { return (0 ..< xsteps).map { (index) in let index = Double(index) let x = edge != 0 ? min.x + floor(index / 2.0) : min.x + ceil(index / 2.0) let y = edge != 0 ? min.y + floor(index / 2.0) - index : min.y + ceil(index / 2.0) - index return XY(x: x, y: y) } } fileprivate class func getY(min: XY, ysteps: Double, edge: Int) -> [XY] { let steps_base = floor(ysteps) let steps_half = ysteps - steps_base return (0 ..< Int(steps_base)).reduce([XY]()) { (result, index) in var result = result let index = Double(index) let x = min.x + index let y = min.y + index result.append(XY(x: x, y: y)) if edge != 0 { if steps_half == 0 && index == steps_base - 1 { } else { let x = edge > 0 ? min.x + index + 1 : min.x + index let y = edge < 0 ? min.y + index + 1 : min.y + index result.append(XY(x: x, y: y)) } } return result } } fileprivate class func getXSteps(minlon: Double, maxlon: Double, min: Zone, max: Zone) -> Int { let minsteps = Int(abs(min.x - min.y)) let maxsteps = Int(abs(max.x - max.y)) let code = min.code let base_steps = (pow(3.0, code.length) * 2.0).integerValue var steps = 0 if min.longitude == -180 && max.longitude == -180 { if (minlon > maxlon && minlon * maxlon >= 0) || (minlon < 0 && maxlon > 0) { steps = base_steps } else { steps = 0 } } else if abs(min.longitude - max.longitude) < 0.0000000001 { if min.longitude != -180 && minlon > maxlon { steps = base_steps } else { steps = 0 } } else if min.longitude < max.longitude { if min.longitude <= 0 && max.longitude <= 0 { steps = minsteps - maxsteps }else if min.longitude <= 0 && max.longitude >= 0 { steps = minsteps + maxsteps }else if min.longitude >= 0 && max.longitude>=0 { steps = maxsteps - minsteps } } else if min.longitude > max.longitude { if min.longitude <= 0 && max.longitude <= 0 { steps = base_steps - maxsteps + minsteps }else if min.longitude >= 0 && max.longitude <= 0 { steps = base_steps-(minsteps + maxsteps) }else if min.longitude >= 0 && max.longitude >= 0 { steps = base_steps + maxsteps - minsteps } } return steps + 1 } fileprivate class func getYSteps(lon: Double, min: Zone, max: Zone) -> Double { var min_x = min.x var min_y = min.y var max_x = max.x var max_y = max.y if lon > 0 { if min.longitude != -180 && max.longitude == -180 { max_x = max.y max_y = max.x } if min.longitude == -180 && max.longitude != -180 { min_x = min.y min_y = min.x } } let steps = abs(min_y - max_y) let half = abs(max_x - min_x) - abs(max_y - min_y) return steps + half * 0.5 + 1 } fileprivate class func merge(xys: [XY], level: Int) -> [XY] { let xys = xys.sorted { (a, b) in return a.x > b.x ? false : a.x < b.x ? true : a.y < b.y ? false : true } var index = 0 var mergeHash: [String:Bool] = [:] return xys.reduce([XY]()) { (result, xy) in var result = result if index == 0 { let inner_xy = self.adjustXY(x: xy.x, y: xy.y, level: level) let key = "\(inner_xy.x):\(inner_xy.y)" if mergeHash[key] == nil { mergeHash[key] = true result.append(inner_xy) } } else { let mergelen = self.mergeCheck(pre: xys[index - 1], next: xy) (0 ..< mergelen).forEach { (j) in let j = Double(j) let inner_xy = self.adjustXY(x: xy.x, y: xy.y + j, level: level) let key = "\(inner_xy.x):\(inner_xy.y)" if mergeHash[key] == nil { mergeHash[key] = true result.append(inner_xy) } } } index += 1 return result } } fileprivate class func mergeCheck(pre: XY, next: XY) -> Int { if pre == next { return 0 } else if pre.x != next.x { return 1 } else { return Int(abs(next.y - pre.y)) } } }
mit
70f190bc5b3aa209215d838d7170436a
34.900164
189
0.463278
3.365812
false
false
false
false
bumpersfm/handy
Components/CustomTitleView.swift
1
3168
// // Created by Dani Postigo on 11/24/16. // import Foundation import UIKit public class CustomTitleView: ControlBar { public let textLabel = UILabel(title: "Title", color: UIColor.whiteColor(), font: UIFont.boldSystemFontOfSize(24.0)) public let detailTextLabel = UILabel(title: "Subtitle", color: UIColor.whiteColor(), font: UIFont.boldSystemFontOfSize(12.0)) override public init(frame: CGRect) { super.init(frame: frame) self.textLabel.textAlignment = .Left self.textLabel.setContentHuggingPriority(1000, forAxis: .Vertical) self.textLabel.setContentCompressionResistancePriority(1000, forAxis: .Horizontal) self.textLabel.numberOfLines = 1 self.detailTextLabel.textAlignment = .Left self.detailTextLabel.setContentHuggingPriority(1000, forAxis: .Vertical) self.detailTextLabel.setContentCompressionResistancePriority(1000, forAxis: .Horizontal) let stack = UIStackView(axis: .Vertical) stack.addArrangedSubviews([self.textLabel, self.detailTextLabel]) stack.preservesSuperviewLayoutMargins = true stack.layoutMarginsRelativeArrangement = true self.translatesAutoresizingMaskIntoConstraints = false self.titleView = stack self.layoutIfNeeded() self.translatesAutoresizingMaskIntoConstraints = true } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: Convenience public convenience init(title: String, subtitle: String = "Subtitle") { self.init(); self.title = title; self.subtitle = subtitle } public convenience init(navigationItem: UINavigationItem) { self.init(title: navigationItem.title ?? "") } public convenience init(forViewController vc: UIViewController) { self.init(navigationItem: vc.navigationItem) let estimatedItemWidth: CGFloat = 50 let target = CGSize(width: vc.view.frame.size.width - (estimatedItemWidth * 2), height: self.titleView.frame.size.height) self.textLabel.preferredMaxLayoutWidth = target.width let fittingSize = self.titleView.systemLayoutSizeFittingSize(target, withHorizontalFittingPriority: UILayoutPriorityRequired, verticalFittingPriority: UILayoutPriorityRequired) self.frame.size.width = fittingSize.width } public var title: String? { set { self.textLabel.text = newValue } get { return self.textLabel.text } } public var subtitle: String? { set { self.detailTextLabel.text = newValue } get { return self.detailTextLabel.text } } } extension UIView { func systemLayout() { let frame = self.frame let compressedSize = self.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) Swift.print("compressedSize = \(compressedSize)") assert(self.frame == frame) let expandedSize = self.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize) Swift.print("expandedSize = \(expandedSize)") assert(self.frame == frame) } }
mit
6df530a4e83c12b5137885e1e6bd66e4
37.180723
184
0.688447
5.297659
false
false
false
false
LYM-mg/DemoTest
其他功能/MGImagePickerControllerTest/MGImagePickerControllerTest/ImagePickerController/Manager/MGPhotoStore.swift
1
11862
// // MGPhotoStore.swift // MGImagePickerControllerDemo // // Created by newunion on 2019/7/5. // Copyright © 2019 MG. All rights reserved. // import UIKit import Photos /// 负责请求图片的管理类 @available(iOS 8.0, *) class MGPhotoStore: NSObject { /// 负责请求图片对象的图片库 fileprivate let photoLibrary: PHPhotoLibrary = PHPhotoLibrary.shared() /// 配置类对象 var config: MGPhotoConfig = MGPhotoConfig() /// 相册变化发生的回调 var photoStoreHasChanged: ((_ changeInstance: PHChange) -> Void)? override init() { super.init() photoLibrary.register(self) } /// 初始化方法 /// /// - Parameter config: 赋值配置类对象 convenience init(config: MGPhotoConfig) { self.init() self.config = config } deinit { /// 移除观察者 photoLibrary.unregisterChangeObserver(self as PHPhotoLibraryChangeObserver) } // MARK: fetch /// 获取photos提供的所有的智能分类相册组,与config属性无关 /// /// - Parameter groups: 图片组对象 public func fetch(groups: @escaping([PHAssetCollection]) -> Void) -> Void { mg_fetchBasePhotosGroup { (group) in guard let group = group else { return } MGPhotoHandleManager.resultToArray(group as! PHFetchResult<AnyObject>, complete: { (completeGroup, _) in let tempArray = self.mg_handleAssetCollection(completeGroup as? [PHAssetCollection] ?? [PHAssetCollection]()) if tempArray.count > 0 { groups(tempArray) } }) } } /// 根据photos提供的智能分类相册组 根据config中的groupNamesConfig属性进行筛别 /// /// - Parameter groups: 图片组对象 public func fetchDefault(groups: @escaping ([PHAssetCollection]) -> Void) -> Void { mg_fetchBasePhotosGroup { [weak self](result) in let strongSelf = self guard let result = result else { return } strongSelf!.mg_prepare(result, complete: { (defaultGroup) in let tempArray = strongSelf?.mg_handleAssetCollection(defaultGroup) if let tempArray = tempArray, tempArray.count > 0 { groups(tempArray) } }) } } /// 根据photos提供的智能分类相册组 根据config中的groupNamesConfig属性进行筛别 并添加上其他在手机中创建的相册 /// /// - Parameter groups: public func fetchDefaultAllGroups(_ groups: @escaping (([PHAssetCollection], PHFetchResult<AnyObject>) -> Void)) { var defaultAllGroups = [PHAssetCollection]() // 获取 fetchDefault { (defaultGroups) in defaultAllGroups.append(contentsOf: defaultGroups) //遍历自定义的组 MGPhotoHandleManager.resultToArray(PHCollection.fetchTopLevelUserCollections(with: PHFetchOptions()) as! PHFetchResult<AnyObject>, complete: { (topLevelArray, result) in defaultAllGroups.append(contentsOf: topLevelArray as! [PHAssetCollection]) //进行主线程回调 if Thread.isMainThread { groups(defaultAllGroups, result); return } DispatchQueue.global().async { //主线程刷新UI DispatchQueue.main.async { groups(defaultAllGroups, result) } } }) } } // MARK: 相片 /// 获取某个相册的所有照片的简便方法 /// /// - Parameter group: /// - Returns: static func fetchPhotos(_ group: PHAssetCollection) -> PHFetchResult<AnyObject> { return PHAsset.fetchAssets(in: group, options: PHFetchOptions()) as! PHFetchResult<AnyObject> } // MARK: private function /// 获取最基本的智能分组 /// /// - Parameter _: 获取到的回调closer private func mg_fetchBasePhotosGroup(complete: @escaping ((PHFetchResult<PHAssetCollection>?) -> Void)) { mg_checkAuthorizationState(allow: { () in //获取智能分组 let smartGroups = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.albumRegular, options: nil) // 准许 complete((smartGroups)) }, denied: {() in //获得权限 let status = PHPhotoLibrary.authorizationStatus() if status == .denied || status == .restricted { } }) } // MARK: 检测权限 /// 检测是否获得图片库的权限 /// /// - Parameters: /// - allow: 允许操作 /// - denied: 不允许操作 func mg_checkAuthorizationState(allow: @escaping () -> Void, denied: @escaping() -> Void) { //获得权限 let status = PHPhotoLibrary.authorizationStatus() switch status { case .authorized: allow() //允许 case .notDetermined://询问 PHPhotoLibrary.requestAuthorization({ (status) in if status == .authorized { allow() } else { denied() } }) case .denied: break //不允许 case .restricted: denied() default: break } } /// 将处理数组中的 胶卷相册拍到第一位 /// /// - Parameter assCollection: 需要处理的数组 /// - Returns: 处理完毕的数组 private func mg_handleAssetCollection(_ assCollection: [PHAssetCollection]) -> [PHAssetCollection] { var collections: [PHAssetCollection] = assCollection for i in 0 ..< assCollection.count { //获取资源 let collection = assCollection[i] guard let collectionTitle = collection.localizedTitle else { continue } if collectionTitle.isEqual(NSLocalizedString(ConfigurationAllPhotos, comment: "")) || collectionTitle.isEqual(NSLocalizedString(ConfigurationCameraRoll, comment: "")) { collections.swapAt(i, 0) // 交换位置 // collections.remove(at: i) // collections.insert(collection, at: 0) } } return collections } /// 将configuration属性中的分类进行筛选 /// /// - Parameters: /// - result: 进行筛选的result /// - complete: 处理完毕的数组 private func mg_prepare(_ result: PHFetchResult<PHAssetCollection>, complete: @escaping(([PHAssetCollection]) -> Void)) { var preparationCollections = [PHAssetCollection]() result.enumerateObjects({ (obj, idx, _) in if obj.isKind(of: PHAssetCollection.self) && obj.estimatedAssetCount > 0 { // //获取出但前相簿内的图片 // let resultsOptions = PHFetchOptions() // resultsOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", // ascending: false)] // resultsOptions.predicate = NSPredicate(format: "mediaType = %d", // PHAssetMediaType.image.rawValue) let assetResult = MGPhotoStore.fetchPhotos(obj) debugPrint(obj.localizedTitle ?? "") // 过滤空数组 if assetResult.count != 0 { preparationCollections.append(obj) } } }) complete(preparationCollections) } } // MARK: - 监听变化 extension MGPhotoStore: PHPhotoLibraryChangeObserver { public func photoLibraryDidChange(_ changeInstance: PHChange) { self.photoStoreHasChanged?(changeInstance) } } // MARK: - 对组的操作 extension MGPhotoStore { /// 创建一个相册 /// /// - Parameters: /// - title: 相册的名称 /// - complete: 完成 /// - fail: 失败 func add(customGroupNamed title: String, complete: @escaping(() -> Void), fail: @escaping((String?) -> Void)) { photoLibrary.performChanges({ //执行请求 PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: title) }) { (success, error) in if success == true { complete() return } fail(error?.localizedDescription) } } /// 创建一个相册 /// /// - Parameters: /// - title: 相册的名称 /// - photos: 同时添加进相册的默认图片 /// - complete: 完成 /// - fail: 失败 func add(customGroupNamed title: String, including photos: [PHAsset], complete: @escaping(() -> Void), fail: @escaping((String?) -> Void)) { photoLibrary.performChanges({ let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: title) //添加图片资源 request.addAssets(photos as NSFastEnumeration) }) { (success, error) in if success == true { complete() return } fail(error?.localizedDescription) } } /// 检测是否存在同名相册,如果存在返回第一个同名相册 /// /// - Parameters: /// - title: 相册的名称 /// - result: 如果存在返回第一个同名相册 func check(groupnamed title: String, result closure: @escaping((Bool, PHAssetCollection) -> Void)) { MGPhotoHandleManager.resultToArray(PHCollection.fetchTopLevelUserCollections(with: PHFetchOptions()) as! PHFetchResult<AnyObject>) { (topLevelArray, _) in var isExist = false var isExistCollection: PHAssetCollection? //开始遍历 for i in 0 ..< topLevelArray.count { if topLevelArray[i].localizedDescription == title { isExist = true isExistCollection = (topLevelArray[i] as! PHAssetCollection) break } } closure(isExist, isExistCollection!) } } } // MARK: - 对照片的处理 extension MGPhotoStore { /// 向组对象中添加image对象 /// /// - Parameters: /// - image: 添加的image /// - collection: 组 /// - completeHandle: 完成 /// - fail: 失败 func add(_ image: UIImage, to collection: PHAssetCollection, completeHandle: @escaping(() -> Void), fail: @escaping((_ error: String) -> Void)) { photoLibrary.performChanges({ if collection.canPerform(PHCollectionEditOperation.addContent) { let request = PHAssetChangeRequest.creationRequestForAsset(from: image) let groupRequest = PHAssetCollectionChangeRequest(for: collection) groupRequest?.addAssets([request.placeholderForCreatedAsset!] as NSFastEnumeration) } }) { (success, error) in if success == true { completeHandle() return } fail(error?.localizedDescription ?? "") } } /// 向组对象中添加image对象 /// /// - Parameters: /// - path: image对象的路径 /// - collection: 组 /// - completeHandle: 完成 /// - fail: 失败 func add(imageAtPath path: String, to collection: PHAssetCollection, completeHandle: @escaping(() -> Void), fail: @escaping((_ error: String) -> Void)) { let image = UIImage(contentsOfFile: path) add(image!, to: collection, completeHandle: completeHandle, fail: fail) } }
mit
2fad64d36dade78fad2b3b115d289547
31.888554
181
0.568825
4.850733
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/Pods/Kingfisher/Sources/Networking/ImageDownloader.swift
3
15886
// // ImageDownloader.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// Represents a success result of an image downloading progress. public struct ImageLoadingResult { /// The downloaded image. public let image: Image /// Original URL of the image request. public let url: URL? /// The raw data received from downloader. public let originalData: Data } /// Represents a task of an image downloading process. public struct DownloadTask { /// The `SessionDataTask` object bounded to this download task. Multiple `DownloadTask`s could refer /// to a same `sessionTask`. This is an optimization in Kingfisher to prevent multiple downloading task /// for the same URL resource at the same time. /// /// When you `cancel` a `DownloadTask`, this `SessionDataTask` and its cancel token will be pass through. /// You can use them to identify the cancelled task. public let sessionTask: SessionDataTask /// The cancel token which is used to cancel the task. This is only for identify the task when it is cancelled. /// To cancel a `DownloadTask`, use `cancel` instead. public let cancelToken: SessionDataTask.CancelToken /// Cancel this task if it is running. It will do nothing if this task is not running. /// /// - Note: /// In Kingfisher, there is an optimization to prevent starting another download task if the target URL is being /// downloading. However, even when internally no new session task created, a `DownloadTask` will be still created /// and returned when you call related methods, but it will share the session downloading task with a previous task. /// In this case, if multiple `DownloadTask`s share a single session download task, cancelling a `DownloadTask` /// does not affect other `DownloadTask`s. /// /// If you need to cancel all `DownloadTask`s of a url, use `ImageDownloader.cancel(url:)`. If you need to cancel /// all downloading tasks of an `ImageDownloader`, use `ImageDownloader.cancelAll()`. public func cancel() { sessionTask.cancel(token: cancelToken) } } extension DownloadTask { enum WrappedTask { case download(DownloadTask) case dataProviding func cancel() { switch self { case .download(let task): task.cancel() case .dataProviding: break } } var value: DownloadTask? { switch self { case .download(let task): return task case .dataProviding: return nil } } } } /// Represents a downloading manager for requesting the image with a URL from server. open class ImageDownloader { // MARK: Singleton /// The default downloader. public static let `default` = ImageDownloader(name: "default") // MARK: Public Properties /// The duration before the downloading is timeout. Default is 15 seconds. open var downloadTimeout: TimeInterval = 15.0 /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this /// set will be ignored. You can use this set to specify the self-signed site. It only will be used if you don't /// specify the `authenticationChallengeResponder`. /// /// If `authenticationChallengeResponder` is set, this property will be ignored and the implementation of /// `authenticationChallengeResponder` will be used instead. open var trustedHosts: Set<String>? /// Use this to set supply a configuration for the downloader. By default, /// NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. /// /// You could change the configuration before a downloading task starts. /// A configuration without persistent storage for caches is requested for downloader working correctly. open var sessionConfiguration = URLSessionConfiguration.ephemeral { didSet { session.invalidateAndCancel() session = URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil) } } /// Whether the download requests should use pipeline or not. Default is false. open var requestsUsePipelining = false /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. open weak var delegate: ImageDownloaderDelegate? /// A responder for authentication challenge. /// Downloader will forward the received authentication challenge for the downloading session to this responder. open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable? private let name: String private let sessionDelegate: SessionDelegate private var session: URLSession // MARK: Initializers /// Creates a downloader with name. /// /// - Parameter name: The name for the downloader. It should not be empty. public init(name: String) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the downloader. " + "A downloader with empty name is not permitted.") } self.name = name sessionDelegate = SessionDelegate() session = URLSession( configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil) authenticationChallengeResponder = self setupSessionHandler() } deinit { session.invalidateAndCancel() } private func setupSessionHandler() { sessionDelegate.onReceiveSessionChallenge.delegate(on: self) { (self, invoke) in self.authenticationChallengeResponder?.downloader(self, didReceive: invoke.1, completionHandler: invoke.2) } sessionDelegate.onReceiveSessionTaskChallenge.delegate(on: self) { (self, invoke) in self.authenticationChallengeResponder?.downloader( self, task: invoke.1, didReceive: invoke.2, completionHandler: invoke.3) } sessionDelegate.onValidStatusCode.delegate(on: self) { (self, code) in return (self.delegate ?? self).isValidStatusCode(code, for: self) } sessionDelegate.onDownloadingFinished.delegate(on: self) { (self, value) in let (url, result) = value do { let value = try result.get() self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: value, error: nil) } catch { self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: nil, error: error) } } sessionDelegate.onDidDownloadData.delegate(on: self) { (self, task) in guard let url = task.task.originalRequest?.url else { return task.mutableData } return (self.delegate ?? self).imageDownloader(self, didDownload: task.mutableData, for: url) } } @discardableResult func downloadImage( with url: URL, options: KingfisherParsedOptionsInfo, completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { // Creates default request. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: downloadTimeout) request.httpShouldUsePipelining = requestsUsePipelining if let requestModifier = options.requestModifier { // Modifies request before sending. guard let r = requestModifier.modified(for: request) else { options.callbackQueue.execute { completionHandler?(.failure(KingfisherError.requestError(reason: .emptyRequest))) } return nil } request = r } // There is a possibility that request modifier changed the url to `nil` or empty. // In this case, throw an error. guard let url = request.url, !url.absoluteString.isEmpty else { options.callbackQueue.execute { completionHandler?(.failure(KingfisherError.requestError(reason: .invalidURL(request: request)))) } return nil } // Wraps `completionHandler` to `onCompleted` respectively. let onCompleted = completionHandler.map { block -> Delegate<Result<ImageLoadingResult, KingfisherError>, Void> in let delegate = Delegate<Result<ImageLoadingResult, KingfisherError>, Void>() delegate.delegate(on: self) { (_, callback) in block(callback) } return delegate } // SessionDataTask.TaskCallback is a wrapper for `onCompleted` and `options` (for processor info) let callback = SessionDataTask.TaskCallback( onCompleted: onCompleted, options: options ) // Ready to start download. Add it to session task manager (`sessionHandler`) let downloadTask: DownloadTask if let existingTask = sessionDelegate.task(for: url) { downloadTask = sessionDelegate.append(existingTask, url: url, callback: callback) } else { let sessionDataTask = session.dataTask(with: request) sessionDataTask.priority = options.downloadPriority downloadTask = sessionDelegate.add(sessionDataTask, url: url, callback: callback) } let sessionTask = downloadTask.sessionTask // Start the session task if not started yet. if !sessionTask.started { sessionTask.onTaskDone.delegate(on: self) { (self, done) in // Underlying downloading finishes. // result: Result<(Data, URLResponse?)>, callbacks: [TaskCallback] let (result, callbacks) = done // Before processing the downloaded data. do { let value = try result.get() self.delegate?.imageDownloader( self, didFinishDownloadingImageForURL: url, with: value.1, error: nil ) } catch { self.delegate?.imageDownloader( self, didFinishDownloadingImageForURL: url, with: nil, error: error ) } switch result { // Download finished. Now process the data to an image. case .success(let (data, response)): let processor = ImageDataProcessor( data: data, callbacks: callbacks, processingQueue: options.processingQueue) processor.onImageProcessed.delegate(on: self) { (self, result) in // `onImageProcessed` will be called for `callbacks.count` times, with each // `SessionDataTask.TaskCallback` as the input parameter. // result: Result<Image>, callback: SessionDataTask.TaskCallback let (result, callback) = result if let image = try? result.get() { self.delegate?.imageDownloader(self, didDownload: image, for: url, with: response) } let imageResult = result.map { ImageLoadingResult(image: $0, url: url, originalData: data) } let queue = callback.options.callbackQueue queue.execute { callback.onCompleted?.call(imageResult) } } processor.process() case .failure(let error): callbacks.forEach { callback in let queue = callback.options.callbackQueue queue.execute { callback.onCompleted?.call(.failure(error)) } } } } delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request) sessionTask.resume() } return downloadTask } // MARK: Dowloading Task /// Downloads an image with a URL and option. /// /// - Parameters: /// - url: Target URL. /// - options: The options could control download behavior. See `KingfisherOptionsInfo`. /// - progressBlock: Called when the download progress updated. This block will be always be called in main queue. /// - completionHandler: Called when the download progress finishes. This block will be called in the queue /// defined in `.callbackQueue` in `options` parameter. /// - Returns: A downloading task. You could call `cancel` on it to stop the download task. @discardableResult open func downloadImage( with url: URL, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { var info = KingfisherParsedOptionsInfo(options) if let block = progressBlock { info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] } return downloadImage( with: url, options: info, completionHandler: completionHandler) } } // MARK: Cancelling Task extension ImageDownloader { /// Cancel all downloading tasks for this `ImageDownloader`. It will trigger the completion handlers /// for all not-yet-finished downloading tasks. /// /// If you need to only cancel a certain task, call `cancel()` on the `DownloadTask` /// returned by the downloading methods. If you need to cancel all `DownloadTask`s of a certain url, /// use `ImageDownloader.cancel(url:)`. public func cancelAll() { sessionDelegate.cancelAll() } /// Cancel all downloading tasks for a given URL. It will trigger the completion handlers for /// all not-yet-finished downloading tasks for the URL. /// /// - Parameter url: The URL which you want to cancel downloading. public func cancel(url: URL) { sessionDelegate.cancel(url: url) } } // Use the default implementation from extension of `AuthenticationChallengeResponsable`. extension ImageDownloader: AuthenticationChallengeResponsable {} // Use the default implementation from extension of `ImageDownloaderDelegate`. extension ImageDownloader: ImageDownloaderDelegate {}
mit
348764bbf5625b3bf10cf197ca3c7e80
42.051491
120
0.641194
5.295333
false
false
false
false
kgn/KGNPreferredFontManager
Source/PreferredFontLabel.swift
1
4055
// // PreferredFontLabel.swift // Vesting // // Created by David Keegan on 1/11/15. // Copyright (c) 2015 David Keegan. All rights reserved. // import UIKit private extension Selector { static let contentSizeCategoryDidChange = #selector(PreferredFontLabel.contentSizeCategoryDidChange(notification:)) static let preferredFontManagerDidChange = #selector(PreferredFontLabel.preferredFontManagerDidChange(notification:)) } /// Subclass of `UILabel` whos font is controlled by /// the `textStyle` and `preferredFontManager` properties. /// The font used is automaticly updated when the user changes /// their accesability text size setting. open class PreferredFontLabel: UILabel { // TODO: before iOS 10 this may not behave as expected private var lastSizeCategory: UIContentSizeCategory = .medium private var sizeCategory: UIContentSizeCategory { if #available(iOSApplicationExtension 10.0, *) { // TODO: is this always unspecified if self.traitCollection.preferredContentSizeCategory != .unspecified { return self.traitCollection.preferredContentSizeCategory } } return self.lastSizeCategory } /// The text style to be used. /// Defaults to `UIFontTextStyleBody`. open var textStyle: UIFont.TextStyle = UIFont.TextStyle.body { didSet { self.updateFont() } } /// The preferred font manager object to use. /// Defaults to `PreferredFontManager.sharedManager()`. open var preferredFontManager: PreferredFontManager? = PreferredFontManager.shared { didSet { self.updateFont() } } public override init(frame: CGRect) { super.init(frame: frame) self.setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } /// Initialize a `PreferredFontLabel` object with a given textStyle. public convenience init(textStyle: UIFont.TextStyle) { self.init(frame: CGRect.zero) self.textStyle = textStyle self.updateFont() } deinit { NotificationCenter.default.removeObserver(self) } /// This `setup` method is called when initalized. /// Override this method to customize the setup of the button object. /// Be sure to call `super.setup()` in your implementation. open func setup() { self.updateFont() NotificationCenter.default.addObserver( self, selector: .contentSizeCategoryDidChange, name: UIContentSizeCategory.didChangeNotification, object: nil) NotificationCenter.default.addObserver( self, selector: .preferredFontManagerDidChange, name: NSNotification.Name(rawValue: PreferredFontManagerDidChangeNotification), object: nil) } private func updateFont() { if let font = self.preferredFontManager?.preferredFont(forTextStyle: self.textStyle, sizeCategory: self.sizeCategory) { self.font = font } else { self.font = UIFont.preferredFont(forTextStyle: self.textStyle) } } @objc fileprivate func preferredFontManagerDidChange(notification: Notification) { guard let object = notification.object as? [String: Any] else { return } let preferredFontManager = object[PreferredFontManagerObjectKey] as? PreferredFontManager let textStyle = object[PreferredFontManagerTextStyleKey] as? UIFont.TextStyle if preferredFontManager == self.preferredFontManager && textStyle == self.textStyle { self.updateFont() } } @objc fileprivate func contentSizeCategoryDidChange(notification: Notification) { if let object = notification.object as? [String: Any] { if let sizeCategory = object[UIContentSizeCategory.newValueUserInfoKey] as? UIContentSizeCategory { self.lastSizeCategory = sizeCategory } } self.updateFont() } }
mit
fa198233297bfa89326b60180fb49fd9
34.884956
127
0.674723
5.107053
false
false
false
false
Silent-Fred/iOSFrontendMentalist
Mentalist/TableViewController.swift
1
1783
// // TableViewController.swift // Mentalist // // Created by Michael Kühweg on 04.03.17. // Copyright © 2017 Michael Kühweg. All rights reserved. // import Foundation import UIKit class TableViewController: UITableViewController { var nextMove = NextMove() override func viewDidLoad() { self.navigationItem.title = "Rating" } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return nextMove.currentEvaluation.count } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "jumpToCelebritiesWithRating" { let celebritiesWithRatingController = segue.destination as! CelebritiesWithRatingTableViewController celebritiesWithRatingController.rating = nextMove.currentEvaluation[(self.tableView.indexPathForSelectedRow?.row)!] } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ratingCell", for: indexPath) let rating = nextMove.currentEvaluation[indexPath.row] cell.textLabel?.text = String("\(rating.points) Punkte") let celebrityText = rating.numberOfEntitiesThatHaveThisEvaluationStatus == 1 ? "Persönlichkeit" : "Persönlichkeiten" cell.detailTextLabel?.text = String("\(rating.numberOfEntitiesThatHaveThisEvaluationStatus) \(celebrityText) mit diesem Rating") cell.percentageArc(percent: rating.percentOfMax, drawnInColor: self.view.tintColor) return cell } }
bsd-2-clause
a16a2e1b851a02673ec2b9a63d26e60e
35.285714
136
0.69685
4.65445
false
false
false
false
natecook1000/swift
test/SILGen/init_ref_delegation.swift
2
8626
// RUN: %target-swift-emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s struct X { } // Initializer delegation within a struct. struct S { // CHECK-LABEL: sil hidden @$S19init_ref_delegation1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> S { init() { // CHECK: bb0([[SELF_META:%[0-9]+]] : @trivial $@thin S.Type): // CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var S } // CHECK-NEXT: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK-NEXT: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK-NEXT: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X_CTOR:%[0-9]+]] = function_ref @$S19init_ref_delegation1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK-NEXT: [[X:%[0-9]+]] = apply [[X_CTOR]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[S_DELEG_INIT:%[0-9]+]] = function_ref @$S19init_ref_delegation1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (X, @thin S.Type) -> S // CHECK-NEXT: [[REPLACEMENT_SELF:%[0-9]+]] = apply [[S_DELEG_INIT]]([[X]], [[SELF_META]]) : $@convention(method) (X, @thin S.Type) -> S self.init(x: X()) // CHECK-NEXT: assign [[REPLACEMENT_SELF]] to [[PB]] : $*S // CHECK-NEXT: [[SELF_BOX1:%[0-9]+]] = load [trivial] [[PB]] : $*S // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] : ${ var S } // CHECK-NEXT: return [[SELF_BOX1]] : $S } init(x: X) { } } // Initializer delegation within an enum enum E { // We don't want the enum to be uninhabited case Foo // CHECK-LABEL: sil hidden @$S19init_ref_delegation1EO{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin E.Type) -> E init() { // CHECK: bb0([[E_META:%[0-9]+]] : @trivial $@thin E.Type): // CHECK: [[E_BOX:%[0-9]+]] = alloc_box ${ var E } // CHECK: [[MARKED_E_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[E_BOX]] // CHECK: [[PB:%.*]] = project_box [[MARKED_E_BOX]] // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[E_DELEG_INIT:%[0-9]+]] = function_ref @$S19init_ref_delegation1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK: [[X:%[0-9]+]] = apply [[E_DELEG_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_INIT:%[0-9]+]] = function_ref @$S19init_ref_delegation1EO{{[_0-9a-zA-Z]*}}fC : $@convention(method) (X, @thin E.Type) -> E // CHECK: [[S:%[0-9]+]] = apply [[X_INIT]]([[X]], [[E_META]]) : $@convention(method) (X, @thin E.Type) -> E // CHECK: assign [[S:%[0-9]+]] to [[PB]] : $*E // CHECK: [[E_BOX1:%[0-9]+]] = load [trivial] [[PB]] : $*E self.init(x: X()) // CHECK: destroy_value [[MARKED_E_BOX]] : ${ var E } // CHECK: return [[E_BOX1:%[0-9]+]] : $E } init(x: X) { } } // Initializer delegation to a generic initializer struct S2 { // CHECK-LABEL: sil hidden @$S19init_ref_delegation2S2V{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S2.Type) -> S2 init() { // CHECK: bb0([[S2_META:%[0-9]+]] : @trivial $@thin S2.Type): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var S2 } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X_INIT:%[0-9]+]] = function_ref @$S19init_ref_delegation1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X // CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_BOX:%[0-9]+]] = alloc_stack $X // CHECK: store [[X]] to [trivial] [[X_BOX]] : $*X // CHECK: [[S2_DELEG_INIT:%[0-9]+]] = function_ref @$S19init_ref_delegation2S2V{{[_0-9a-zA-Z]*}}fC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2 // CHECK: [[SELF_BOX1:%[0-9]+]] = apply [[S2_DELEG_INIT]]<X>([[X_BOX]], [[S2_META]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2 // CHECK: dealloc_stack [[X_BOX]] : $*X // CHECK: assign [[SELF_BOX1]] to [[PB]] : $*S2 // CHECK: [[SELF_BOX4:%[0-9]+]] = load [trivial] [[PB]] : $*S2 self.init(t: X()) // CHECK: destroy_value [[MARKED_SELF_BOX]] : ${ var S2 } // CHECK: return [[SELF_BOX4]] : $S2 } init<T>(t: T) { } } class C1 { var ivar: X // CHECK-LABEL: sil hidden @$S19init_ref_delegation2C1C{{[_0-9a-zA-Z]*}}fc : $@convention(method) (X, @owned C1) -> @owned C1 convenience init(x: X) { // CHECK: bb0([[X:%[0-9]+]] : @trivial $X, [[ORIG_SELF:%[0-9]+]] : @owned $C1): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var C1 } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[ORIG_SELF]] to [init] [[PB]] : $*C1 // CHECK: [[SELF_FROM_BOX:%[0-9]+]] = load [take] [[PB]] : $*C1 // CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF_FROM_BOX]] : $C1, #C1.init!initializer.1 : (C1.Type) -> (X, X) -> C1, $@convention(method) (X, X, @owned C1) -> @owned C1 // CHECK: [[SELFP:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF_FROM_BOX]]) : $@convention(method) (X, X, @owned C1) -> @owned C1 // CHECK: store [[SELFP]] to [init] [[PB]] : $*C1 // CHECK: [[SELFP:%[0-9]+]] = load [copy] [[PB]] : $*C1 // CHECK: destroy_value [[MARKED_SELF_BOX]] : ${ var C1 } // CHECK: return [[SELFP]] : $C1 self.init(x1: x, x2: x) } init(x1: X, x2: X) { ivar = x1 } } @objc class C2 { var ivar: X // CHECK-LABEL: sil hidden @$S19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fc : $@convention(method) (X, @owned C2) -> @owned C2 convenience init(x: X) { // CHECK: bb0([[X:%[0-9]+]] : @trivial $X, [[ORIG_SELF:%[0-9]+]] : @owned $C2): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var C2 } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_SELF:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[ORIG_SELF]] to [init] [[PB_SELF]] : $*C2 // CHECK: [[SELF:%[0-9]+]] = load [take] [[PB_SELF]] : $*C2 // CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF]] : $C2, #C2.init!initializer.1 : (C2.Type) -> (X, X) -> C2, $@convention(method) (X, X, @owned C2) -> @owned C2 // CHECK: [[REPLACE_SELF:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF]]) : $@convention(method) (X, X, @owned C2) -> @owned C2 // CHECK: store [[REPLACE_SELF]] to [init] [[PB_SELF]] : $*C2 // CHECK: [[VAR_15:%[0-9]+]] = load [copy] [[PB_SELF]] : $*C2 // CHECK: destroy_value [[MARKED_SELF_BOX]] : ${ var C2 } // CHECK: return [[VAR_15]] : $C2 self.init(x1: x, x2: x) // CHECK-NOT: sil hidden @$S19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (X, @owned C2) -> @owned C2 { } // CHECK-LABEL: sil hidden @$S19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fC : $@convention(method) (X, X, @thick C2.Type) -> @owned C2 { // CHECK-NOT: sil @$S19init_ref_delegation2C2C{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (X, X, @owned C2) -> @owned C2 { init(x1: X, x2: X) { ivar = x1 } } var x: X = X() class C3 { var i: Int = 5 // CHECK-LABEL: sil hidden @$S19init_ref_delegation2C3C{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned C3) -> @owned C3 convenience init() { // CHECK: mark_uninitialized [delegatingself] // CHECK-NOT: integer_literal // CHECK: class_method [[SELF:%[0-9]+]] : $C3, #C3.init!initializer.1 : (C3.Type) -> (X) -> C3, $@convention(method) (X, @owned C3) -> @owned C3 // CHECK-NOT: integer_literal // CHECK: return self.init(x: x) } init(x: X) { } } // Initializer delegation from a constructor defined in an extension. class C4 { } extension C4 { convenience init(x1: X) { self.init() } // CHECK: sil hidden @$S19init_ref_delegation2C4C{{[_0-9a-zA-Z]*}}fc // CHECK: [[PEER:%[0-9]+]] = function_ref @$S19init_ref_delegation2C4C{{[_0-9a-zA-Z]*}}fc // CHECK: apply [[PEER]]([[X:%[0-9]+]], [[OBJ:%[0-9]+]]) convenience init(x2: X) { self.init(x1: x2) } } // Initializer delegation to a constructor defined in a protocol extension. protocol Pb { init() } extension Pb { init(d: Int) { } } class Sn : Pb { required init() { } convenience init(d3: Int) { self.init(d: d3) } } // Same as above but for a value type. struct Cs : Pb { init() { } init(d3: Int) { self.init(d: d3) } }
apache-2.0
dbbfcff7775f5f2cb93dd2f15d724826
43.215385
182
0.539782
2.710468
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/PeerMediaCollectionInterfaceState.swift
1
5478
// // PeerMediaCollectionInterfaceState.swift // Telegram-Mac // // Created by keepcoder on 26/10/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import TelegramCore import Postbox import TGUIKit final class PeerMediaCollectionInteraction : InterfaceObserver { private(set) var interfaceState:PeerMediaCollectionInterfaceState func update(animated:Bool = false, _ f:(PeerMediaCollectionInterfaceState)->PeerMediaCollectionInterfaceState)->Void { let oldValue = interfaceState interfaceState = f(interfaceState) if oldValue != interfaceState { notifyObservers(value: interfaceState, oldValue:oldValue, animated: animated) } } var deleteSelected:()->Void = {} var forwardSelected:()->Void = {} override init() { self.interfaceState = PeerMediaCollectionInterfaceState() } } enum PeerMediaCollectionMode : Int32 { case members = -2 case photoOrVideo = -1 case file = 0 case webpage = 1 case music = 2 case voice = 3 case commonGroups = 4 case gifs = 5 var tagsValue:MessageTags { switch self { case .photoOrVideo: return .photoOrVideo case .file: return .file case .music: return .music case .webpage: return .webPage case .voice: return .voiceOrInstantVideo case .members: return [] case .commonGroups: return [] case .gifs: return .gif } } } struct PeerMediaCollectionInterfaceState: Equatable { let peer: Peer? let selectionState: ChatInterfaceSelectionState? let mode: PeerMediaCollectionMode let selectingMode: Bool init() { self.peer = nil self.selectionState = nil self.mode = .photoOrVideo self.selectingMode = false } init(peer: Peer?, selectionState: ChatInterfaceSelectionState?, mode: PeerMediaCollectionMode, selectingMode: Bool) { self.peer = peer self.selectionState = selectionState self.mode = mode self.selectingMode = selectingMode } static func ==(lhs: PeerMediaCollectionInterfaceState, rhs: PeerMediaCollectionInterfaceState) -> Bool { if let peer = lhs.peer { if rhs.peer == nil || !peer.isEqual(rhs.peer!) { return false } } else if let _ = rhs.peer { return false } if lhs.selectionState != rhs.selectionState { return false } if lhs.mode != rhs.mode { return false } if lhs.selectingMode != rhs.selectingMode { return false } return true } func isSelectedMessageId(_ messageId:MessageId) -> Bool { if let selectionState = selectionState { return selectionState.selectedIds.contains(messageId) } return false } func withUpdatedSelectedMessage(_ messageId: MessageId) -> PeerMediaCollectionInterfaceState { var selectedIds = Set<MessageId>() if let selectionState = self.selectionState { selectedIds.formUnion(selectionState.selectedIds) } selectedIds.insert(messageId) return PeerMediaCollectionInterfaceState(peer: self.peer, selectionState: ChatInterfaceSelectionState(selectedIds: selectedIds, lastSelectedId: nil), mode: self.mode, selectingMode: self.selectingMode) } func withToggledSelectedMessage(_ messageId: MessageId) -> PeerMediaCollectionInterfaceState { var selectedIds = Set<MessageId>() if let selectionState = self.selectionState { selectedIds.formUnion(selectionState.selectedIds) } if selectedIds.contains(messageId) { let _ = selectedIds.remove(messageId) } else { selectedIds.insert(messageId) } return PeerMediaCollectionInterfaceState(peer: self.peer, selectionState: ChatInterfaceSelectionState(selectedIds: selectedIds, lastSelectedId: nil), mode: self.mode, selectingMode: self.selectingMode) } func withSelectionState() -> PeerMediaCollectionInterfaceState { return PeerMediaCollectionInterfaceState(peer: self.peer, selectionState: self.selectionState ?? ChatInterfaceSelectionState(selectedIds: Set(), lastSelectedId: nil), mode: self.mode, selectingMode: true) } func withoutSelectionState() -> PeerMediaCollectionInterfaceState { return PeerMediaCollectionInterfaceState(peer: self.peer, selectionState: nil, mode: self.mode, selectingMode: false) } func withUpdatedPeer(_ peer: Peer?) -> PeerMediaCollectionInterfaceState { return PeerMediaCollectionInterfaceState(peer: peer, selectionState: self.selectionState, mode: self.mode, selectingMode: self.selectingMode) } func withToggledSelectingMode() -> PeerMediaCollectionInterfaceState { return PeerMediaCollectionInterfaceState(peer: self.peer, selectionState: self.selectionState, mode: self.mode, selectingMode: !self.selectingMode) } func withMode(_ mode: PeerMediaCollectionMode) -> PeerMediaCollectionInterfaceState { return PeerMediaCollectionInterfaceState(peer: self.peer, selectionState: self.selectionState, mode: mode, selectingMode: self.selectingMode) } }
gpl-2.0
5cb8b8bb05d6bf3da580b34b6a6b9482
33.018634
212
0.659485
4.868444
false
false
false
false
martinschilliger/SwissGrid
Pods/Alamofire/Source/Result.swift
2
10996
// // Result.swift // // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Used to represent whether a request was successful or encountered an error. /// /// - success: The request and all post processing operations were successful resulting in the serialization of the /// provided associated value. /// /// - failure: The request encountered an error resulting in a failure. The associated values are the original data /// provided by the server as well as the error that caused the failure. public enum Result<Value> { case success(Value) case failure(Error) /// Returns `true` if the result is a success, `false` otherwise. public var isSuccess: Bool { switch self { case .success: return true case .failure: return false } } /// Returns `true` if the result is a failure, `false` otherwise. public var isFailure: Bool { return !isSuccess } /// Returns the associated value if the result is a success, `nil` otherwise. public var value: Value? { switch self { case let .success(value): return value case .failure: return nil } } /// Returns the associated error value if the result is a failure, `nil` otherwise. public var error: Error? { switch self { case .success: return nil case let .failure(error): return error } } } // MARK: - CustomStringConvertible extension Result: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { switch self { case .success: return "SUCCESS" case .failure: return "FAILURE" } } } // MARK: - CustomDebugStringConvertible extension Result: CustomDebugStringConvertible { /// The debug textual representation used when written to an output stream, which includes whether the result was a /// success or failure in addition to the value or error. public var debugDescription: String { switch self { case let .success(value): return "SUCCESS: \(value)" case let .failure(error): return "FAILURE: \(error)" } } } // MARK: - Functional APIs extension Result { /// Creates a `Result` instance from the result of a closure. /// /// A failure result is created when the closure throws, and a success result is created when the closure /// succeeds without throwing an error. /// /// func someString() throws -> String { ... } /// /// let result = Result(value: { /// return try someString() /// }) /// /// // The type of result is Result<String> /// /// The trailing closure syntax is also supported: /// /// let result = Result { try someString() } /// /// - parameter value: The closure to execute and create the result for. public init(value: () throws -> Value) { do { self = try .success(value()) } catch { self = .failure(error) } } /// Returns the success value, or throws the failure error. /// /// let possibleString: Result<String> = .success("success") /// try print(possibleString.unwrap()) /// // Prints "success" /// /// let noString: Result<String> = .failure(error) /// try print(noString.unwrap()) /// // Throws error public func unwrap() throws -> Value { switch self { case let .success(value): return value case let .failure(error): throw error } } /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: Result<Data> = .success(Data()) /// let possibleInt = possibleData.map { $0.count } /// try print(possibleInt.unwrap()) /// // Prints "0" /// /// let noData: Result<Data> = .failure(error) /// let noInt = noData.map { $0.count } /// try print(noInt.unwrap()) /// // Throws error /// /// - parameter transform: A closure that takes the success value of the `Result` instance. /// /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the /// same failure. public func map<T>(_ transform: (Value) -> T) -> Result<T> { switch self { case let .success(value): return .success(transform(value)) case let .failure(error): return .failure(error) } } /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. /// /// Use the `flatMap` method with a closure that may throw an error. For example: /// /// let possibleData: Result<Data> = .success(Data(...)) /// let possibleObject = possibleData.flatMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance. /// /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the /// same failure. public func flatMap<T>(_ transform: (Value) throws -> T) -> Result<T> { switch self { case let .success(value): do { return try .success(transform(value)) } catch { return .failure(error) } case let .failure(error): return .failure(error) } } /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. /// /// Use the `mapError` function with a closure that does not throw. For example: /// /// let possibleData: Result<Data> = .failure(someError) /// let withMyError: Result<Data> = possibleData.mapError { MyError.error($0) } /// /// - Parameter transform: A closure that takes the error of the instance. /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns /// the same instance. public func mapError<T: Error>(_ transform: (Error) -> T) -> Result { switch self { case let .failure(error): return .failure(transform(error)) case .success: return self } } /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. /// /// Use the `flatMapError` function with a closure that may throw an error. For example: /// /// let possibleData: Result<Data> = .success(Data(...)) /// let possibleObject = possibleData.flatMapError { /// try someFailableFunction(taking: $0) /// } /// /// - Parameter transform: A throwing closure that takes the error of the instance. /// /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns /// the same instance. public func flatMapError<T: Error>(_ transform: (Error) throws -> T) -> Result { switch self { case let .failure(error): do { return try .failure(transform(error)) } catch { return .failure(error) } case .success: return self } } /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. /// /// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance. /// /// - Parameter closure: A closure that takes the success value of this instance. /// - Returns: This `Result` instance, unmodified. @discardableResult public func withValue(_ closure: (Value) -> Void) -> Result { if case let .success(value) = self { closure(value) } return self } /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. /// /// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance. /// /// - Parameter closure: A closure that takes the success value of this instance. /// - Returns: This `Result` instance, unmodified. @discardableResult public func withError(_ closure: (Error) -> Void) -> Result { if case let .failure(error) = self { closure(error) } return self } /// Evaluates the specified closure when the `Result` is a success. /// /// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance. /// /// - Parameter closure: A `Void` closure. /// - Returns: This `Result` instance, unmodified. @discardableResult public func ifSuccess(_ closure: () -> Void) -> Result { if isSuccess { closure() } return self } /// Evaluates the specified closure when the `Result` is a failure. /// /// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance. /// /// - Parameter closure: A `Void` closure. /// - Returns: This `Result` instance, unmodified. @discardableResult public func ifFailure(_ closure: () -> Void) -> Result { if isFailure { closure() } return self } }
mit
853735bae8b867d26a9c207c6478e323
35.653333
119
0.611677
4.598913
false
false
false
false
wfilleman/ArraysPlayground
Arrays.playground/Pages/Array.filter Intro.xcplaygroundpage/Contents.swift
1
564
//: [Previous](@previous) //: ## Swift Array.filter Intro //: .filter operates over an array to keep elements based on a condition that resolves to true. import Foundation let siblings = ["Bobby", "Mary", "Lisa", "Johnny"] let girlsOnly = siblings.filter { firstName -> Bool in return (firstName == "Mary" || firstName == "Lisa") } //: Exercise: Create an array using .filter on "siblings" that returns all names longer than 4 characters. IE: //: * Bobby //: * Johnny // START Exercise // REPLACE WITH YOUR CODE // END Exercise code //: [Next](@next)
apache-2.0
efa4498cf74d040ffb955d2d62d7dbe6
22.5
110
0.673759
3.735099
false
false
false
false
huangboju/QMUI.swift
QMUI.swift/QMUIKit/UIComponents/QMUIImagePreviewView.swift
1
14021
// // QMUIImagePreviewView.swift // QMUI.swift // // Created by 黄伯驹 on 2017/7/10. // Copyright © 2017年 伯驹 黄. All rights reserved. // @objc enum QMUIImagePreviewMediaType: UInt { case image = 0 case livePhoto case video case others } @objc protocol QMUIImagePreviewViewDelegate: QMUIZoomImageViewDelegate { @objc func numberOfImages(in imagePreviewView: QMUIImagePreviewView) -> Int @objc func imagePreviewView(_ imagePreviewView: QMUIImagePreviewView, renderZoomImageView zoomImageView: QMUIZoomImageView, at index: Int) // 返回要展示的媒体资源的类型(图片、live photo、视频),如果不实现此方法,则 QMUIImagePreviewView 将无法选择最合适的 cell 来复用从而略微增大系统开销 @objc optional func imagePreviewView(_ imagePreviewView: QMUIImagePreviewView, assetTypeAt index: Int) -> QMUIImagePreviewMediaType /** * 当左右的滚动停止时会触发这个方法 * @param imagePreviewView 当前预览的 QMUIImagePreviewView * @param index 当前滚动到的图片所在的索引 */ @objc optional func imagePreviewView(_ imagePreviewView: QMUIImagePreviewView, didScrollToIndex: Int) /** * 在滚动过程中,如果某一张图片的边缘(左/右)经过预览控件的中心点时,就会触发这个方法 * @param imagePreviewView 当前预览的 QMUIImagePreviewView * @param index 当前滚动到的图片所在的索引 */ @objc optional func imagePreviewView(_ imagePreviewView: QMUIImagePreviewView, willScrollHalfTo index: Int) } /** * 查看图片的控件,支持横向滚动、放大缩小、loading 及错误语展示,内部使用 UICollectionView 实现横向滚动及 cell 复用,因此与其他普通的 UICollectionView 一样,也可使用 reloadData、collectionViewLayout 等常用方法。 * * 使用方式: * * 1. 使用 initWithFrame: 或 init 方法初始化。 * 2. 设置 delegate。 * 3. 在 delegate 的 numberOfImagesInImagePreviewView: 方法里返回图片总数。 * 4. 在 delegate 的 imagePreviewView:renderZoomImageView:atIndex: 方法里为 zoomImageView.image 设置图片,如果需要,也可调用 [zoomImageView showLoading] 等方法来显示 loading。 * 5. 由于 QMUIImagePreviewViewDelegate 继承自 QMUIZoomImageViewDelegate,所以若需要响应单击、双击、长按事件,请实现 QMUIZoomImageViewDelegate 里的对应方法。 * 6. 若需要从指定的某一张图片开始查看,可使用 currentImageIndex 属性。 * * @see QMUIImagePreviewViewController */ class QMUIImagePreviewView: UIView { weak var delegate: QMUIImagePreviewViewDelegate? private(set) var collectionView: UICollectionView! private(set) var collectionViewLayout: QMUICollectionViewPagingLayout! /// 获取当前正在查看的图片 index,也可强制将图片滚动到指定的 index var currentImageIndex: Int { set { set(currentImageIndex: newValue) } get { return _currentImageIndex } } private var _currentImageIndex = 0 /// 每一页里的 loading 的颜色,默认为 UIColorWhite var loadingColor: UIColor? = UIColorWhite { didSet { let isLoadingColorChanged = loadingColor != nil && loadingColor != oldValue if isLoadingColorChanged { collectionView.reloadItems(at: collectionView.indexPathsForVisibleItems) } } } private var isChangingCollectionViewBounds = false private var previousIndexWhenScrolling: CGFloat = 0 private let kLivePhotoCellIdentifier = "livephoto" private let kVideoCellIdentifier = "video" private let kImageOrUnknownCellIdentifier = "imageorunknown" override init(frame: CGRect) { super.init(frame: frame) didInitialized(with: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) didInitialized(with: .zero) } private func didInitialized(with frame: CGRect) { collectionViewLayout = QMUICollectionViewPagingLayout(with: .default) collectionViewLayout.allowsMultipleItemScroll = false collectionView = UICollectionView(frame: frame.size.rect, collectionViewLayout: collectionViewLayout) collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = UIColorClear collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.scrollsToTop = false collectionView.delaysContentTouches = false collectionView.decelerationRate = UIScrollView.DecelerationRate.fast if #available(iOS 11, *) { collectionView.contentInsetAdjustmentBehavior = .never } collectionView.register(QMUIImagePreviewCell.self, forCellWithReuseIdentifier: kImageOrUnknownCellIdentifier) collectionView.register(QMUIImagePreviewCell.self, forCellWithReuseIdentifier: kVideoCellIdentifier) collectionView.register(QMUIImagePreviewCell.self, forCellWithReuseIdentifier: kLivePhotoCellIdentifier) addSubview(collectionView) } override func layoutSubviews() { super.layoutSubviews() let isCollectionViewSizeChanged = collectionView.bounds.size != bounds.size if isCollectionViewSizeChanged { isChangingCollectionViewBounds = true // 必须先 invalidateLayout,再更新 collectionView.frame,否则横竖屏旋转前后的图片不一致(因为 scrollViewDidScroll: 时 contentSize、contentOffset 那些是错的) collectionViewLayout.invalidateLayout() collectionView.frame = bounds collectionView.scrollToItem(at: IndexPath(row: currentImageIndex, section: 0), at: .centeredHorizontally, animated: false) isChangingCollectionViewBounds = false } } func set(currentImageIndex: Int, animated: Bool = false) { _currentImageIndex = currentImageIndex collectionView.reloadData() if currentImageIndex < collectionView.numberOfItems(inSection: 0) { collectionView.scrollToItem(at: IndexPath(row: currentImageIndex, section: 0), at: .centeredHorizontally, animated: animated) } else { // dataSource 里的图片数量和当前 View 层的图片数量不匹配 print("\(type(of: self)) \(#function),collectionView.numberOfItems = \(collectionView.numberOfItems(inSection: 0)), collectionViewDataSource.numberOfItems = \(collectionView.dataSource?.numberOfSections?(in: collectionView) ?? 0), currentImageIndex = \(currentImageIndex)") } } } extension QMUIImagePreviewView: UICollectionViewDataSource { func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int { return delegate?.numberOfImages(in: self) ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var identifier = kImageOrUnknownCellIdentifier if let type = delegate?.imagePreviewView?(self, assetTypeAt: indexPath.item) { if type == .livePhoto { identifier = kLivePhotoCellIdentifier } else if type == .video { identifier = kVideoCellIdentifier } } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as? QMUIImagePreviewCell let zoomView = cell?.zoomImageView if let loadingView = zoomView?.emptyView.loadingView as? UIActivityIndicatorView { loadingView.color = loadingColor } zoomView?.cloudProgressView?.tintColor = loadingColor zoomView?.cloudDownloadRetryButton?.tintColor = loadingColor zoomView?.delegate = self // 因为 cell 复用的问题,很可能此时会显示一张错误的图片,因此这里要清空所有图片的显示 zoomView?.image = nil if #available(iOS 9.1, *) { zoomView?.livePhoto = nil } delegate?.imagePreviewView(self, renderZoomImageView: zoomView!, at: indexPath.item) return cell ?? QMUIImagePreviewCell() } } extension QMUIImagePreviewView: UICollectionViewDelegateFlowLayout { func collectionView(_: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt _: IndexPath) { let previewCell = cell as? QMUIImagePreviewCell previewCell?.zoomImageView.revertZooming() } func collectionView(_: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt _: IndexPath) { let previewCell = cell as? QMUIImagePreviewCell previewCell?.zoomImageView.endPlayingVideo() } func collectionView(_ collectionView: UICollectionView, layout _: UICollectionViewLayout, sizeForItemAt _: IndexPath) -> CGSize { return collectionView.bounds.size } // MARK: - UIScrollViewDelegate func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView != collectionView { return } // 当前滚动到的页数 delegate?.imagePreviewView?(self, didScrollToIndex: currentImageIndex) } func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView != collectionView { return } if isChangingCollectionViewBounds { return } let pageWidth = collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: IndexPath(row: 0, section: 0)).width let pageHorizontalMargin = collectionViewLayout.minimumLineSpacing let contentOffsetX = collectionView.contentOffset.x var index = contentOffsetX / (pageWidth + pageHorizontalMargin) // 在滑动过临界点的那一次才去调用 delegate,避免过于频繁的调用 let isFirstDidScroll = previousIndexWhenScrolling == 0 let turnPageToRight = betweenOrEqual(previousIndexWhenScrolling, floor(index) + 0.5, index) let turnPageToLeft = betweenOrEqual(index, floor(index) + 0.5, previousIndexWhenScrolling) if !isFirstDidScroll && (turnPageToRight || turnPageToLeft) { index = round(index) if 0 <= index && index < CGFloat(collectionView.numberOfItems(inSection: 0)) { // 不调用 setter,避免又走一次 scrollToItem _currentImageIndex = Int(index) delegate?.imagePreviewView?(self, willScrollHalfTo: Int(index)) } } previousIndexWhenScrolling = index } } extension QMUIImagePreviewView: QMUIZoomImageViewDelegate { /** * 获取某个 QMUIZoomImageView 所对应的 index * @return zoomImageView 对应的 index,若当前的 zoomImageView 不可见,会返回 0 */ func index(for zoomImageView: QMUIZoomImageView) -> Int { if let cell = zoomImageView.superview?.superview as? QMUIImagePreviewCell { return collectionView.indexPath(for: cell)?.item ?? 0 } else { assert(false, "尝试通过 \(#function) 获取 QMUIZoomImageView 所在的 index,但找不到 QMUIZoomImageView 所在的 cell,index 获取失败。\(zoomImageView)") } return Int.max } /** * 获取某个 index 对应的 zoomImageView * @return 指定的 index 所在的 zoomImageView,若该 index 对应的图片当前不可见(不处于可视区域),则返回 nil */ func zoomImageView(at index: Int) -> QMUIZoomImageView? { let cell = collectionView.cellForItem(at: IndexPath(row: index, section: 0)) as? QMUIImagePreviewCell return cell?.zoomImageView } private func checkIfDelegateMissing() { #if DEBUG // TODO: // NSObject.qmui_enumerateProtocolMethods(ptc: Protocol(QMUIZoomImageViewDelegate), using: { selector in // if !responds(to: selector) { // assert(false, "\(type(of: self)) 需要响应 \(QMUIZoomImageViewDelegate) 的方法 -\(selector)") // } // }) #endif } func singleTouch(in zoomingImageView: QMUIZoomImageView, location: CGPoint) { checkIfDelegateMissing() delegate?.singleTouch?(in: zoomingImageView, location: location) } func doubleTouch(in zoomingImageView: QMUIZoomImageView, location: CGPoint) { checkIfDelegateMissing() delegate?.doubleTouch?(in: zoomingImageView, location: location) } func longPress(in zoomingImageView: QMUIZoomImageView) { checkIfDelegateMissing() delegate?.longPress?(in: zoomingImageView) } func zoomImageView(_ imageView: QMUIZoomImageView, didHideVideoToolbar didHide: Bool) { checkIfDelegateMissing() delegate?.zoomImageView?(imageView, didHideVideoToolbar: didHide) } func enabledZoomView(in zoomImageView: QMUIZoomImageView) -> Bool { checkIfDelegateMissing() return delegate?.enabledZoomView?(in: zoomImageView) ?? true } func didTouchICloudRetryButton(in zoomImageView: QMUIZoomImageView) { checkIfDelegateMissing() delegate?.didTouchICloudRetryButton?(in: zoomImageView) } } fileprivate class QMUIImagePreviewCell: UICollectionViewCell { fileprivate var zoomImageView: QMUIZoomImageView! override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColorClear zoomImageView = QMUIZoomImageView() contentView.addSubview(zoomImageView) } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() zoomImageView.frame = contentView.bounds } }
mit
dd4057f2afb5ba13234f18fe5f52a521
38.247706
285
0.693782
4.941856
false
false
false
false
ruter/Strap-in-Swift
StormViewer/StormViewer/DetailViewController.swift
1
1553
// // DetailViewController.swift // StormViewer // // Created by Ruter on 16/4/12. // Copyright © 2016年 Ruter. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var detailImageView: UIImageView! var didTapped = false var detailItem: String? { didSet { // Update the view. self.configureView() } } func configureView() { // Update the user interface for the detail item. if let detail = self.detailItem { self.title = detail if let imageView = self.detailImageView { imageView.image = UIImage(named: detail) } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))) self.view.addGestureRecognizer(tapGestureRecognizer) } func handleTap(sender: UITapGestureRecognizer) { if sender.state == .Ended { if didTapped { didTapped = false self.view.backgroundColor = UIColor.whiteColor() navigationController?.navigationBarHidden = false } else { didTapped = true self.view.backgroundColor = UIColor.blackColor() navigationController?.navigationBarHidden = true } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
a42c65fc1ae2c8d3801be888ea9f25d3
23.21875
101
0.661935
4.936306
false
false
false
false
milankamilya/DoupQueue
Example/Tests/Tests.swift
1
2462
// https://github.com/Quick/Quick import Quick import Nimble import DoupQueue class TableOfContentsSpec: QuickSpec { override func spec() { // 1. Download queue test describe("Download queue test"){ var downloadCompletionIndex = -1 it("1st Download Asynchronous", closure: { waitUntil(timeout: 180, action: { (done) in DoupQueueManager.sharedManager.pushToDownloadQueue("http://cdn.wccftech.com/wp-content/uploads/2015/06/os-x-10.11-wallpaper.jpg", progressHandler: { (percentage) in downloadCompletionIndex = 0 }) { (location, error) in expect("0") == "\(downloadCompletionIndex)" done() } }) }) it("2nd Download Asynchronous", closure: { waitUntil(timeout: 180, action: { (done) in DoupQueueManager.sharedManager.pushToDownloadQueue("http://www.webextensionline.com/wp-content/uploads/Natural-summer-pink-flower.jpg", progressHandler: { (percentage) in downloadCompletionIndex = 1 }) { (location, error) in expect("1") == "\(downloadCompletionIndex)" done() } }) }) it("3rd Download Asynchronous", closure: { waitUntil(timeout: 180, action: { (done) in DoupQueueManager.sharedManager.pushToDownloadQueue("http://wallpaperswide.com/download/nature_221-wallpaper-2880x1800.jpg", progressHandler: { (percentage) in downloadCompletionIndex = 2 }) { (location, error) in expect("2") == "\(downloadCompletionIndex)" done() } }) }) } // 2. Upload queue test using uploading already downloaded data // 3. Simultaneous testing of download & upload testing. } }
mit
b8fdb9c7dabd9a57dfcbb4483c81d388
33.676056
190
0.444354
6.079012
false
true
false
false
DonMag/ScratchPad
Swift3/scratchy/XC8.playground/Pages/ArraySorting.xcplaygroundpage/Contents.swift
1
3581
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) //struct Objects { // var sectionName: String! // var sectionObjects: [Brands]! //} // //struct Brand { // var id: String! // var name: String! //} // // var sortedLetters = [String]() // var sortedBrands = [Brands]() // var objectBrands = [Objects]() // // //var allBrands: [Brands] = [ // Brands(id: "1", name: "Z Brand") // ] // //allBrands.append(Brands(id: "1", name: "C Brand")) //allBrands.append(Brands(id: "2", name: "L Brand")) //allBrands.append(Brands(id: "3", name: "M Brand")) //allBrands.append(Brands(id: "4", name: "F Brand")) //allBrands.append(Brands(id: "5", name: "D Brand")) //allBrands.append(Brands(id: "6", name: "A Brand")) //allBrands.append(Brands(id: "7", name: "C Brand")) //allBrands.append(Brands(id: "8", name: "C Brand")) //allBrands.append(Brands(id: "9", name: "C Brand")) //allBrands.append(Brands(id: "10", name: "C Brand")) //allBrands.append(Brands(id: "11", name: "C Brand")) //allBrands.append(Brands(id: "12", name: "C Brand")) //allBrands.append(Brands(id: "13", name: "C Brand")) //allBrands.append(Brands(id: "14", name: "C Brand")) // //objectBrands.append(Brands(id: "1", name: "C Brand")) struct Brand { var id: String! var name: String! } var aBrands: [Brand] = [ Brand(id: "8925", name: "Chrysler"), Brand(id: "8121", name: "Dodge"), Brand(id: "3943", name: "Jeep"), Brand(id: "2878", name: "Ram"), Brand(id: "1893", name: "Ford"), Brand(id: "9318", name: "Lincoln"), Brand(id: "1253", name: "Buick"), Brand(id: "4799", name: "Cadillac"), Brand(id: "2918", name: "Chevrolet"), Brand(id: "6603", name: "GMC"), Brand(id: "9743", name: "Tesla Motors"), Brand(id: "9429", name: "Hennessey"), Brand(id: "5028", name: "Acura"), Brand(id: "7276", name: "Honda"), Brand(id: "6929", name: "Toyota"), Brand(id: "1202", name: "Lexus"), Brand(id: "1901", name: "Mitsubishi"), Brand(id: "9199", name: "Suzuki"), Brand(id: "5902", name: "Mazda"), Brand(id: "8889", name: "Subaru"), Brand(id: "2805", name: "Scion"), Brand(id: "2415", name: "Ferrari"), Brand(id: "1157", name: "Maserati"), Brand(id: "1239", name: "Lamborghini"), Brand(id: "1938", name: "Lancia"), Brand(id: "9078", name: "Porsche"), Brand(id: "5786", name: "Saab"), Brand(id: "4728", name: "BMW"), Brand(id: "2341", name: "Mercedes-Benz"), Brand(id: "1232", name: "Volkswagon"), Brand(id: "9307", name: "Bugatti"), Brand(id: "2279", name: "Volvo") ] aBrands.sort(by: { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }) var sections : [(index: Int, length :Int, title: String)] = Array() var index = 0; for i in 0...aBrands.count - 1 { let commonPrefix = aBrands[i].name.commonPrefix(with: aBrands[index].name, options: .caseInsensitive) if commonPrefix.characters.count == 0 { let string = aBrands[index].name.uppercased(); let firstCharacter = string[string.startIndex] let title = "\(firstCharacter)" let newSection = (index: index, length: i - index, title: title) sections.append(newSection) index = i; } } print(sections) //var s = "Chrysler, Dodge, Jeep, Ram, Ford, Lincoln, Buick, Cadillac, Chevrolet, GMC, Tesla Motors, Hennessey, Acura, Honda, Toyota, Lexus, Mitsubishi, Suzuki, Mazda, Subaru, Scion, Ferrari, Maserati, Lamborghini, Lancia, Porsche, Saab, BMW, Mercedes-Benz, Volkswagon, Bugatti, Volvo" // //var a = s.components(separatedBy: ", ") // //for t in a { // let n = arc4random_uniform(8999) + 1000 // print("Brand(id: \"\(n)\", name: \"\(t)\"),") //}
mit
e41183ba21ba7ac4f5582cf68fe645cb
27.648
285
0.626082
2.608157
false
false
false
false
shiningdracon/YingLong2
Sources/DataForum.swift
2
21924
public struct YLDBbans { var id: UInt32 var username: String? var ip: String? var email: String? var message: String? var expire: UInt32? var ban_creator: UInt32 init(_ args: [String: Any]) { id = item(from: args["id"]) username = item(from: args["username"]) ip = item(from: args["ip"]) email = item(from: args["email"]) message = item(from: args["message"]) expire = item(from: args["expire"]) ban_creator = item(from: args["ban_creator"]) } } public struct YLDBcategories { var id: UInt32 var cat_name: String var disp_position: Int32 init(_ args: [String: Any]) { id = item(from: args["id"]) cat_name = item(from: args["cat_name"]) disp_position = item(from: args["disp_position"]) } } public struct YLDBcensoring { var id: UInt32 var search_for: String var replace_with: String init(_ args: [String: Any]) { id = item(from: args["id"]) search_for = item(from: args["search_for"]) replace_with = item(from: args["replace_with"]) } } public struct YLDBconfig { var conf_name: String var conf_value: String? init(_ args: [String: Any]) { conf_name = item(from: args["conf_name"]) conf_value = item(from: args["conf_value"]) } } public struct YLDBforum_perms { var group_id: Int32 var forum_id: Int32 var read_forum: Bool var post_replies: Bool var post_topics: Bool init(_ args: [String: Any]) { group_id = item(from: args["group_id"]) forum_id = item(from: args["forum_id"]) read_forum = item(from: args["read_forum"]) as Int8 == 0 ? false : true post_replies = item(from: args["post_replies"]) as Int8 == 0 ? false : true post_topics = item(from: args["post_topics"]) as Int8 == 0 ? false : true } } public struct YLDBforums { var id: UInt32 var forum_name: String var forum_desc: String? var redirect_url: String? var moderators: String? var num_topics: UInt32 var num_posts: UInt32 var last_post: UInt32? var last_post_id: UInt32? var last_poster: String? var sort_by: Bool var disp_position: Int32 var cat_id: UInt32 init(_ args: [String: Any]) { id = item(from: args["id"]) forum_name = item(from: args["forum_name"]) forum_desc = item(from: args["forum_desc"]) redirect_url = item(from: args["redirect_url"]) moderators = item(from: args["moderators"]) num_topics = item(from: args["num_topics"]) num_posts = item(from: args["num_posts"]) last_post = item(from: args["last_post"]) last_post_id = item(from: args["last_post_id"]) last_poster = item(from: args["last_poster"]) sort_by = item(from: args["sort_by"]) as Int8 == 0 ? false : true disp_position = item(from: args["disp_position"]) cat_id = item(from: args["cat_id"]) } } public struct YLDBgroups { var g_id: UInt32 var g_title: String var g_user_title: String? var g_promote_min_posts: UInt32 var g_promote_next_group: UInt32 var g_moderator: Bool var g_mod_edit_users: Bool var g_mod_rename_users: Bool var g_mod_change_passwords: Bool var g_mod_ban_users: Bool var g_mod_promote_users: Bool var g_read_board: Bool var g_view_users: Bool var g_post_replies: Bool var g_post_topics: Bool var g_edit_posts: Bool var g_delete_posts: Bool var g_delete_topics: Bool var g_post_links: Bool var g_set_title: Bool var g_search: Bool var g_search_users: Bool var g_send_email: Bool var g_post_flood: Int16 var g_search_flood: Int16 var g_email_flood: Int16 var g_report_flood: Int16 init(_ args: [String: Any]) { g_id = item(from: args["g_id"]) g_title = item(from: args["g_title"]) g_user_title = item(from: args["g_user_title"]) g_promote_min_posts = item(from: args["g_promote_min_posts"]) g_promote_next_group = item(from: args["g_promote_next_group"]) g_moderator = item(from: args["g_moderator"]) as Int8 == 0 ? false : true g_mod_edit_users = item(from: args["g_mod_edit_users"]) as Int8 == 0 ? false : true g_mod_rename_users = item(from: args["g_mod_rename_users"]) as Int8 == 0 ? false : true g_mod_change_passwords = item(from: args["g_mod_change_passwords"]) as Int8 == 0 ? false : true g_mod_ban_users = item(from: args["g_mod_ban_users"]) as Int8 == 0 ? false : true g_mod_promote_users = item(from: args["g_mod_promote_users"]) as Int8 == 0 ? false : true g_read_board = item(from: args["g_read_board"]) as Int8 == 0 ? false : true g_view_users = item(from: args["g_view_users"]) as Int8 == 0 ? false : true g_post_replies = item(from: args["g_post_replies"]) as Int8 == 0 ? false : true g_post_topics = item(from: args["g_post_topics"]) as Int8 == 0 ? false : true g_edit_posts = item(from: args["g_edit_posts"]) as Int8 == 0 ? false : true g_delete_posts = item(from: args["g_delete_posts"]) as Int8 == 0 ? false : true g_delete_topics = item(from: args["g_delete_topics"]) as Int8 == 0 ? false : true g_post_links = item(from: args["g_post_links"]) as Int8 == 0 ? false : true g_set_title = item(from: args["g_set_title"]) as Int8 == 0 ? false : true g_search = item(from: args["g_search"]) as Int8 == 0 ? false : true g_search_users = item(from: args["g_search_users"]) as Int8 == 0 ? false : true g_send_email = item(from: args["g_send_email"]) as Int8 == 0 ? false : true g_post_flood = item(from: args["g_post_flood"]) g_search_flood = item(from: args["g_search_flood"]) g_email_flood = item(from: args["g_email_flood"]) g_report_flood = item(from: args["g_report_flood"]) } } public struct YLDBonline { var user_id: UInt32 var ident: String var logged: UInt32 var idle: Bool var last_post: UInt32? var last_search: UInt32? init(_ args: [String: Any]) { user_id = item(from: args["user_id"]) ident = item(from: args["ident"]) logged = item(from: args["logged"]) idle = item(from: args["idle"]) as Int8 == 0 ? false : true last_post = item(from: args["last_post"]) last_search = item(from: args["last_search"]) } } public struct YLDBposts { var id: UInt32 var poster: String var poster_id: UInt32 var poster_ip: String? var poster_email: String? var message: String? var hide_smilies: Bool var posted: UInt32 var edited: UInt32? var edited_by: String? var topic_id: UInt32 init(_ args: [String: Any]) { id = item(from: args["id"]) poster = item(from: args["poster"]) poster_id = item(from: args["poster_id"]) poster_ip = item(from: args["poster_ip"]) poster_email = item(from: args["poster_email"]) message = item(from: args["message"]) hide_smilies = item(from: args["hide_smilies"]) as Int8 == 0 ? false : true posted = item(from: args["posted"]) edited = item(from: args["edited"]) edited_by = item(from: args["edited_by"]) topic_id = item(from: args["topic_id"]) } } public struct YLDBreports { var id: UInt32 var post_id: UInt32 var topic_id: UInt32 var forum_id: UInt32 var reported_by: UInt32 var created: UInt32 var message: String? var zapped: UInt32? var zapped_by: UInt32? init(_ args: [String: Any]) { id = item(from: args["id"]) post_id = item(from: args["post_id"]) topic_id = item(from: args["topic_id"]) forum_id = item(from: args["forum_id"]) reported_by = item(from: args["reported_by"]) created = item(from: args["created"]) message = item(from: args["message"]) zapped = item(from: args["zapped"]) zapped_by = item(from: args["zapped_by"]) } } public struct YLDBsearch_cache { var id: UInt32 var ident: String var search_data: String? init(_ args: [String: Any]) { id = item(from: args["id"]) ident = item(from: args["ident"]) search_data = item(from: args["search_data"]) } } public struct YLDBsearch_matches { var post_id: UInt32 var word_id: UInt32 var subject_match: Bool init(_ args: [String: Any]) { post_id = item(from: args["post_id"]) word_id = item(from: args["word_id"]) subject_match = item(from: args["subject_match"]) as Int8 == 0 ? false : true } } public struct YLDBsearch_words { var id: UInt32 var word: String init(_ args: [String: Any]) { id = item(from: args["id"]) word = item(from: args["word"]) } } public struct YLDBtopic_subscriptions { var user_id: UInt32 var topic_id: UInt32 init(_ args: [String: Any]) { user_id = item(from: args["user_id"]) topic_id = item(from: args["topic_id"]) } } public struct YLDBforum_subscriptions { var user_id: UInt32 var forum_id: UInt32 init(_ args: [String: Any]) { user_id = item(from: args["user_id"]) forum_id = item(from: args["forum_id"]) } } public struct YLDBtopics { var id: UInt32 var poster: String var subject: String var posted: UInt32 var first_post_id: UInt32 var last_post: UInt32 var last_post_id: UInt32 var last_poster: String? var num_views: UInt32 var num_replies: UInt32 var closed: Bool var sticky: Bool var moved_to: UInt32? var forum_id: UInt32 var special: Int32 init(_ args: [String: Any]) { id = item(from: args["id"]) poster = item(from: args["poster"]) subject = item(from: args["subject"]) posted = item(from: args["posted"]) first_post_id = item(from: args["first_post_id"]) last_post = item(from: args["last_post"]) last_post_id = item(from: args["last_post_id"]) last_poster = item(from: args["last_poster"]) num_views = item(from: args["num_views"]) num_replies = item(from: args["num_replies"]) closed = item(from: args["closed"]) as Int8 == 0 ? false : true sticky = item(from: args["sticky"]) as Int8 == 0 ? false : true moved_to = item(from: args["moved_to"]) forum_id = item(from: args["forum_id"]) special = item(from: args["special"]) } } public struct YLDBusers { var id: UInt32 var group_id: UInt32 var username: String var password: String var email: String var title: String? var realname: String? var url: String? var jabber: String? var icq: String? var msn: String? var aim: String? var yahoo: String? var location: String? var signature: String? var disp_topics: UInt8? var disp_posts: UInt8? var email_setting: Bool var notify_with_post: Bool var auto_notify: Bool var show_smilies: Bool var show_img: Bool var show_img_sig: Bool var show_avatars: Bool var show_sig: Bool var timezone: Float var dst: Float var time_format: Int8 var date_format: Int8 var language: String var style: String var num_posts: UInt32 var last_post: UInt32? var last_search: UInt32? var last_email_sent: UInt32? var last_report_sent: UInt32? var registered: UInt32 var registration_ip: String var last_visit: UInt32 var admin_note: String? var activate_string: String? var activate_key: String? init(_ args: [String: Any]) { id = item(from: args["id"]) group_id = item(from: args["group_id"]) username = item(from: args["username"]) password = item(from: args["password"]) email = item(from: args["email"]) title = item(from: args["title"]) realname = item(from: args["realname"]) url = item(from: args["url"]) jabber = item(from: args["jabber"]) icq = item(from: args["icq"]) msn = item(from: args["msn"]) aim = item(from: args["aim"]) yahoo = item(from: args["yahoo"]) location = item(from: args["location"]) signature = item(from: args["signature"]) disp_topics = item(from: args["disp_topics"]) disp_posts = item(from: args["disp_posts"]) email_setting = item(from: args["email_setting"]) as Int8 == 0 ? false : true notify_with_post = item(from: args["notify_with_post"]) as Int8 == 0 ? false : true auto_notify = item(from: args["auto_notify"]) as Int8 == 0 ? false : true show_smilies = item(from: args["show_smilies"]) as Int8 == 0 ? false : true show_img = item(from: args["show_img"]) as Int8 == 0 ? false : true show_img_sig = item(from: args["show_img_sig"]) as Int8 == 0 ? false : true show_avatars = item(from: args["show_avatars"]) as Int8 == 0 ? false : true show_sig = item(from: args["show_sig"]) as Int8 == 0 ? false : true timezone = item(from: args["timezone"]) dst = Float(item(from: args["dst"]) as Int8) time_format = item(from: args["time_format"])//todo date_format = item(from: args["date_format"])//todo language = item(from: args["language"]) style = item(from: args["style"]) num_posts = item(from: args["num_posts"]) last_post = item(from: args["last_post"]) last_search = item(from: args["last_search"]) last_email_sent = item(from: args["last_email_sent"]) last_report_sent = item(from: args["last_report_sent"]) registered = item(from: args["registered"]) registration_ip = item(from: args["registration_ip"]) last_visit = item(from: args["last_visit"]) admin_note = item(from: args["admin_note"]) activate_string = item(from: args["activate_string"]) activate_key = item(from: args["activate_key"]) } func isGuest() -> Bool { return id == 1 } } public struct YLDBsite_info { var newestUserId: UInt32 var newestUserName: String var totalUsers: UInt64 var totalTopics: UInt64 var totalPosts: UInt64 init(_ args: [String: Any]) { newestUserId = item(from: args["user_id"]) newestUserName = item(from: args["username"]) totalUsers = item(from: args["total_users"]) totalTopics = item(from: args["total_topics"]) totalPosts = item(from: args["total_posts"]) } } public struct YLDBdraconity { var userId: UInt32 var useAvatar: Bool var resume: String var draconity: String var draconityOptions: String init(_ args: [String: Any]) { userId = item(from: args["user_id"]) useAvatar = item(from: args["use_avatar"]) as Int8 == 0 ? false : true resume = item(from: args["resume"]) draconity = item(from: args["dragoncode"]) draconityOptions = item(from: args["draconity_ops"]) } } public struct YLDBfolders { var id: UInt32 var name: String var description: String var userId: UInt32 init(_ args: [String: Any]) { id = item(from: args["id"]) name = item(from: args["name"]) description = item(from: args["description"]) userId = item(from: args["user_id"]) } } extension DataManager { public func getConfig() -> [String: String] { return memoryStorage.getConfigs() } public func getSiteInfo() -> YLDBsite_info { return memoryStorage.getSiteInfo() } public func getNewestTopics() -> [YLDBtopics] { return memoryStorage.getNewestTopics() } public func getUser(userID: UInt32) -> YLDBusers? { return memoryStorage.getUsers()[userID] } public func getUser(userName: String) throws -> YLDBusers? { guard let args = dbStorage.getUser(userName: userName) else { throw DataError.dbError } if args.count == 0 { return nil } return YLDBusers(args) } public func getUser(email: String) throws -> YLDBusers? { guard let args = dbStorage.getUser(email: email) else { throw DataError.dbError } if args.count == 0 { return nil } return YLDBusers(args) } public func getDefaultUser(remoteAddress: String) throws -> YLDBusers? { guard let args = dbStorage.getDefaultUser(remoteAddress: remoteAddress) else { throw DataError.dbError } if args.count == 0 { return nil } return YLDBusers(args) } public func getGroup(id: UInt32) -> YLDBgroups? { return memoryStorage.getGroups()[id] } public func getForum(id: UInt32) -> YLDBforums? { return memoryStorage.getForums()[id] } public func getPermission(forumId: UInt32, groupId: UInt32) -> YLDBforum_perms? { for item in self.memoryStorage.getPermissions() { if UInt32(item.group_id) == groupId && UInt32(item.forum_id) == forumId { return item } } return nil } public func getTopic(id: UInt32) throws -> YLDBtopics? { guard let args = dbStorage.getTopic(id: id) else { throw DataError.dbError } if args.count == 0 { return nil } return YLDBtopics(args) } public func getTopics(forumIds: [UInt32], startFrom: UInt32, limit: UInt32) throws -> [YLDBtopics]? { guard let _topics = dbStorage.getTopics(forumIds: forumIds, startFrom: startFrom, limit: limit) else { throw DataError.dbError } if _topics.count == 0 { return nil } var topics: [YLDBtopics] = [] for args in _topics { topics.append(YLDBtopics(args)) } return topics } public func getPosts(topicId: UInt32, startFrom: UInt32, limit: UInt32) throws -> [YLDBposts]? { guard let _posts = dbStorage.getPosts(topicId: topicId, startFrom: startFrom, limit: limit) else { throw DataError.dbError } if _posts.count == 0 { return nil } var posts: [YLDBposts] = [] for args in _posts { posts.append(YLDBposts(args)) } return posts } public func getPost(id: UInt32) throws -> YLDBposts? { guard let args = dbStorage.getPost(id: id) else { throw DataError.dbError } if args.count == 0 { return nil } return YLDBposts(args) } public func locatePostInTopic(topicId: UInt32, posted: UInt32) -> UInt32? { return dbStorage.locatePostInTopic(topicId: topicId, posted: posted) } public func getForumName(id: UInt32) -> String { return memoryStorage.getForums()[id]?.forum_name ?? "Not Found" } public func getTotalTopics(forumIds: [UInt32]) -> UInt32 { var total: UInt32 = 0 let forums = memoryStorage.getForums() for i in forumIds { if let num = forums[i]?.num_topics { total = total + num } } return total } public func updatePost(id: UInt32, message: String) -> Bool { return dbStorage.updatePost(id: id, message: message) } public func insertPost(topicId: UInt32, message: String, user: YLDBusers, remoteAddress: String, postTime: UInt32) throws -> UInt32 { guard let insertId = dbStorage.insertPost(topicId: topicId, message: message, user: user, remoteAddress: remoteAddress, postTime: postTime) else { throw DataError.dbError } return insertId } public func deletePost(id: UInt32) -> Bool { return dbStorage.deletePost(id: id) } public func updateTopicAfterNewPost(id: UInt32, lastPostId: UInt32, lastPoster: YLDBusers, lastPostTime: UInt32) -> Bool { return dbStorage.updateTopicAfterNewPost(id: id, lastPostId: lastPostId, lastPosterName: lastPoster.username, lastPostTime: lastPostTime) } public func updateTopic(id: UInt32, forumId: UInt32, subject: String, sticky: Bool) -> Bool { return dbStorage.updateTopic(id: id, forumId: forumId, subject: subject, sticky: sticky) } public func insertTopic(forumId: UInt32, subject: String, user: YLDBusers, postTime: UInt32, type:Int32, sticky: Bool) throws -> UInt32 { guard let insertId = dbStorage.insertTopic(forumId: forumId, subject: subject, user: user, postTime: postTime, type: type, sticky: sticky) else { throw DataError.dbError } return insertId } public func deleteTopic(id: UInt32) -> Bool { return dbStorage.deletePost(id: id) } public func getDraconity(userId: UInt32) throws -> YLDBdraconity? { guard let args = dbStorage.getDraconity(userId: userId) else { throw DataError.dbError } if args.count == 0 { return nil } return YLDBdraconity(args) } public func insertUpload(fileName: String, localName: String, localDirectory: String, mimeType: String, size: UInt32, hash: String, userId: UInt32, createTime: UInt32) throws -> UInt32 { guard let insertId = dbStorage.insertUpload(fileName: fileName, localName: localName, localDirectory: localDirectory, mimeType: mimeType, size: size, hash: hash, userId: userId, createTime: createTime) else { throw DataError.dbError } return insertId } public func insertFolder(name: String, description: String, ownerId: UInt32) throws -> UInt32 { guard let insertId = dbStorage.insertFolder(name: name, description: description, ownerId: ownerId) else { throw DataError.dbError } return insertId } }
apache-2.0
62e25f844425690863dc9b5d37075e65
33.910828
216
0.597701
3.552171
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/SearchVC/WaitingScreen/Results/PhotosEngine/HLPhotoCollectionView+UpdateDataSource.swift
1
1082
extension HLPhotoCollectionView { func updateDataSource(withHotel hotel: HDKHotel, imageSize: CGSize, thumbSize: CGSize, useThumbs: Bool) { if useThumbs { self.thumbs = HLUrlUtils.photoUrls(by: hotel, withSizeInPoints: thumbSize) as! [URL] } self.updateDataSource(withHotel: hotel, imageSize: imageSize) } func updateDataSource(withHotel hotel: HDKHotel, imageSize: CGSize, useThumbs: Bool) { updateDataSource(withHotel: hotel, imageSize: imageSize, thumbSize: HLPhotoManager.defaultThumbPhotoSize, useThumbs: useThumbs) } func updateDataSource(withHotel hotel: HDKHotel, imageSize: CGSize, firstImage: UIImage? = nil) { if hotel.photosIds.count > 0 { var content = HLUrlUtils.photoUrls(by: hotel, withSizeInPoints: imageSize) if let img = firstImage { content[0] = img } self.content = content as [AnyObject] } else { self.content = [UIImage.photoPlaceholder] } self.collectionView.reloadData() } }
mit
ce2fa4b3cf708c9108ae9172f88da83b
36.310345
135
0.654344
4.398374
false
false
false
false
february29/Learning
swift/Fch_Contact/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift
27
1725
// // SchedulerType+SharedSequence.swift // RxCocoa // // Created by Krunoslav Zaher on 8/27/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import RxSwift public enum SharingScheduler { /// Default scheduler used in SharedSequence based traits. public private(set) static var make: () -> SchedulerType = { MainScheduler() } /** This method can be used in unit tests to ensure that built in shared sequences are using mock schedulers instead of main schedulers. **This shouldn't be used in normal release builds.** */ static public func mock(scheduler: SchedulerType, action: () -> ()) { return mock(makeScheduler: { scheduler }, action: action) } /** This method can be used in unit tests to ensure that built in shared sequences are using mock schedulers instead of main schedulers. **This shouldn't be used in normal release builds.** */ static public func mock(makeScheduler: @escaping () -> SchedulerType, action: () -> ()) { let originalMake = make make = makeScheduler action() // If you remove this line , compiler buggy optimizations will change behavior of this code _forceCompilerToStopDoingInsaneOptimizationsThatBreakCode(makeScheduler) // Scary, I know make = originalMake } } #if os(Linux) import Glibc #else import func Foundation.arc4random #endif func _forceCompilerToStopDoingInsaneOptimizationsThatBreakCode(_ scheduler: () -> SchedulerType) { let a: Int32 = 1 #if os(Linux) let b = 314 + Int32(Glibc.random() & 1) #else let b = 314 + Int32(arc4random() & 1) #endif if a == b { print(scheduler()) } }
mit
5e07b9998a9989e7e9c3777f4fbaa477
27.262295
117
0.664733
4.25679
false
false
false
false