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
koher/PromiseK
Sources/PromiseK/Promise.swift
1
1650
import Foundation public class Promise<Value> { private var value: Value? private var handlers: [(Value) -> ()] = [] private let lock = NSRecursiveLock() public init(_ value: Value) { self.value = value } public init(_ executor: (_ fulfill: @escaping (Value) -> ()) -> ()) { executor { value in synchronized(with: self.lock) { precondition(self.value == nil, "`fulfill` cannot be called multiple times.") self.value = value self.handlers.forEach { $0(value) } self.handlers.removeAll(keepingCapacity: false) } } } public func get(_ handler: @escaping (Value) -> ()) { synchronized(with: lock) { if let value = self.value { handler(value) } else { handlers.append(handler) } } } public func map<T>(_ transform: @escaping (Value) -> T) -> Promise<T> { return Promise<T> { fulfill in get { fulfill(transform($0)) } } } public func flatMap<T>(_ transform: @escaping (Value) -> Promise<T>) -> Promise<T> { return Promise<T> { fulfill in get { transform($0).get { fulfill($0) } } } } } extension Promise : CustomStringConvertible { public var description: String { if let value = self.value { return "Promise(\(value))" } else { return "Promise(\(Value.self))" } } } private func synchronized(with lock: NSRecursiveLock, _ operation: () -> ()) { lock.lock() defer { lock.unlock() } operation() }
mit
16ace02ee3a8114f8bbe158a377b4405
28.464286
93
0.530303
4.353562
false
false
false
false
cannawen/dota-helper
dota-helper/GameState.swift
1
1675
// // GameState.swift // dota-helper // // Created by Canna Wen on 2016-11-26. // Copyright © 2016 Canna Wen. All rights reserved. // import UIKit protocol GameRenderer { func render(gameState: GameState) } class GameState { private(set) public var wards: Array<Ward>! private(set) public var currentTime: TimeInterval! private(set) public var paused: Bool! private var timer: Timer? private var renderer: GameRenderer! public func resetGame(renderer: GameRenderer) { wards = [] currentTime = 0 paused = false if timer == nil { timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(tick), userInfo: nil, repeats: true) } self.renderer = renderer renderer.render(gameState: self) } public func addWard(type: WardType, location: CGPoint) { wards.append(Ward(type: type, creationTime: currentTime, location: location)) renderer.render(gameState: self) } public func togglePauseState() { paused = !paused renderer.render(gameState: self) } @objc private func tick() { guard !paused else { return } func removeExpiredWards() { wards = wards.filter { $0.isValid(currentTime: currentTime) } } currentTime = currentTime + 1 removeExpiredWards() renderer.render(gameState: self) } } private extension Ward { func isValid(currentTime: TimeInterval) -> Bool { let age = currentTime - creationTime return age <= type.lifespan(); } }
apache-2.0
3ae70b01326afea858590c2bc97e36b3
24.363636
130
0.60454
4.393701
false
false
false
false
debugsquad/Hyperborea
Hyperborea/Model/Search/MSearchEntryTense.swift
1
3260
import UIKit class MSearchEntryTense { private static let kBreak:String = "\n" private static let kSeparator:String = ", " private static let kKeyEntries:String = "entries" private static let kKeyGrammaticalFeatures:String = "grammaticalFeatures" private static let kKeyType:String = "type" private static let kKeyText:String = "text" private static let kTypeTense:String = "Tense" private static let kTypeNotFinite:String = "Non Finiteness" private static let kFontSize:CGFloat = 14 class func parse(json:Any) -> NSAttributedString? { guard let jsonMap:[String:Any] = json as? [String:Any], let jsonEntries:[Any] = jsonMap[kKeyEntries] as? [Any] else { return nil } let mutableString:NSMutableAttributedString = NSMutableAttributedString() let attributes:[String:AnyObject] = [ NSFontAttributeName:UIFont.regular(size:kFontSize), NSForegroundColorAttributeName:UIColor.black] let stringBreak:NSAttributedString = NSAttributedString( string:kBreak, attributes:attributes) let stringSeparator:NSAttributedString = NSAttributedString( string:kSeparator, attributes:attributes) for jsonEntry:Any in jsonEntries { guard let jsonEntryMap:[String:Any] = jsonEntry as? [String:Any], let jsonFeatures:[Any] = jsonEntryMap[kKeyGrammaticalFeatures] as? [Any] else { continue } for jsonFeature:Any in jsonFeatures { guard let featureMap:[String:Any] = jsonFeature as? [String:Any], let featureMapType:String = featureMap[kKeyType] as? String, let featureMapText:String = featureMap[kKeyText] as? String else { continue } let tenseLowerCase:String = featureMapText.lowercased() let tenseString:NSAttributedString = NSAttributedString( string:tenseLowerCase, attributes:attributes) if featureMapType == kTypeTense { if !mutableString.string.isEmpty { mutableString.insert(stringSeparator, at:0) } mutableString.insert(tenseString, at:0) } else if featureMapType == kTypeNotFinite { if !mutableString.string.isEmpty { mutableString.append(stringSeparator) } mutableString.append(tenseString) } } } if !mutableString.string.isEmpty { mutableString.insert(stringBreak, at:0) } return mutableString } }
mit
835e099940fa5c99fb830dfa9c6a3841
32.958333
88
0.513497
6.05948
false
false
false
false
connienguyen/volunteers-iOS
VOLA/VOLA/Helpers/Extensions/UIKit/UIView.swift
1
2106
import Foundation import UIKit extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 //performance, test required layer.shouldRasterize = newValue > 0 layer.rasterizationScale = UIScreen.main.scale } } /// Border width. @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set(value) { layer.borderWidth = value } } /// Border color. @IBInspectable var borderColor: UIColor? { get { guard let layerBorderColor = layer.borderColor else { return nil } return UIColor(cgColor: layerBorderColor) } set(value) { layer.borderColor = value?.cgColor } } /// Shadow color of view. @IBInspectable var shadowColor: UIColor? { get { guard let color = layer.shadowColor else { return nil } return UIColor(cgColor: color) } set { layer.shadowColor = newValue?.cgColor } } /// Shadow offset of view. @IBInspectable var shadowOffset: CGSize { get { return layer.shadowOffset } set { layer.shadowOffset = newValue } } /// Shadow opacity of view. @IBInspectable var shadowOpacity: Float { get { return layer.shadowOpacity } set { layer.shadowOpacity = newValue } } @IBInspectable var shadowRadius: CGFloat { get { return layer.shadowRadius } set { layer.masksToBounds = newValue <= 0 layer.shadowRadius = newValue //performance, test required layer.shouldRasterize = newValue > 0 layer.rasterizationScale = UIScreen.main.scale } } }
gpl-2.0
df954d1664c9b0970dbfd02b69d1e6bf
22.4
66
0.522317
5.601064
false
false
false
false
redlock/SwiftyDeepstream
SwiftyDeepstream/Classes/deepstream/utils/Reflection/Array+Extensions.swift
13
600
protocol UTF8Initializable { init?(validatingUTF8: UnsafePointer<CChar>) } extension String : UTF8Initializable {} extension Array where Element : UTF8Initializable { init(utf8Strings: UnsafePointer<CChar>) { var strings = [Element]() var pointer = utf8Strings while let string = Element(validatingUTF8: pointer) { strings.append(string) while pointer.pointee != 0 { pointer.advance() } pointer.advance() guard pointer.pointee != 0 else { break } } self = strings } }
mit
0bb36f15fdba934d7e6e3869ec11bb36
25.086957
61
0.593333
4.761905
false
false
false
false
swiftingio/alti-sampler
Sampler/ViewController.swift
1
5711
import UIKit class ViewController: UIViewController { var button: UIBarButtonItem! var export: UIBarButtonItem! var clear: UIBarButtonItem! var textView: UITextView! let toolbar = UIToolbar(frame: .zero) var locationButton: UIBarButtonItem! let exporter: Exporter let sampler: Sampler init(sampler: Sampler, exporter: Exporter) { self.sampler = sampler self.exporter = exporter super.init(nibName: nil, bundle: nil) sampler.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white title = "Pressure + Location" setupButtons() setupTextView() setupToolbar() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() textView.frame = view.bounds toolbar.sizeToFit() toolbar.frame.origin.x = view.bounds.origin.x toolbar.frame.origin.y = view.bounds.origin.y + view.bounds.size.height - toolbar.frame.size.height } private func setupButtons() { button = UIBarButtonItem(title: "record", style: .plain, target: self, action: #selector(toggleRecording)) setButtonTitle(self.sampler.isRecording) export = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareAll)) clear = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(clearDatabase)) navigationItem.rightBarButtonItem = button navigationItem.leftBarButtonItems = [export, clear] } private func setupToolbar() { locationButton = UIBarButtonItem(title: "location", style: .plain, target: self, action: #selector(showLocationPicker)) let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) toolbar.items = [flexible, locationButton, flexible] view.addSubview(toolbar) } private func setButtonTitle(_ isRecording: Bool) { button.title = isRecording ? "stop" : "record" } private func setupTextView() { textView = UITextView() textView.isEditable = false textView.isUserInteractionEnabled = false textView.font = UIFont.preferredFont(forTextStyle: .body) view.addSubview(textView) } @objc private func toggleRecording() { if sampler.isRecording { sampler.stopSampling() exporter.save(sampler.samples) } else { sampler.clearSamples() sampler.startSampling() } setButtonTitle(sampler.isRecording) } func showLocationPicker() { let viewController = SkiLiftPickerViewController() viewController.delegate = self let navigationController = UINavigationController(rootViewController: viewController) present(navigationController, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() exporter.save(sampler.samples) } func exportAll() { do { if let filePath: String = try exporter.saveAsPlistToDocuments() { showMsg("Saved at filePath: \(filePath).") } } catch { showMsg("Error when saving :(!") } } func shareAll() { do { let json = try exporter.allJSONRecordings() let activityVC = UIActivityViewController(activityItems: [json], applicationActivities: nil) var excluded: [UIActivityType] = [ .addToReadingList, .assignToContact, .message, .openInIBooks, .postToFacebook, .postToFlickr, .postToTencentWeibo, .postToTwitter, .postToVimeo, .postToWeibo, .print, .saveToCameraRoll, ] if #available(iOS 11.0, *) { excluded.append(.markupAsPDF) } activityVC.excludedActivityTypes = excluded present(activityVC, animated: true, completion: nil) } catch { printE(error) } } func clearDatabase() { let alert = UIAlertController(title: "Remove recordings", message: "Do you want to remove all recorded data?", preferredStyle: .alert) let ok = UIAlertAction(title: "cancel", style: .default) let remove = UIAlertAction(title: "remove", style: .destructive) { [weak self] _ in self?.exporter.clearAll() } alert.addAction(remove) alert.addAction(ok) present(alert, animated: true, completion: nil) } } extension ViewController: SkiLiftPickerViewControllerDelegate { func locationViewController(_ viewController: SkiLiftPickerViewController, didSelectLocation location: String) { sampler.locationName = location } } extension UIViewController { func printE(_ error: Error) { showMsg(error.localizedDescription) } func showMsg(_ message: String) { let alert = UIAlertController(title: "", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } } extension ViewController: SamplerDelegate { func sampler(_ sampler: Sampler, didAdd sample: Sample) { show(sample) } func show(_ sample: Sample) { textView.text = exporter.json(from: sample) } }
mit
5a28e7856397c38f19b510038b877f51
32.594118
142
0.627036
5.071936
false
false
false
false
alvarozizou/Noticias-Leganes-iOS
NoticiasLeganes/MatchesViewController.swift
1
2648
// // ScheduleViewController.swift // NoticiasLeganes // // Created by Alvaro Blazquez Montero on 25/5/17. // Copyright © 2017 Alvaro Blazquez Montero. All rights reserved. // import UIKit class MatchesViewController: UIViewController, ListViewController { @IBOutlet weak var tableView: UITableView! var activityIndicator = UIActivityIndicatorView(style: .whiteLarge) var refreshControl = UIRefreshControl() var firstTime = true var viewModel : ViewModel<MatchItemViewModel>! override func viewDidLoad() { super.viewDidLoad() initTableView() Analytics.watchMatches() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func prepareTableView() { prepareRefreshControl() refreshControl.addTarget(self, action: #selector(refreshData(_:)), for: .valueChanged) tableView.refreshControl = refreshControl } @objc func refreshData(_ sender: Any) { reloadData() } func reloadData() { viewModel.reloadData() } func reloadTableView() { tableView.reloadData() } } extension MatchesViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: MatchTableViewCell.ReuseIdentifier, for: indexPath) as? MatchTableViewCell else { fatalError("The dequeued cell is not an instance of MatchTableViewCell.") } if let matchItemViewModel = viewModel.itemAtIndex(indexPath.row) { cell.matchItemViewModel = matchItemViewModel } return cell } } extension MatchesViewController: ListViewModelDelegate { func itemsDidChange() { showNewData() if firstTime { let index = IndexPath(row: findFirstOpenMatch(), section: 0) tableView.scrollToRow(at: index,at: .middle, animated: true) firstTime = false } } func itemsError() { showError() } func findFirstOpenMatch() -> Int { if let i = self.viewModel.getData().firstIndex(where: { !$0.isFinished }) { return i } return 0 } }
mit
b4909081f17d2a28316e40fdbf59ff23
26.863158
153
0.641481
5.402041
false
false
false
false
milseman/swift
test/SILGen/objc_bridging.swift
6
38276
// RUN: %empty-directory(%t) // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t -I %S/../Inputs/ObjCBridging %S/../Inputs/ObjCBridging/Appliances.swift // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -I %S/../Inputs/ObjCBridging -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-cpu --check-prefix=CHECK-%target-os-%target-cpu // REQUIRES: objc_interop import Foundation import Appliances func getDescription(_ o: NSObject) -> String { return o.description } // CHECK-LABEL: sil hidden @_T013objc_bridging14getDescription{{.*}}F // CHECK: bb0([[ARG:%.*]] : $NSObject): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[DESCRIPTION:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $NSObject, #NSObject.description!getter.1.foreign // CHECK: [[OPT_BRIDGED:%.*]] = apply [[DESCRIPTION]]([[BORROWED_ARG]]) // CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : $NSString): // CHECK-NOT: unchecked_enum_data // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]], // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: br [[CONT_BB:bb[0-9]+]]([[OPT_NATIVE]] : $Optional<String>) // // CHECK: [[NONE_BB]]: // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.none!enumelt // CHECK: br [[CONT_BB]]([[OPT_NATIVE]] : $Optional<String>) // // CHECK: [[CONT_BB]]([[OPT_NATIVE:%.*]] : $Optional<String>): // CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: unreachable // // CHECK: [[SOME_BB]]([[NATIVE:%.*]] : $String): // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[NATIVE]] // CHECK:} func getUppercaseString(_ s: NSString) -> String { return s.uppercase() } // CHECK-LABEL: sil hidden @_T013objc_bridging18getUppercaseString{{.*}}F // CHECK: bb0([[ARG:%.*]] : $NSString): // -- The 'self' argument of NSString methods doesn't bridge. // CHECK-NOT: function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK-NOT: function_ref @swift_StringToNSString // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[UPPERCASE_STRING:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $NSString, #NSString.uppercase!1.foreign // CHECK: [[OPT_BRIDGED:%.*]] = apply [[UPPERCASE_STRING]]([[BORROWED_ARG]]) : $@convention(objc_method) (NSString) -> @autoreleased Optional<NSString> // CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // // CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : // CHECK-NOT: unchecked_enum_data // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]] // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: br [[CONT_BB:bb[0-9]+]]([[OPT_NATIVE]] : $Optional<String>) // // CHECK: [[NONE_BB]]: // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.none!enumelt // CHECK: br [[CONT_BB]]([[OPT_NATIVE]] : $Optional<String>) // // CHECK: [[CONT_BB]]([[OPT_NATIVE:%.*]] : $Optional<String>): // CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: unreachable // // CHECK: [[SOME_BB]]([[NATIVE:%.*]] : $String): // CHECK: return [[NATIVE]] // CHECK: } // @interface Foo -(void) setFoo: (NSString*)s; @end func setFoo(_ f: Foo, s: String) { var s = s f.setFoo(s) } // CHECK-LABEL: sil hidden @_T013objc_bridging6setFoo{{.*}}F // CHECK: bb0([[ARG0:%.*]] : $Foo, {{%.*}} : $String): // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[SET_FOO:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setFoo!1.foreign // CHECK: [[NATIVE:%.*]] = load // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_NATIVE:%.*]] = begin_borrow [[NATIVE]] // CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_NATIVE]]) // CHECK: [[OPT_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: apply [[SET_FOO]]([[OPT_BRIDGED]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Optional<NSString>, Foo) -> () // CHECK: destroy_value [[OPT_BRIDGED]] // CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK: destroy_value [[ARG0]] // CHECK: } // @interface Foo -(BOOL) zim; @end func getZim(_ f: Foo) -> Bool { return f.zim() } // CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-ios-i386: bb0([[SELF:%.*]] : $Foo): // CHECK-ios-i386: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-ios-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Bool // CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> ObjCBool // CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool // CHECK-ios-i386: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool // CHECK-ios-i386: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-ios-i386: return [[SWIFT_BOOL]] : $Bool // CHECK-ios-i386: } // CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-watchos-i386: bb0([[SELF:%.*]] : $Foo): // CHECK-watchos-i386: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-watchos-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo // CHECK-watchos-i386: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> Bool // CHECK-watchos-i386: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-watchos-i386: return [[BOOL]] : $Bool // CHECK-watchos-i386: } // CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-macosx-x86_64: bb0([[SELF:%.*]] : $Foo): // CHECK-macosx-x86_64: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-macosx-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Bool // CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> ObjCBool // CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool // CHECK-macosx-x86_64: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool // CHECK-macosx-x86_64: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-macosx-x86_64: return [[SWIFT_BOOL]] : $Bool // CHECK-macosx-x86_64: } // CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-ios-x86_64: bb0([[SELF:%.*]] : $Foo): // CHECK-ios-x86_64: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-ios-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo // CHECK-ios-x86_64: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> Bool // CHECK-ios-x86_64: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-ios-x86_64: return [[BOOL]] : $Bool // CHECK-ios-x86_64: } // CHECK-arm64-LABEL: sil hidden @_T013objc_bridging6getZim{{.*}}F // CHECK-arm64: bb0([[SELF:%.*]] : $Foo): // CHECK-arm64: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-arm64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo // CHECK-arm64: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_SELF]]) : $@convention(objc_method) (Foo) -> Bool // CHECK-arm64: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-arm64: return [[BOOL]] : $Bool // CHECK-arm64: } // @interface Foo -(void) setZim: (BOOL)b; @end func setZim(_ f: Foo, b: Bool) { f.setZim(b) } // CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-ios-i386: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool): // CHECK-ios-i386: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-ios-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool // CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]([[ARG1]]) : $@convention(thin) (Bool) -> ObjCBool // CHECK-ios-i386: apply [[METHOD]]([[OBJC_BOOL]], [[BORROWED_ARG0]]) : $@convention(objc_method) (ObjCBool, Foo) -> () // CHECK-ios-i386: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-ios-i386: destroy_value [[ARG0]] // CHECK-ios-i386: } // CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-macosx-x86_64: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool): // CHECK-macosx-x86_64: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-macosx-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool // CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]([[ARG1]]) : $@convention(thin) (Bool) -> ObjCBool // CHECK-macosx-x86_64: apply [[METHOD]]([[OBJC_BOOL]], [[BORROWED_ARG0]]) : $@convention(objc_method) (ObjCBool, Foo) -> () // CHECK-macosx-x86_64: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-macosx-x86_64: destroy_value [[ARG0]] // CHECK-macosx-x86_64: } // CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-ios-x86_64: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool): // CHECK-ios-x86_64: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-ios-x86_64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-ios-x86_64: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-ios-x86_64: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-ios-x86_64: destroy_value [[ARG0]] // CHECK-ios-x86_64: } // CHECK-arm64-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-arm64: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool): // CHECK-arm64: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-arm64: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-arm64: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-arm64: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-arm64: destroy_value [[ARG0]] // CHECK-arm64: } // CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging6setZim{{.*}}F // CHECK-watchos-i386: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool): // CHECK-watchos-i386: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK-watchos-i386: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZim!1.foreign // CHECK-watchos-i386: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-watchos-i386: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-watchos-i386: destroy_value [[ARG0]] // CHECK-watchos-i386: } // @interface Foo -(_Bool) zang; @end func getZang(_ f: Foo) -> Bool { return f.zang() } // CHECK-LABEL: sil hidden @_T013objc_bridging7getZangSbSo3FooCF // CHECK: bb0([[ARG:%.*]] : $Foo) // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG]] : $Foo, #Foo.zang!1.foreign // CHECK: [[BOOL:%.*]] = apply [[METHOD]]([[BORROWED_ARG]]) : $@convention(objc_method) (Foo) -> Bool // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[BOOL]] // @interface Foo -(void) setZang: (_Bool)b; @end func setZang(_ f: Foo, _ b: Bool) { f.setZang(b) } // CHECK-LABEL: sil hidden @_T013objc_bridging7setZangySo3FooC_SbtF // CHECK: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $Bool): // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.setZang!1.foreign // CHECK: apply [[METHOD]]([[ARG1]], [[BORROWED_ARG0]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK: destroy_value [[ARG0]] // CHECK: } // end sil function '_T013objc_bridging7setZangySo3FooC_SbtF' // NSString *bar(void); func callBar() -> String { return bar() } // CHECK-LABEL: sil hidden @_T013objc_bridging7callBar{{.*}}F // CHECK: bb0: // CHECK: [[BAR:%.*]] = function_ref @bar // CHECK: [[OPT_BRIDGED:%.*]] = apply [[BAR]]() : $@convention(c) () -> @autoreleased Optional<NSString> // CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : $NSString): // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]] // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: bb5([[NATIVE:%.*]] : $String): // CHECK: return [[NATIVE]] // CHECK: } // void setBar(NSString *s); func callSetBar(_ s: String) { var s = s setBar(s) } // CHECK-LABEL: sil hidden @_T013objc_bridging10callSetBar{{.*}}F // CHECK: bb0({{%.*}} : $String): // CHECK: [[SET_BAR:%.*]] = function_ref @setBar // CHECK: [[NATIVE:%.*]] = load // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_NATIVE:%.*]] = begin_borrow [[NATIVE]] // CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_NATIVE]]) // CHECK: [[OPT_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: end_borrow [[BORROWED_NATIVE]] from [[NATIVE]] // CHECK: apply [[SET_BAR]]([[OPT_BRIDGED]]) // CHECK: destroy_value [[OPT_BRIDGED]] // CHECK: } var NSS: NSString // -- NSString methods don't convert 'self' extension NSString { var nsstrFakeProp: NSString { get { return NSS } set {} } // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE13nsstrFakePropABfgTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE13nsstrFakePropABfsTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } func nsstrResult() -> NSString { return NSS } // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE11nsstrResultAByFTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } func nsstrArg(_ s: NSString) { } // CHECK-LABEL: sil hidden [thunk] @_T0So8NSStringC13objc_bridgingE8nsstrArgyABFTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } } class Bas : NSObject { // -- Bridging thunks for String properties convert between NSString var strRealProp: String = "Hello" // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strRealPropSSfgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK: bb0([[THIS:%.*]] : $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] : $Bas // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: // function_ref objc_bridging.Bas.strRealProp.getter // CHECK: [[PROPIMPL:%.*]] = function_ref @_T013objc_bridging3BasC11strRealPropSSfg // CHECK: [[PROP_COPY:%.*]] = apply [[PROPIMPL]]([[BORROWED_THIS_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned String // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_PROP_COPY:%.*]] = begin_borrow [[PROP_COPY]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_PROP_COPY]]) // CHECK: end_borrow [[BORROWED_PROP_COPY]] from [[PROP_COPY]] // CHECK: destroy_value [[PROP_COPY]] // CHECK: return [[NSSTR]] // CHECK: } // CHECK-LABEL: sil hidden @_T013objc_bridging3BasC11strRealPropSSfg // CHECK: [[PROP_ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Bas.strRealProp // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[PROP_ADDR]] : $*String // CHECK: [[PROP:%.*]] = load [copy] [[READ]] // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strRealPropSSfsTo : $@convention(objc_method) (NSString, Bas) -> () { // CHECK: bb0([[VALUE:%.*]] : $NSString, [[THIS:%.*]] : $Bas): // CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[VALUE_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[VALUE_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[VALUE_BOX]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[SETIMPL:%.*]] = function_ref @_T013objc_bridging3BasC11strRealPropSSfs // CHECK: apply [[SETIMPL]]([[STR]], [[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_T013objc_bridging3BasC11strRealPropSSfsTo' // CHECK-LABEL: sil hidden @_T013objc_bridging3BasC11strRealPropSSfs // CHECK: bb0(%0 : $String, %1 : $Bas): // CHECK: [[STR_ADDR:%.*]] = ref_element_addr %1 : {{.*}}, #Bas.strRealProp // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[STR_ADDR]] : $*String // CHECK: assign {{.*}} to [[WRITE]] // CHECK: } var strFakeProp: String { get { return "" } set {} } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strFakePropSSfgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK: bb0([[THIS:%.*]] : $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[GETTER:%.*]] = function_ref @_T013objc_bridging3BasC11strFakePropSSfg // CHECK: [[STR:%.*]] = apply [[GETTER]]([[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STR]]) // CHECK: end_borrow [[BORROWED_STR]] from [[STR]] // CHECK: destroy_value [[STR]] // CHECK: return [[NSSTR]] // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11strFakePropSSfsTo : $@convention(objc_method) (NSString, Bas) -> () { // CHECK: bb0([[NSSTR:%.*]] : $NSString, [[THIS:%.*]] : $Bas): // CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[SETTER:%.*]] = function_ref @_T013objc_bridging3BasC11strFakePropSSfs // CHECK: apply [[SETTER]]([[STR]], [[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_T013objc_bridging3BasC11strFakePropSSfsTo' // -- Bridging thunks for explicitly NSString properties don't convert var nsstrRealProp: NSString var nsstrFakeProp: NSString { get { return NSS } set {} } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC13nsstrRealPropSo8NSStringCfgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC13nsstrRealPropSo8NSStringCfsTo : $@convention(objc_method) (NSString, Bas) -> // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } // -- Bridging thunks for String methods convert between NSString func strResult() -> String { return "" } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC9strResultSSyFTo // CHECK: bb0([[THIS:%.*]] : $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[METHOD:%.*]] = function_ref @_T013objc_bridging3BasC9strResultSSyF // CHECK: [[STR:%.*]] = apply [[METHOD]]([[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STR]]) // CHECK: end_borrow [[BORROWED_STR]] from [[STR]] // CHECK: destroy_value [[STR]] // CHECK: return [[NSSTR]] // CHECK: } func strArg(_ s: String) { } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC6strArgySSFTo // CHECK: bb0([[NSSTR:%.*]] : $NSString, [[THIS:%.*]] : $Bas): // CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]] // CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]] // CHECK: [[METHOD:%.*]] = function_ref @_T013objc_bridging3BasC6strArgySSF // CHECK: apply [[METHOD]]([[STR]], [[BORROWED_THIS_COPY]]) // CHECK: end_borrow [[BORROWED_THIS_COPY]] from [[THIS_COPY]] // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_T013objc_bridging3BasC6strArgySSFTo' // -- Bridging thunks for explicitly NSString properties don't convert func nsstrResult() -> NSString { return NSS } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11nsstrResultSo8NSStringCyFTo // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } func nsstrArg(_ s: NSString) { } // CHECK-LABEL: sil hidden @_T013objc_bridging3BasC8nsstrArgySo8NSStringCF // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: } init(str: NSString) { nsstrRealProp = str super.init() } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC8arrayArgySayyXlGFTo : $@convention(objc_method) (NSArray, Bas) -> () // CHECK: bb0([[NSARRAY:%[0-9]+]] : $NSArray, [[SELF:%[0-9]+]] : $Bas): // CHECK: [[NSARRAY_COPY:%.*]] = copy_value [[NSARRAY]] : $NSArray // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas // CHECK: [[CONV_FN:%[0-9]+]] = function_ref @_T0Sa10FoundationE36_unconditionallyBridgeFromObjectiveCSayxGSo7NSArrayCSgFZ // CHECK: [[OPT_NSARRAY:%[0-9]+]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[NSARRAY_COPY]] : $NSArray // CHECK: [[ARRAY_META:%[0-9]+]] = metatype $@thin Array<AnyObject>.Type // CHECK: [[ARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[OPT_NSARRAY]], [[ARRAY_META]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T013objc_bridging3BasC8arrayArgySayyXlGF : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[ARRAY]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> () // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] : $Bas // CHECK: return [[RESULT]] : $() func arrayArg(_ array: [AnyObject]) { } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC11arrayResultSayyXlGyFTo : $@convention(objc_method) (Bas) -> @autoreleased NSArray // CHECK: bb0([[SELF:%[0-9]+]] : $Bas): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T013objc_bridging3BasC11arrayResultSayyXlGyF : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject> // CHECK: [[ARRAY:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject> // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[CONV_FN:%[0-9]+]] = function_ref @_T0Sa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF // CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]] // CHECK: [[NSARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[BORROWED_ARRAY]]) : $@convention(method) <τ_0_0> (@guaranteed Array<τ_0_0>) -> @owned NSArray // CHECK: end_borrow [[BORROWED_ARRAY]] from [[ARRAY]] // CHECK: destroy_value [[ARRAY]] // CHECK: return [[NSARRAY]] func arrayResult() -> [AnyObject] { return [] } // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC9arrayPropSaySSGfgTo : $@convention(objc_method) (Bas) -> @autoreleased NSArray // CHECK-LABEL: sil hidden [thunk] @_T013objc_bridging3BasC9arrayPropSaySSGfsTo : $@convention(objc_method) (NSArray, Bas) -> () var arrayProp: [String] = [] } // CHECK-LABEL: sil hidden @_T013objc_bridging16applyStringBlockS3SXB_SS1xtF func applyStringBlock(_ f: @convention(block) (String) -> String, x: String) -> String { // CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (NSString) -> @autoreleased NSString, [[STRING:%.*]] : $String): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[BORROWED_BLOCK_COPY:%.*]] = begin_borrow [[BLOCK_COPY]] // CHECK: [[BLOCK_COPY_COPY:%.*]] = copy_value [[BORROWED_BLOCK_COPY]] // CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]] // CHECK: [[STRING_COPY:%.*]] = copy_value [[BORROWED_STRING]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STRING_COPY]]) : $@convention(method) (@guaranteed String) // CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]] // CHECK: destroy_value [[STRING_COPY]] // CHECK: [[RESULT_NSSTR:%.*]] = apply [[BLOCK_COPY_COPY]]([[NSSTR]]) : $@convention(block) (NSString) -> @autoreleased NSString // CHECK: destroy_value [[NSSTR]] // CHECK: [[FINAL_BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK: [[OPTIONAL_NSSTR:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[RESULT_NSSTR]] // CHECK: [[RESULT:%.*]] = apply [[FINAL_BRIDGE]]([[OPTIONAL_NSSTR]], {{.*}}) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: destroy_value [[BLOCK_COPY_COPY]] // CHECK: destroy_value [[STRING]] // CHECK: destroy_value [[BLOCK_COPY]] // CHECK: destroy_value [[BLOCK]] // CHECK: return [[RESULT]] : $String return f(x) } // CHECK: } // end sil function '_T013objc_bridging16applyStringBlockS3SXB_SS1xtF' // CHECK-LABEL: sil hidden @_T013objc_bridging15bridgeCFunction{{.*}}F func bridgeCFunction() -> (String!) -> (String!) { // CHECK: [[THUNK:%.*]] = function_ref @_T0SC18NSStringFromStringSQySSGABFTO : $@convention(thin) (@owned Optional<String>) -> @owned Optional<String> // CHECK: [[THICK:%.*]] = thin_to_thick_function [[THUNK]] // CHECK: return [[THICK]] return NSStringFromString } func forceNSArrayMembers() -> (NSArray, NSArray) { let x = NSArray(objects: nil, count: 0) return (x, x) } // Check that the allocating initializer shim for initializers that take pointer // arguments lifetime-extends the bridged pointer for the right duration. // <rdar://problem/16738050> // CHECK-LABEL: sil shared [serializable] @_T0So7NSArrayCABSQySPyyXlSgGG7objects_s5Int32V5counttcfC // CHECK: [[SELF:%.*]] = alloc_ref_dynamic // CHECK: [[METHOD:%.*]] = function_ref @_T0So7NSArrayCABSQySPyyXlSgGG7objects_s5Int32V5counttcfcTO // CHECK: [[RESULT:%.*]] = apply [[METHOD]] // CHECK: return [[RESULT]] // Check that type lowering preserves the bool/BOOL distinction when bridging // imported C functions. // CHECK-ios-i386-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-ios-i386: function_ref @useBOOL : $@convention(c) (ObjCBool) -> () // CHECK-ios-i386: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-ios-i386: function_ref @getBOOL : $@convention(c) () -> ObjCBool // CHECK-ios-i386: function_ref @getBool : $@convention(c) () -> Bool // CHECK-macosx-x86_64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-macosx-x86_64: function_ref @useBOOL : $@convention(c) (ObjCBool) -> () // CHECK-macosx-x86_64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-macosx-x86_64: function_ref @getBOOL : $@convention(c) () -> ObjCBool // CHECK-macosx-x86_64: function_ref @getBool : $@convention(c) () -> Bool // FIXME: no distinction on x86_64, arm64 or watchos-i386, since SILGen looks // at the underlying Clang decl of the bridged decl to decide whether it needs // bridging. // // CHECK-watchos-i386-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-watchos-i386: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-watchos-i386: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-watchos-i386: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-watchos-i386: function_ref @getBool : $@convention(c) () -> Bool // CHECK-ios-x86_64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-ios-x86_64: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-ios-x86_64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-ios-x86_64: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-ios-x86_64: function_ref @getBool : $@convention(c) () -> Bool // CHECK-arm64-LABEL: sil hidden @_T013objc_bridging5boolsSb_SbtSbF // CHECK-arm64: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-arm64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-arm64: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-arm64: function_ref @getBool : $@convention(c) () -> Bool func bools(_ x: Bool) -> (Bool, Bool) { useBOOL(x) useBool(x) return (getBOOL(), getBool()) } // CHECK-LABEL: sil hidden @_T013objc_bridging9getFridge{{.*}}F // CHECK: bb0([[HOME:%[0-9]+]] : $APPHouse): func getFridge(_ home: APPHouse) -> Refrigerator { // CHECK: [[BORROWED_HOME:%.*]] = begin_borrow [[HOME]] // CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign // CHECK: [[OBJC_RESULT:%[0-9]+]] = apply [[GETTER]]([[BORROWED_HOME]]) // CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCACSo15APPRefrigeratorCSgFZ // CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type // CHECK: [[RESULT:%[0-9]+]] = apply [[BRIDGE_FN]]([[OBJC_RESULT]], [[REFRIGERATOR_META]]) // CHECK: end_borrow [[BORROWED_HOME]] from [[HOME]] // CHECK: destroy_value [[HOME]] : $APPHouse // CHECK: return [[RESULT]] : $Refrigerator return home.fridge } // FIXME(integers): the following checks should be updated for the new integer // protocols. <rdar://problem/29939484> // XCHECK-LABEL: sil hidden @_T013objc_bridging16updateFridgeTemp{{.*}}F // XCHECK: bb0([[HOME:%[0-9]+]] : $APPHouse, [[DELTA:%[0-9]+]] : $Double): func updateFridgeTemp(_ home: APPHouse, delta: Double) { // += // XCHECK: [[PLUS_EQ:%[0-9]+]] = function_ref @_T0s2peoiySdz_SdtF // Borrowed home // CHECK: [[BORROWED_HOME:%.*]] = begin_borrow [[HOME]] // Temporary fridge // XCHECK: [[TEMP_FRIDGE:%[0-9]+]] = alloc_stack $Refrigerator // Get operation // CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign // CHECK: [[OBJC_FRIDGE:%[0-9]+]] = apply [[GETTER]]([[BORROWED_HOME]]) // CHECK: [[BRIDGE_FROM_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCACSo15APPRefrigeratorCSgFZ // CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type // CHECK: [[FRIDGE:%[0-9]+]] = apply [[BRIDGE_FROM_FN]]([[OBJC_FRIDGE]], [[REFRIGERATOR_META]]) // Addition // XCHECK: [[TEMP:%[0-9]+]] = struct_element_addr [[TEMP_FRIDGE]] : $*Refrigerator, #Refrigerator.temperature // XCHECK: apply [[PLUS_EQ]]([[TEMP]], [[DELTA]]) // Setter // XCHECK: [[FRIDGE:%[0-9]+]] = load [trivial] [[TEMP_FRIDGE]] : $*Refrigerator // XCHECK: [[SETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!setter.1.foreign // XCHECK: [[BRIDGE_TO_FN:%[0-9]+]] = function_ref @_T010Appliances12RefrigeratorV19_bridgeToObjectiveCSo15APPRefrigeratorCyF // XCHECK: [[OBJC_ARG:%[0-9]+]] = apply [[BRIDGE_TO_FN]]([[FRIDGE]]) // XCHECK: apply [[SETTER]]([[OBJC_ARG]], [[BORROWED_HOME]]) : $@convention(objc_method) (APPRefrigerator, APPHouse) -> () // XCHECK: destroy_value [[OBJC_ARG]] // XCHECK: end_borrow [[BORROWED_HOME]] from [[HOME]] // XCHECK: destroy_value [[HOME]] home.fridge.temperature += delta } // CHECK-LABEL: sil hidden @_T013objc_bridging20callNonStandardBlockySi5value_tF func callNonStandardBlock(value: Int) { // CHECK: enum $Optional<@convention(block) () -> @owned Optional<AnyObject>> takesNonStandardBlock { return value } } func takeTwoAnys(_ lhs: Any, _ rhs: Any) -> Any { return lhs } // CHECK-LABEL: sil hidden @_T013objc_bridging22defineNonStandardBlockyyp1x_tF func defineNonStandardBlock(x: Any) { // CHECK: function_ref @_T013objc_bridging22defineNonStandardBlockyyp1x_tFypypcfU_ // CHECK: function_ref @_T0ypypIxir_yXlyXlIyBya_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@in Any) -> @out Any, AnyObject) -> @autoreleased AnyObject let fn : @convention(block) (Any) -> Any = { y in takeTwoAnys(x, y) } } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypypIxir_yXlyXlIyBya_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@in Any) -> @out Any, AnyObject) -> @autoreleased AnyObject // CHECK: bb0(%0 : $*@block_storage @callee_owned (@in Any) -> @out Any, %1 : $AnyObject): // CHECK: [[T0:%.*]] = copy_value %1 : $AnyObject // CHECK: [[T1:%.*]] = open_existential_ref [[T0]] : $AnyObject // CHECK: [[ARG:%.*]] = alloc_stack $Any // CHECK: [[T2:%.*]] = init_existential_addr [[ARG]] // CHECK: store [[T1]] to [init] [[T2]] // CHECK: [[RESULT:%.*]] = alloc_stack $Any // CHECK: apply {{.*}}([[RESULT]], [[ARG]]) // CHECK-LABEL: sil hidden @_T013objc_bridging15castToCFunctionySV3ptr_tF : $@convention(thin) (UnsafeRawPointer) -> () { func castToCFunction(ptr: UnsafeRawPointer) { // CHECK: [[CASTFN:%.*]] = function_ref @_T0s13unsafeBitCastq_x_q_m2totr0_lF // CHECK: [[OUT:%.*]] = alloc_stack $@convention(c) (Optional<AnyObject>) -> () // CHECK: [[IN:%.]] = alloc_stack $UnsafeRawPointer // CHECK: store %0 to [trivial] [[IN]] : $*UnsafeRawPointer // CHECK: [[META:%.*]] = metatype $@thick (@convention(c) (Optional<AnyObject>) -> ()).Type // CHECK: apply [[CASTFN]]<UnsafeRawPointer, @convention(c) (AnyObject?) -> ()>([[OUT]], [[IN]], [[META]]) : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0, @thick τ_0_1.Type) -> @out τ_0_1 // CHECK: [[RESULT:%.*]] = load [trivial] %3 : $*@convention(c) (Optional<AnyObject>) -> () typealias Fn = @convention(c) (AnyObject?) -> Void unsafeBitCast(ptr, to: Fn.self)(nil) }
apache-2.0
1b7fc303dba3c2023356527ed1554187
55.947917
247
0.635214
3.309894
false
false
false
false
googleprojectzero/fuzzilli
Sources/Fuzzilli/FuzzIL/Program.swift
1
5050
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// Immutable unit of code that can, amongst others, be lifted, executed, scored, (de)serialized, and serve as basis for mutations. /// /// A Program's code is guaranteed to have a number of static properties, as checked by code.isStaticallyValid(): /// * All input variables must have previously been defined /// * Variables have increasing numbers starting at zero and there are no holes /// * Variables are only used while they are visible (the block they were defined in is still active) /// * Blocks are balanced and the opening and closing operations match (e.g. BeginIf is closed by EndIf) /// * The outputs of an instruction are always new variables and never overwrite an existing variable /// public final class Program { /// The immutable code of this program. public let code: Code /// The parent program that was used to construct this program. /// This is mostly only used when inspection mode is enabled to reconstruct /// the "history" of a program. public private(set) var parent: Program? = nil /// Comments attached to this program public var comments = ProgramComments() /// Everything that contributed to this program. This is not preserved across protobuf serialization. public var contributors = Contributors() /// Each program has a unique ID to identify it even accross different fuzzer instances. public private(set) lazy var id = UUID() /// Constructs an empty program. public init() { self.code = Code() self.parent = nil } /// Constructs a program with the given code. The code must be statically valid. public init(with code: Code) { assert(code.isStaticallyValid()) self.code = code } /// Construct a program with the given code and type information. public convenience init(code: Code, parent: Program? = nil, comments: ProgramComments = ProgramComments(), contributors: Contributors = Contributors()) { self.init(with: code) self.comments = comments self.contributors = contributors self.parent = parent } /// The number of instructions in this program. public var size: Int { return code.count } /// Indicates whether this program is empty. public var isEmpty: Bool { return size == 0 } public func clearParent() { parent = nil } // Create and return a deep copy of this program. public func copy() -> Program { let proto = self.asProtobuf() return try! Program(from: proto) } } extension Program: ProtobufConvertible { public typealias ProtobufType = Fuzzilli_Protobuf_Program func asProtobuf(opCache: OperationCache? = nil, typeCache: TypeCache? = nil) -> ProtobufType { return ProtobufType.with { $0.uuid = id.uuidData $0.code = code.map({ $0.asProtobuf(with: opCache) }) if !comments.isEmpty { $0.comments = comments.asProtobuf() } if let parent = parent { $0.parent = parent.asProtobuf(opCache: opCache, typeCache: typeCache) } } } public func asProtobuf() -> ProtobufType { return asProtobuf(opCache: nil, typeCache: nil) } convenience init(from proto: ProtobufType, opCache: OperationCache? = nil, typeCache: TypeCache? = nil) throws { var code = Code() for (i, protoInstr) in proto.code.enumerated() { do { code.append(try Instruction(from: protoInstr, with: opCache)) } catch FuzzilliError.instructionDecodingError(let reason) { throw FuzzilliError.programDecodingError("could not decode instruction #\(i): \(reason)") } } do { try code.check() } catch FuzzilliError.codeVerificationError(let reason) { throw FuzzilliError.programDecodingError("decoded code is not statically valid: \(reason)") } self.init(code: code) if let uuid = UUID(uuidData: proto.uuid) { self.id = uuid } self.comments = ProgramComments(from: proto.comments) if proto.hasParent { self.parent = try Program(from: proto.parent, opCache: opCache, typeCache: typeCache) } } public convenience init(from proto: ProtobufType) throws { try self.init(from: proto, opCache: nil, typeCache: nil) } }
apache-2.0
adf5ec7a95e2e0d402d1b5bd3e94926d
35.330935
157
0.658218
4.590909
false
false
false
false
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Views/Cells/AAHeaderCell.swift
2
1255
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation public class AAHeaderCell: AATableViewCell { public var titleView = UILabel() public var iconView = UIImageView() public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.backgroundColor = appStyle.vcBackyardColor selectionStyle = UITableViewCellSelectionStyle.None titleView.textColor = appStyle.cellHeaderColor titleView.font = UIFont.systemFontOfSize(14) contentView.addSubview(titleView) iconView.contentMode = UIViewContentMode.ScaleAspectFill contentView.addSubview(iconView) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func layoutSubviews() { super.layoutSubviews() let height = self.contentView.bounds.height let width = self.contentView.bounds.width titleView.frame = CGRectMake(15, height - 28, width - 48, 24) iconView.frame = CGRectMake(width - 18 - 15, height - 18 - 4, 18, 18) } }
agpl-3.0
1cfb7f4c871bcb99da7f3ce71a99c71e
31.205128
81
0.660558
5.122449
false
false
false
false
josercc/ZHTableViewGroupSwift
Sources/SwiftTableViewGroup/UICollectionView/CollectionHeaderFooter.swift
1
934
// // CollectionHeaderFooter.swift // // // Created by 张行 on 2019/7/17. // import UIKit.UICollectionView public final class CollectionHeaderView : DataContentView, ContentView, CollectionContentView { public var makeTypeBlock: ((BlockContent, CollectionHeaderView) -> Void)? public typealias View = UICollectionReusableView public init<V:UICollectionReusableView>(_ type: V.Type = V.self, _ block: MakeTypeBlock? = nil) { super.init(anyClass: V.self) self.makeTypeBlock = block } } public final class CollectionFooterView : DataContentView, ContentView, CollectionContentView { public var makeTypeBlock: ((BlockContent, CollectionFooterView) -> Void)? public typealias View = UICollectionReusableView public init<V:UICollectionReusableView>(_ type: V.Type = V.self, _ block: MakeTypeBlock? = nil) { super.init(anyClass: V.self) self.makeTypeBlock = block } }
mit
970df9288f88dd6c2c4ef947a3eeaffc
34.769231
101
0.72043
4.428571
false
false
false
false
matthewpurcell/firefox-ios
Client/Frontend/Share/ShareExtensionHelper.swift
1
5963
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import OnePasswordExtension private let log = Logger.browserLogger class ShareExtensionHelper: NSObject { private weak var selectedTab: Browser? private let selectedURL: NSURL private var onePasswordExtensionItem: NSExtensionItem! private let activities: [UIActivity] init(url: NSURL, tab: Browser?, activities: [UIActivity]) { self.selectedURL = url self.selectedTab = tab self.activities = activities } func createActivityViewController(completionHandler: (Bool) -> Void) -> UIActivityViewController { var activityItems = [AnyObject]() let printInfo = UIPrintInfo(dictionary: nil) printInfo.jobName = selectedTab?.url?.absoluteString ?? selectedURL.absoluteString printInfo.outputType = .General activityItems.append(printInfo) if let tab = selectedTab { activityItems.append(BrowserPrintPageRenderer(browser: tab)) } if let title = selectedTab?.title { activityItems.append(TitleActivityItemProvider(title: title)) } activityItems.append(self) let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: activities) // Hide 'Add to Reading List' which currently uses Safari. // We would also hide View Later, if possible, but the exclusion list doesn't currently support // third-party activity types (rdar://19430419). activityViewController.excludedActivityTypes = [ UIActivityTypeAddToReadingList, ] // This needs to be ready by the time the share menu has been displayed and // activityViewController(activityViewController:, activityType:) is called, // which is after the user taps the button. So a million cycles away. if (ShareExtensionHelper.isPasswordManagerExtensionAvailable()) { findLoginExtensionItem() } activityViewController.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in if !completed { completionHandler(completed) return } if self.isPasswordManagerActivityType(activityType) { if let logins = returnedItems { self.fillPasswords(logins) } } completionHandler(completed) } return activityViewController } } extension ShareExtensionHelper: UIActivityItemSource { func activityViewControllerPlaceholderItem(activityViewController: UIActivityViewController) -> AnyObject { if let displayURL = selectedTab?.displayURL { return displayURL } return selectedURL } func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? { if isPasswordManagerActivityType(activityType) { return onePasswordExtensionItem } else { // Return the URL for the selected tab. If we are in reader view then decode // it so that we copy the original and not the internal localhost one. if let url = selectedTab?.displayURL where ReaderModeUtils.isReaderModeURL(url) { return ReaderModeUtils.decodeURL(url) } return selectedTab?.displayURL ?? selectedURL } } func activityViewController(activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: String?) -> String { // Because of our UTI declaration, this UTI now satisfies both the 1Password Extension and the usual NSURL for Share extensions. return "org.appextension.fill-browser-action" } } private extension ShareExtensionHelper { static func isPasswordManagerExtensionAvailable() -> Bool { return OnePasswordExtension.sharedExtension().isAppExtensionAvailable() } func isPasswordManagerActivityType(activityType: String?) -> Bool { if (!ShareExtensionHelper.isPasswordManagerExtensionAvailable()) { return false } // A 'password' substring covers the most cases, such as pwsafe and 1Password. // com.agilebits.onepassword-ios.extension // com.app77.ios.pwsafe2.find-login-action-password-actionExtension // If your extension's bundle identifier does not contain "password", simply submit a pull request by adding your bundle identifier. return (activityType?.rangeOfString("password") != nil) || (activityType == "com.lastpass.ilastpass.LastPassExt") } func findLoginExtensionItem() { guard let selectedWebView = selectedTab?.webView else { return } // Add 1Password to share sheet OnePasswordExtension.sharedExtension().createExtensionItemForWebView(selectedWebView, completion: {(extensionItem, error) -> Void in if extensionItem == nil { log.error("Failed to create the password manager extension item: \(error).") return } // Set the 1Password extension item property self.onePasswordExtensionItem = extensionItem }) } func fillPasswords(returnedItems: [AnyObject]) { guard let selectedWebView = selectedTab?.webView else { return } OnePasswordExtension.sharedExtension().fillReturnedItems(returnedItems, intoWebView: selectedWebView, completion: { (success, returnedItemsError) -> Void in if !success { log.error("Failed to fill item into webview: \(returnedItemsError).") } }) } }
mpl-2.0
74b963e9e37be867394158fe1d5b762b
39.290541
164
0.673822
5.898121
false
false
false
false
402v/elm-lang
ElmLang/ElmLang/PocketFlowLayout.swift
1
2690
// // PocketFlowLayout.swift // ElmLang // // Created by 于天航 on 16/8/17. // Copyright © 2016年 402v. All rights reserved. // import UIKit class PocketFlowLayout: UICollectionViewFlowLayout { override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let layoutAttrs = super.layoutAttributesForElements(in: rect) var decorationAttrs = [UICollectionViewLayoutAttributes]() let indexPaths: [IndexPath] = self.indexPathsOfSeparators(of: rect) for indexPath in indexPaths { if let attrs = self.layoutAttributesForDecorationView(ofKind: "Separator", at: indexPath) { decorationAttrs.append(attrs) } } if layoutAttrs != nil { let retAry = layoutAttrs! + decorationAttrs return retAry } else { return nil } } override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let decorationOffset = CGFloat(indexPath.row + 1) * self.itemSize.height + CGFloat(indexPath.row) * self.minimumLineSpacing if let attrs: UICollectionViewLayoutAttributes = UICollectionViewLayoutAttributes(forDecorationViewOfKind: elementKind, with: indexPath) { attrs.frame = CGRect(x: 0, y: decorationOffset, width: self.collectionViewContentSize.width, height: self.minimumLineSpacing) attrs.zIndex = 1000 return attrs } else { return nil } } override func initialLayoutAttributesForAppearingDecorationElement(ofKind elementKind: String, at decorationIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if let attrs = self.layoutAttributesForDecorationView(ofKind: elementKind, at: decorationIndexPath) { return attrs } else { return nil } } // MARK: - private func indexPathsOfSeparators(of rect: CGRect) -> [IndexPath] { let firstCellIndexToShow = Int(rect.origin.y / self.itemSize.height) let lastCellIndexToShow = Int((rect.origin.y + rect.height) / self.itemSize.height) var indexPaths = [IndexPath]() if let collectionView = self.collectionView { let count = collectionView.dataSource?.collectionView(collectionView, numberOfItemsInSection: 0) for i in stride(from: max(firstCellIndexToShow, 0), to: lastCellIndexToShow, by: 1) { if i < count! { indexPaths.append(IndexPath(row: i, section: 0)) } } } return indexPaths } }
gpl-3.0
5d76a374e32ae70641c3285ccd064bb3
35.726027
172
0.656471
5.175676
false
false
false
false
shotscopebot/MKRingProgressView
MKRingProgressView/MKGradientGenerator.swift
1
10564
/* The MIT License (MIT) Copyright (c) 2015 Max Konovalov 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 // MARK: - Gradient Generator public enum GradientType: Int { case linear case radial case conical case bilinear } open class MKGradientGenerator { open class func gradientImage(type: GradientType, size: CGSize, colors: [CGColor], colors2: [CGColor]? = nil, locations: [Float]? = nil, locations2: [Float]? = nil, startPoint: CGPoint? = nil, endPoint: CGPoint? = nil, startPoint2: CGPoint? = nil, endPoint2: CGPoint? = nil, scale: CGFloat? = nil) -> CGImage { let w = Int(size.width * (scale ?? UIScreen.main.scale)) let h = Int(size.height * (scale ?? UIScreen.main.scale)) let bitsPerComponent: Int = MemoryLayout<UInt8>.size * 8 let bytesPerPixel: Int = bitsPerComponent * 4 / 8 let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) var data = [RGBA]() for y in 0..<h { for x in 0..<w { let c = pixelDataForGradient(type, colors: [colors, colors2], locations: [locations, locations2], startPoints: [startPoint, startPoint2], endPoints: [endPoint, endPoint2], point: CGPoint(x: x, y: y), size: CGSize(width: w, height: h)) data.append(c) } } let ctx = CGContext(data: &data, width: w, height: h, bitsPerComponent: bitsPerComponent, bytesPerRow: w * bytesPerPixel, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) let img = ctx?.makeImage()! return img! } fileprivate class func pixelDataForGradient(_ gradientType: GradientType, colors: [[CGColor]?], locations: [[Float]?], startPoints: [CGPoint?], endPoints: [CGPoint?], point: CGPoint, size: CGSize) -> RGBA { assert(colors.count > 0) var colors = colors var locations = locations var startPoints = startPoints var endPoints = endPoints if gradientType == .bilinear && colors.count == 1 { colors.append([UIColor.clear.cgColor]) } for (index, colorArray) in colors.enumerated() { if gradientType != .bilinear && index > 0 { continue } if colorArray == nil { colors[index] = [UIColor.clear.cgColor] } if locations.count <= index { locations.append(uniformLocationsWithCount(colorArray!.count)) } else if locations[index] == nil { locations[index] = uniformLocationsWithCount(colorArray!.count) } if startPoints.count <= index { startPoints.append(nil) } if endPoints.count <= index { endPoints.append(nil) } } switch gradientType { case .linear: let g0 = startPoints[0] ?? CGPoint(x: 0.5, y: 0.0) let g1 = endPoints[0] ?? CGPoint(x: 0.5, y: 1.0) let t = linearGradientStop(point, size, g0, g1) return interpolatedColor(t, colors[0]!, locations[0]!) case .radial: let g0 = startPoints[0] ?? CGPoint(x: 0.5, y: 0.5) let g1 = endPoints[0] ?? CGPoint(x: 1.0, y: 0.5) let t = radialGradientStop(point, size, g0, g1) return interpolatedColor(t, colors[0]!, locations[0]!) case .conical: let g0 = startPoints[0] ?? CGPoint(x: 0.5, y: 0.5) let g1 = endPoints[0] ?? CGPoint(x: 1.0, y: 0.5) let t = conicalGradientStop(point, size, g0, g1) return interpolatedColor(t, colors[0]!, locations[0]!) case .bilinear: let g0x = startPoints[0] ?? CGPoint(x: 0.0, y: 0.5) let g1x = endPoints[0] ?? CGPoint(x: 1.0, y: 0.5) let tx = linearGradientStop(point, size, g0x, g1x) let g0y = startPoints[1] ?? CGPoint(x: 0.5, y: 0.0) let g1y = endPoints[1] ?? CGPoint(x: 0.5, y: 1.0) let ty = linearGradientStop(point, size, g0y, g1y) let c1 = interpolatedColor(tx, colors[0]!, locations[0]!) let c2 = interpolatedColor(tx, colors[1]!, locations[1]!) let c = interpolatedColor(ty, [c1.cgColor, c2.cgColor], [0.0, 1.0]) return c } } fileprivate class func uniformLocationsWithCount(_ count: Int) -> [Float] { var locations = [Float]() for i in 0..<count { locations.append(Float(i)/Float(count-1)) } return locations } fileprivate class func linearGradientStop(_ point: CGPoint, _ size: CGSize, _ g0: CGPoint, _ g1: CGPoint) -> Float { let s = CGPoint(x: size.width * (g1.x - g0.x), y: size.height * (g1.y - g0.y)) let p = CGPoint(x: point.x - size.width * g0.x, y: point.y - size.height * g0.y) let t = (p.x * s.x + p.y * s.y) / (s.x * s.x + s.y * s.y) return Float(t) } fileprivate class func radialGradientStop(_ point: CGPoint, _ size: CGSize, _ g0: CGPoint, _ g1: CGPoint) -> Float { let c = CGPoint(x: size.width * g0.x, y: size.height * g0.y) let s = CGPoint(x: size.width * (g1.x - g0.x), y: size.height * (g1.y - g0.y)) let d = sqrt(s.x * s.x + s.y * s.y) let p = CGPoint(x: point.x - c.x, y: point.y - c.y) let r = sqrt(p.x * p.x + p.y * p.y) let t = r / d return Float(t) } fileprivate class func conicalGradientStop(_ point: CGPoint, _ size: CGSize, _ g0: CGPoint, _ g1: CGPoint) -> Float { let c = CGPoint(x: size.width * g0.x, y: size.height * g0.y) let s = CGPoint(x: size.width * (g1.x - g0.x), y: size.height * (g1.y - g0.y)) let q = atan2(s.y, s.x) let p = CGPoint(x: point.x - c.x, y: point.y - c.y) var a = atan2(p.y, p.x) - q if a < 0 { a += 2 * π } let t = a / (2 * π) return Float(t) } fileprivate class func interpolatedColor(_ t: Float, _ colors: [CGColor], _ locations: [Float]) -> RGBA { assert(!colors.isEmpty) assert(colors.count == locations.count) var p0: Float = 0 var p1: Float = 1 var c0 = colors.first! var c1 = colors.last! for (i, v) in locations.enumerated() { if v > p0 && t >= v { p0 = v c0 = colors[i] } if v < p1 && t <= v { p1 = v c1 = colors[i] } } let p: Float if p0 == p1 { p = 0 } else { p = lerp(t, inRange: p0...p1, outRange: 0...1) } let color0 = RGBA(c0) let color1 = RGBA(c1) return color0.interpolateTo(color1, p) } } // MARK: - Color Data fileprivate struct RGBA { var r: UInt8 var g: UInt8 var b: UInt8 var a: UInt8 } extension RGBA: Equatable { } fileprivate func ==(lhs: RGBA, rhs: RGBA) -> Bool { return (lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b && lhs.a == rhs.a) } extension RGBA { fileprivate init() { self.init(r: 0, g: 0, b: 0, a: 0) } fileprivate init(_ hex: Int) { let r = UInt8((hex >> 16) & 0xff) let g = UInt8((hex >> 08) & 0xff) let b = UInt8((hex >> 00) & 0xff) self.init(r: r, g: g, b: b, a: 0xff) } fileprivate init(_ color: UIColor) { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 color.getRed(&r, green: &g, blue: &b, alpha: &a) self.init(r: UInt8(r * 0xff), g: UInt8(g * 0xff), b: UInt8(b * 0xff), a: UInt8(a * 0xff)) } fileprivate init(_ color: CGColor) { let c = color.components?.map { min(max($0, 0.0), 1.0) } switch color.numberOfComponents { case 2: self.init(r: UInt8((c?[0])! * 0xff), g: UInt8((c?[0])! * 0xff), b: UInt8((c?[0])! * 0xff), a: UInt8((c?[1])! * 0xff)) case 4: self.init(r: UInt8((c?[0])! * 0xff), g: UInt8((c?[1])! * 0xff), b: UInt8((c?[2])! * 0xff), a: UInt8((c?[3])! * 0xff)) default: self.init() } } fileprivate var uiColor: UIColor { return UIColor(red: CGFloat(r)/0xff, green: CGFloat(g)/0xff, blue: CGFloat(b)/0xff, alpha: CGFloat(a)/0xff) } fileprivate var cgColor: CGColor { return self.uiColor.cgColor } fileprivate func interpolateTo(_ color: RGBA, _ t: Float) -> RGBA { let r = lerp(t, self.r, color.r) let g = lerp(t, self.g, color.g) let b = lerp(t, self.b, color.b) let a = lerp(t, self.a, color.a) return RGBA(r: r, g: g, b: b, a: a) } } // MARK: - Utility fileprivate let π = CGFloat.pi fileprivate func lerp(_ t: Float, _ a: UInt8, _ b: UInt8) -> UInt8 { return UInt8(Float(a) + min(max(t, 0), 1) * (Float(b) - Float(a))) } fileprivate func lerp(_ value: Float, inRange: ClosedRange<Float>, outRange: ClosedRange<Float>) -> Float { return (value - inRange.lowerBound) * (outRange.upperBound - outRange.lowerBound) / (inRange.upperBound - inRange.lowerBound) + outRange.lowerBound } // MARK: - Extensions extension Array { fileprivate subscript (safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } }
mit
912e12a77ffeee11f4725e5fae5d80f8
35.797909
314
0.558754
3.564293
false
false
false
false
craig86322/Learning-Swift
ClosureExercises.playground/section-1.swift
1
3855
// Closure Exercises. import UIKit // Arrays **************************************************** // Three ways to create an empty Int array /* var array1 = Array<Int>() var array2 = [Int]() var array3: [Int] = [] // Load empty arrays with data sets let ARRAYMAX = 10 var odds:[Int] = [] var evens:[Int] = [] var randoms:[Int] = [] var alphas:[Character] = [] // Load with even numbers for i in 1...ARRAYMAX { if i % 2 == 0 { evens.append(i) } } println("evens: \(evens)") // Load with odd numbers for var i=0; i<=ARRAYMAX; i++ { if i % 2 == 1 { odds.append(i) } } println("odds: \(odds)") // Load with random numbers for i in 1...ARRAYMAX { randoms.append(Int(arc4random_uniform(20))) } println("randoms: \(randoms)") // Load with the alphabet let alphabet = "abcdefghijklmnopqrstuvwxyz" for c in alphabet { alphas.append(c) } println(alphas) */ // Map *************************************************************** println("map()") // Convert an array of temperatures in F to C // C = (F - 32) * ( 5 / 9) // F = C * ( 9 / 5 ) + 32 var degreesF = [-10.5, 32.0, 60.9, 80.3, 100.9, 115] // Pass the temperature conversion forumla to map() via a named function func cToF (t:Double) -> Double { return ( t - 32 ) * (5 / 9 ) } var degreesC = degreesF.map(cToF) println("1: \(degreesC)") // Pass the forumla to map() via a closure println("2: \(degreesF.map({($0 - 32) * (5 / 9)}))") // Create a string with 'C' appended to the temp and lose most of the decimals var degreesC2 = degreesC.map({"\(round($0))C"}) println("3: \(degreesC2)") // Tricky point to note: Set the temperature array to all integers var degreesFInt = [-10, 32, 60, 80, 100, 115] var degreesC3 = degreesFInt.map({($0 - 32) * (5 / 9)}) // Prints '0' for each temp because the compiler infers integer math so 5/9 is truncated to 0 println("4: \(degreesC3)") // Filter ********************************************************** /* println("filter()") // Use filter() to create arrays of even and odd numbers var numbers:[Int] = [] for var i=0; i<=10; i++ { numbers.append(i) } // pass a funtion to filter on odd numbers func oddFunc (x:Int) -> Bool { return x % 2 == 1 } println("\(numbers.filter(oddFunc))") // filter using closures let evens = numbers.filter({($0 % 2) == 0}) let odds = numbers.filter({($0 % 2) == 1}) println(evens) println(odds) */ // Reduce ************************************************************ /* println("reduce()") // Init an array with digits from 0...10 var numbers2:[Int] = [] for var i=0; i<=10; i++ { numbers2.append(i) } // pass a function to add all the numbers func addEmUp(x:Int, y:Int)->Int { return x+y } println("\(numbers2.reduce(0,addEmUp))") // Add them up using a closure println("\(numbers2.reduce(0,{$0 + $1}))") // A compact version of the same reduce operation println("\(numbers2.reduce(0,+))") // Add them up starting at 100 println("\(numbers2.reduce(100,+))") */ // Sort ******************************************************************** /* println("sort()") var nums = [5, 0, 9, 1, 3, 0, 8, 4] // the sort method sorts its own array // verbose version, using variable names and a return statement nums.sort({ x, y in return x > y }) println(nums) // more compactly, using default variables and implied return nums.sort({$0 > $1}) println("\(nums)") // even more compactly, only the operator, everything else implied nums.sort(>) println(nums) // Note that nums.sort() sorts itself, but doesn't return a new array var newsort = nums.sort(<) // instead use... var newsort2 = nums // then newsort2.sort(>) println(newsort2) // Since no value is returned that's also why it doesn't work like you might expect in println() println("\(nums.sort(>)), \(nums)") // first arg returns (), second returns the array sorted by the first arg */
mit
f869fe9d4e3b66c5316f8f10d1eddb52
22.506098
109
0.58703
3.292058
false
false
false
false
tadija/mappable
Tests/MappableTests/Models.swift
1
776
import Mappable struct User: Mappable { let id: Int let login: String init(map: [String : Any]) throws { id = try map.value(forKey: "id") login = try map.value(forKey: "login") } } struct Repo: Mappable { let id: Int let name: String let `private`: Bool let owner: User init(map: [String : Any]) throws { id = try map.value(forKey: "id") name = try map.value(forKey: "name") `private` = try map.value(forKey: "private") owner = try map.mappable(forKey: "owner") } } struct Profile: Mappable { let user: User let repos: [Repo] init(map: [String : Any]) throws { user = try User(map: map) repos = try map.mappableArray(forKey: "repos") } }
mit
ac501c8c76f048dcd09b6ca47067554d
21.171429
54
0.561856
3.511312
false
false
false
false
jasonhenderson/examples-ios
WebServices/Pods/Unbox/Sources/UnboxableCollection.swift
5
2429
/** * Unbox * Copyright (c) 2015-2017 John Sundell * Licensed under the MIT license, see LICENSE file */ import Foundation // MARK: - Protocol /// Protocol used to enable collections to be unboxed. Default implementations exist for Array & Dictionary public protocol UnboxableCollection: Collection, UnboxCompatible { /// The value type that this collection contains associatedtype UnboxValue /// Unbox a value into a collection, optionally allowing invalid elements static func unbox<T: UnboxCollectionElementTransformer>(value: Any, allowInvalidElements: Bool, transformer: T) throws -> Self? where T.UnboxedElement == UnboxValue } // MARK: - Default implementations // Default implementation of `UnboxCompatible` for collections public extension UnboxableCollection { public static func unbox(value: Any, allowInvalidCollectionElements: Bool) throws -> Self? { if let matchingCollection = value as? Self { return matchingCollection } if let unboxableType = UnboxValue.self as? Unboxable.Type { let transformer = UnboxCollectionElementClosureTransformer<UnboxableDictionary, UnboxValue>() { element in let unboxer = Unboxer(dictionary: element) return try unboxableType.init(unboxer: unboxer) as? UnboxValue } return try self.unbox(value: value, allowInvalidElements: allowInvalidCollectionElements, transformer: transformer) } if let unboxCompatibleType = UnboxValue.self as? UnboxCompatible.Type { let transformer = UnboxCollectionElementClosureTransformer<Any, UnboxValue>() { element in return try unboxCompatibleType.unbox(value: element, allowInvalidCollectionElements: allowInvalidCollectionElements) as? UnboxValue } return try self.unbox(value: value, allowInvalidElements: allowInvalidCollectionElements, transformer: transformer) } throw UnboxPathError.invalidCollectionElementType(UnboxValue.self) } } // MARK: - Utility types private class UnboxCollectionElementClosureTransformer<I, O>: UnboxCollectionElementTransformer { private let closure: (I) throws -> O? init(closure: @escaping (I) throws -> O?) { self.closure = closure } func unbox(element: I, allowInvalidCollectionElements: Bool) throws -> O? { return try self.closure(element) } }
gpl-3.0
71db6961172d22f85920185780fb41fd
38.177419
168
0.716344
5.397778
false
false
false
false
ioser-udacity/PitchPerfect
PitchPerfect/RecordSoundsViewController.swift
1
3230
// // ViewController.swift // PitchPerfect // // Created by Richard E Millet on 3/4/15. // Copyright (c) 2015 remillet. All rights reserved. // import UIKit import AVFoundation class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate { @IBOutlet weak var startRecordingButton: UIButton! @IBOutlet weak var stopRecordingButton: UIButton! @IBOutlet weak var recordingMessageLabel: UILabel! var audioRecorder: AVAudioRecorder! func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) { if flag { var recordedAudio = RecordedAudio(filePathUrl: recorder.url, title: recorder.url.lastPathComponent!) performSegueWithIdentifier("stopRecording", sender: recordedAudio) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func recordAudio(sender: UIButton) { // Show and hide ui components self.recordingMessageLabel.hidden = false self.stopRecordingButton.hidden = false self.startRecordingButton.enabled = false println("Recording in progress...") // Setup to get current date and time to use as audio file name let currentDateTime = NSDate() let formatter = NSDateFormatter() formatter.dateFormat = "ddMMyyyy-HHmmss" let recordingName = formatter.stringFromDate(currentDateTime)+".wav" // Pick a place to store the audio file we're going to record let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String let pathArray = [dirPath, recordingName] let filePath = NSURL.fileURLWithPathComponents(pathArray) println(filePath) // Not sure what these two lines are doing var session = AVAudioSession.sharedInstance() session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil) // Record some audio and save it. audioRecorder = AVAudioRecorder(URL: filePath, settings: nil, error: nil) audioRecorder.delegate = self // set ouself as an AVAudioRecorderDelegate delegate audioRecorder.meteringEnabled = true audioRecorder.record() } @IBAction func stopRecordingAudio(sender: UIButton) { audioRecorder.stop() self.recordingMessageLabel.hidden = true self.stopRecordingButton.hidden = true self.startRecordingButton.enabled = true } override func viewWillAppear(animated: Bool) { stopRecordingButton.hidden = true // Not sure what these two lines are doing var audioSession = AVAudioSession.sharedInstance() audioSession.setActive(false, error: 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. if let playSoundViewController = segue.destinationViewController as? PlaySoundsViewController { playSoundViewController.recordedAudio = sender as? RecordedAudio } println("prepareForSegue") } }
apache-2.0
0d657e97956d1e21fd07c5df34b08977
33.361702
107
0.771207
4.530154
false
false
false
false
dnevera/ImageMetalling
ImageMetalling-14/ImageMetalling-14/AppDelegate.swift
1
1009
// // AppDelegate.swift // ImageMetalling-14 // // Created by denis svinarchuk on 16.05.2018. // Copyright © 2018 Dehancer. All rights reserved. // import AppKit import IMProcessing import IMProcessingUI import ImageIO @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSOpenSavePanelDelegate { lazy var openPanel:NSOpenPanel = { let p = NSOpenPanel() p.canChooseFiles = true p.canChooseDirectories = false p.resolvesAliases = true p.isExtensionHidden = false p.allowedFileTypes = [ "jpg", "JPEG", "TIFF", "TIF", "PNG", "JPG", "dng", "DNG", "CR2", "ORF" ] return p }() @IBAction func openFile(_ sender: NSMenuItem) { if openPanel.runModal() == NSApplication.ModalResponse.OK { if let path = openPanel.urls.first?.path { (NSApplication.shared.keyWindow?.contentViewController as? ViewController)?.imagePath = path } } } }
mit
5e87e618df240170a6d1e40a7672564f
25.526316
108
0.625
4.421053
false
false
false
false
arvedviehweger/swift
stdlib/public/core/CompilerProtocols.swift
1
34857
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Intrinsic protocols shared with the compiler //===----------------------------------------------------------------------===// /// A type that can be converted to and from an associated raw value. /// /// With a `RawRepresentable` type, you can switch back and forth between a /// custom type and an associated `RawValue` type without losing the value of /// the original `RawRepresentable` type. Using the raw value of a conforming /// type streamlines interoperation with Objective-C and legacy APIs and /// simplifies conformance to other protocols, such as `Equatable`, /// `Comparable`, and `Hashable`. /// /// The `RawRepresentable` protocol is seen mainly in two categories of types: /// enumerations with raw value types and option sets. /// /// Enumerations with Raw Values /// ============================ /// /// For any enumeration with a string, integer, or floating-point raw type, the /// Swift compiler automatically adds `RawRepresentable` conformance. When /// defining your own custom enumeration, you give it a raw type by specifying /// the raw type as the first item in the enumeration's type inheritance list. /// You can also use literals to specify values for one or more cases. /// /// For example, the `Counter` enumeration defined here has an `Int` raw value /// type and gives the first case a raw value of `1`: /// /// enum Counter: Int { /// case one = 1, two, three, four, five /// } /// /// You can create a `Counter` instance from an integer value between 1 and 5 /// by using the `init?(rawValue:)` initializer declared in the /// `RawRepresentable` protocol. This initializer is failable because although /// every case of the `Counter` type has a corresponding `Int` value, there /// are many `Int` values that *don't* correspond to a case of `Counter`. /// /// for i in 3...6 { /// print(Counter(rawValue: i)) /// } /// // Prints "Optional(Counter.three)" /// // Prints "Optional(Counter.four)" /// // Prints "Optional(Counter.five)" /// // Prints "nil" /// /// Option Sets /// =========== /// /// Option sets all conform to `RawRepresentable` by inheritance using the /// `OptionSet` protocol. Whether using an option set or creating your own, /// you use the raw value of an option set instance to store the instance's /// bitfield. The raw value must therefore be of a type that conforms to the /// `FixedWidthInteger` protocol, such as `UInt8` or `Int`. For example, the /// `Direction` type defines an option set for the four directions you can /// move in a game. /// /// struct Directions: OptionSet { /// let rawValue: UInt8 /// /// static let up = Directions(rawValue: 1 << 0) /// static let down = Directions(rawValue: 1 << 1) /// static let left = Directions(rawValue: 1 << 2) /// static let right = Directions(rawValue: 1 << 3) /// } /// /// Unlike enumerations, option sets provide a nonfailable `init(rawValue:)` /// initializer to convert from a raw value, because option sets don't have an /// enumerated list of all possible cases. Option set values have /// a one-to-one correspondence with their associated raw values. /// /// In the case of the `Directions` option set, an instance can contain zero, /// one, or more of the four defined directions. This example declares a /// constant with three currently allowed moves. The raw value of the /// `allowedMoves` instance is the result of the bitwise OR of its three /// members' raw values: /// /// let allowedMoves: Directions = [.up, .down, .left] /// print(allowedMoves.rawValue) /// // Prints "7" /// /// Option sets use bitwise operations on their associated raw values to /// implement their mathematical set operations. For example, the `contains()` /// method on `allowedMoves` performs a bitwise AND operation to check whether /// the option set contains an element. /// /// print(allowedMoves.contains(.right)) /// // Prints "false" /// print(allowedMoves.rawValue & Directions.right.rawValue) /// // Prints "0" /// /// - SeeAlso: `OptionSet`, `FixedWidthInteger` public protocol RawRepresentable { /// The raw type that can be used to represent all values of the conforming /// type. /// /// Every distinct value of the conforming type has a corresponding unique /// value of the `RawValue` type, but there may be values of the `RawValue` /// type that don't have a corresponding value of the conforming type. associatedtype RawValue /// Creates a new instance with the specified raw value. /// /// If there is no value of the type that corresponds with the specified raw /// value, this initializer returns `nil`. For example: /// /// enum PaperSize: String { /// case A4, A5, Letter, Legal /// } /// /// print(PaperSize(rawValue: "Legal")) /// // Prints "Optional("PaperSize.Legal")" /// /// print(PaperSize(rawValue: "Tabloid")) /// // Prints "nil" /// /// - Parameter rawValue: The raw value to use for the new instance. init?(rawValue: RawValue) /// The corresponding value of the raw type. /// /// A new instance initialized with `rawValue` will be equivalent to this /// instance. For example: /// /// enum PaperSize: String { /// case A4, A5, Letter, Legal /// } /// /// let selectedSize = PaperSize.Letter /// print(selectedSize.rawValue) /// // Prints "Letter" /// /// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!) /// // Prints "true" var rawValue: RawValue { get } } /// Returns a Boolean value indicating whether the two arguments are equal. /// /// - Parameters: /// - lhs: A raw-representable instance. /// - rhs: A second raw-representable instance. public func == <T : RawRepresentable>(lhs: T, rhs: T) -> Bool where T.RawValue : Equatable { return lhs.rawValue == rhs.rawValue } /// Returns a Boolean value indicating whether the two arguments are not equal. /// /// - Parameters: /// - lhs: A raw-representable instance. /// - rhs: A second raw-representable instance. public func != <T : RawRepresentable>(lhs: T, rhs: T) -> Bool where T.RawValue : Equatable { return lhs.rawValue != rhs.rawValue } // This overload is needed for ambiguity resolution against the // implementation of != for T : Equatable /// Returns a Boolean value indicating whether the two arguments are not equal. /// /// - Parameters: /// - lhs: A raw-representable instance. /// - rhs: A second raw-representable instance. public func != <T : Equatable>(lhs: T, rhs: T) -> Bool where T : RawRepresentable, T.RawValue : Equatable { return lhs.rawValue != rhs.rawValue } /// A type that can be initialized using the nil literal, `nil`. /// /// `nil` has a specific meaning in Swift---the absence of a value. Only the /// `Optional` type conforms to `ExpressibleByNilLiteral`. /// `ExpressibleByNilLiteral` conformance for types that use `nil` for other /// purposes is discouraged. /// /// - SeeAlso: `Optional` public protocol ExpressibleByNilLiteral { /// Creates an instance initialized with `nil`. init(nilLiteral: ()) } public protocol _ExpressibleByBuiltinIntegerLiteral { init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) } /// A type that can be initialized with an integer literal. /// /// The standard library integer and floating-point types, such as `Int` and /// `Double`, conform to the `ExpressibleByIntegerLiteral` protocol. You can /// initialize a variable or constant of any of these types by assigning an /// integer literal. /// /// // Type inferred as 'Int' /// let cookieCount = 12 /// /// // An array of 'Int' /// let chipsPerCookie = [21, 22, 25, 23, 24, 19] /// /// // A floating-point value initialized using an integer literal /// let redPercentage: Double = 1 /// // redPercentage == 1.0 /// /// Conforming to ExpressibleByIntegerLiteral /// ========================================= /// /// To add `ExpressibleByIntegerLiteral` conformance to your custom type, /// implement the required initializer. public protocol ExpressibleByIntegerLiteral { /// A type that represents an integer literal. /// /// The standard library integer and floating-point types are all valid types /// for `IntegerLiteralType`. associatedtype IntegerLiteralType : _ExpressibleByBuiltinIntegerLiteral /// Creates an instance initialized to the specified integer value. /// /// Do not call this initializer directly. Instead, initialize a variable or /// constant using an integer literal. For example: /// /// let x = 23 /// /// In this example, the assignment to the `x` constant calls this integer /// literal initializer behind the scenes. /// /// - Parameter value: The value to create. init(integerLiteral value: IntegerLiteralType) } public protocol _ExpressibleByBuiltinFloatLiteral { init(_builtinFloatLiteral value: _MaxBuiltinFloatType) } /// A type that can be initialized with a floating-point literal. /// /// The standard library floating-point types---`Float`, `Double`, and /// `Float80` where available---all conform to the `ExpressibleByFloatLiteral` /// protocol. You can initialize a variable or constant of any of these types /// by assigning a floating-point literal. /// /// // Type inferred as 'Double' /// let threshold = 6.0 /// /// // An array of 'Double' /// let measurements = [2.2, 4.1, 3.65, 4.2, 9.1] /// /// Conforming to ExpressibleByFloatLiteral /// ======================================= /// /// To add `ExpressibleByFloatLiteral` conformance to your custom type, /// implement the required initializer. public protocol ExpressibleByFloatLiteral { /// A type that represents a floating-point literal. /// /// Valid types for `FloatLiteralType` are `Float`, `Double`, and `Float80` /// where available. associatedtype FloatLiteralType : _ExpressibleByBuiltinFloatLiteral /// Creates an instance initialized to the specified floating-point value. /// /// Do not call this initializer directly. Instead, initialize a variable or /// constant using a floating-point literal. For example: /// /// let x = 21.5 /// /// In this example, the assignment to the `x` constant calls this /// floating-point literal initializer behind the scenes. /// /// - Parameter value: The value to create. init(floatLiteral value: FloatLiteralType) } public protocol _ExpressibleByBuiltinBooleanLiteral { init(_builtinBooleanLiteral value: Builtin.Int1) } /// A type that can be initialized with the Boolean literals `true` and /// `false`. /// /// Only three types provided by Swift---`Bool`, `DarwinBoolean`, and /// `ObjCBool`---are treated as Boolean values. Expanding this set to include /// types that represent more than simple Boolean values is discouraged. /// /// To add `ExpressibleByBooleanLiteral` conformance to your custom type, /// implement the `init(booleanLiteral:)` initializer that creates an instance /// of your type with the given Boolean value. public protocol ExpressibleByBooleanLiteral { /// A type that represents a Boolean literal, such as `Bool`. associatedtype BooleanLiteralType : _ExpressibleByBuiltinBooleanLiteral /// Creates an instance initialized to the given Boolean value. /// /// Do not call this initializer directly. Instead, initialize a variable or /// constant using one of the Boolean literals `true` and `false`. For /// example: /// /// let twasBrillig = true /// /// In this example, the assignment to the `twasBrillig` constant calls this /// Boolean literal initializer behind the scenes. /// /// - Parameter value: The value of the new instance. init(booleanLiteral value: BooleanLiteralType) } public protocol _ExpressibleByBuiltinUnicodeScalarLiteral { init(_builtinUnicodeScalarLiteral value: Builtin.Int32) } /// A type that can be initialized with a string literal containing a single /// Unicode scalar value. /// /// The `String`, `StaticString`, `Character`, and `UnicodeScalar` types all /// conform to the `ExpressibleByUnicodeScalarLiteral` protocol. You can /// initialize a variable of any of these types using a string literal that /// holds a single Unicode scalar. /// /// let ñ: UnicodeScalar = "ñ" /// print(ñ) /// // Prints "ñ" /// /// Conforming to ExpressibleByUnicodeScalarLiteral /// =============================================== /// /// To add `ExpressibleByUnicodeScalarLiteral` conformance to your custom type, /// implement the required initializer. public protocol ExpressibleByUnicodeScalarLiteral { /// A type that represents a Unicode scalar literal. /// /// Valid types for `UnicodeScalarLiteralType` are `UnicodeScalar`, /// `Character`, `String`, and `StaticString`. associatedtype UnicodeScalarLiteralType : _ExpressibleByBuiltinUnicodeScalarLiteral /// Creates an instance initialized to the given value. /// /// - Parameter value: The value of the new instance. init(unicodeScalarLiteral value: UnicodeScalarLiteralType) } public protocol _ExpressibleByBuiltinExtendedGraphemeClusterLiteral : _ExpressibleByBuiltinUnicodeScalarLiteral { init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) } /// A type that can be initialized with a string literal containing a single /// extended grapheme cluster. /// /// An *extended grapheme cluster* is a group of one or more Unicode code /// points that approximates a single user-perceived character. Many /// individual characters, such as "é", "김", and "🇮🇳", can be made up of /// multiple Unicode code points. These code points are combined by Unicode's /// boundary algorithms into extended grapheme clusters. /// /// The `String`, `StaticString`, and `Character` types conform to the /// `ExpressibleByExtendedGraphemeClusterLiteral` protocol. You can initialize a /// variable or constant of any of these types using a string literal that /// holds a single character. /// /// let snowflake: Character = "❄︎" /// print(snowflake) /// // Prints "❄︎" /// /// Conforming to ExpressibleByExtendedGraphemeClusterLiteral /// ========================================================= /// /// To add `ExpressibleByExtendedGraphemeClusterLiteral` conformance to your /// custom type, implement the required initializer. public protocol ExpressibleByExtendedGraphemeClusterLiteral : ExpressibleByUnicodeScalarLiteral { /// A type that represents an extended grapheme cluster literal. /// /// Valid types for `ExtendedGraphemeClusterLiteralType` are `Character`, /// `String`, and `StaticString`. associatedtype ExtendedGraphemeClusterLiteralType : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral /// Creates an instance initialized to the given value. /// /// - Parameter value: The value of the new instance. init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) } extension ExpressibleByExtendedGraphemeClusterLiteral where ExtendedGraphemeClusterLiteralType == UnicodeScalarLiteralType { @_transparent public init(unicodeScalarLiteral value: ExtendedGraphemeClusterLiteralType) { self.init(extendedGraphemeClusterLiteral: value) } } public protocol _ExpressibleByBuiltinStringLiteral : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral { init( _builtinStringLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) } public protocol _ExpressibleByBuiltinUTF16StringLiteral : _ExpressibleByBuiltinStringLiteral { init( _builtinUTF16StringLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word) } public protocol _ExpressibleByBuiltinConstStringLiteral : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral { init(_builtinConstStringLiteral constantString: Builtin.RawPointer) } public protocol _ExpressibleByBuiltinConstUTF16StringLiteral : _ExpressibleByBuiltinConstStringLiteral { init(_builtinConstUTF16StringLiteral constantUTF16String: Builtin.RawPointer) } /// A type that can be initialized with a string literal. /// /// The `String` and `StaticString` types conform to the /// `ExpressibleByStringLiteral` protocol. You can initialize a variable or /// constant of either of these types using a string literal of any length. /// /// let picnicGuest = "Deserving porcupine" /// /// Conforming to ExpressibleByStringLiteral /// ======================================== /// /// To add `ExpressibleByStringLiteral` conformance to your custom type, /// implement the required initializer. public protocol ExpressibleByStringLiteral : ExpressibleByExtendedGraphemeClusterLiteral { /// A type that represents a string literal. /// /// Valid types for `StringLiteralType` are `String` and `StaticString`. associatedtype StringLiteralType : _ExpressibleByBuiltinStringLiteral /// Creates an instance initialized to the given string value. /// /// - Parameter value: The value of the new instance. init(stringLiteral value: StringLiteralType) } extension ExpressibleByStringLiteral where StringLiteralType == ExtendedGraphemeClusterLiteralType { @_transparent public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(stringLiteral: value) } } /// A type that can be initialized using an array literal. /// /// An array literal is a simple way of expressing a list of values. Simply /// surround a comma-separated list of values, instances, or literals with /// square brackets to create an array literal. You can use an array literal /// anywhere an instance of an `ExpressibleByArrayLiteral` type is expected: as /// a value assigned to a variable or constant, as a parameter to a method or /// initializer, or even as the subject of a nonmutating operation like /// `map(_:)` or `filter(_:)`. /// /// Arrays, sets, and option sets all conform to `ExpressibleByArrayLiteral`, /// and your own custom types can as well. Here's an example of creating a set /// and an array using array literals: /// /// let employeesSet: Set<String> = ["Amir", "Jihye", "Dave", "Alessia", "Dave"] /// print(employeesSet) /// // Prints "["Amir", "Dave", "Jihye", "Alessia"]" /// /// let employeesArray: [String] = ["Amir", "Jihye", "Dave", "Alessia", "Dave"] /// print(employeesArray) /// // Prints "["Amir", "Jihye", "Dave", "Alessia", "Dave"]" /// /// The `Set` and `Array` types each handle array literals in their own way to /// create new instances. In this case, the newly created set drops the /// duplicate value ("Dave") and doesn't maintain the order of the array /// literal's elements. The new array, on the other hand, matches the order /// and number of elements provided. /// /// - Note: An array literal is not the same as an `Array` instance. You can't /// initialize a type that conforms to `ExpressibleByArrayLiteral` simply by /// assigning an existing array. /// /// let anotherSet: Set = employeesArray /// // error: cannot convert value of type '[String]' to specified type 'Set' /// /// Type Inference of Array Literals /// ================================ /// /// Whenever possible, Swift's compiler infers the full intended type of your /// array literal. Because `Array` is the default type for an array literal, /// without writing any other code, you can declare an array with a particular /// element type by providing one or more values. /// /// In this example, the compiler infers the full type of each array literal. /// /// let integers = [1, 2, 3] /// // 'integers' has type '[Int]' /// /// let strings = ["a", "b", "c"] /// // 'strings' has type '[String]' /// /// An empty array literal alone doesn't provide enough information for the /// compiler to infer the intended type of the `Array` instance. When using an /// empty array literal, specify the type of the variable or constant. /// /// var emptyArray: [Bool] = [] /// // 'emptyArray' has type '[Bool]' /// /// Because many functions and initializers fully specify the types of their /// parameters, you can often use an array literal with or without elements as /// a parameter. For example, the `sum(_:)` function shown here takes an `Int` /// array as a parameter: /// /// func sum(values: [Int]) -> Int { /// return values.reduce(0, +) /// } /// /// let sumOfFour = sum([5, 10, 15, 20]) /// // 'sumOfFour' == 50 /// /// let sumOfNone = sum([]) /// // 'sumOfNone' == 0 /// /// When you call a function that does not fully specify its parameters' types, /// use the type-cast operator (`as`) to specify the type of an array literal. /// For example, the `log(name:value:)` function shown here has an /// unconstrained generic `value` parameter. /// /// func log<T>(name name: String, value: T) { /// print("\(name): \(value)") /// } /// /// log(name: "Four integers", value: [5, 10, 15, 20]) /// // Prints "Four integers: [5, 10, 15, 20]" /// /// log(name: "Zero integers", value: [] as [Int]) /// // Prints "Zero integers: []" /// /// Conforming to ExpressibleByArrayLiteral /// ======================================= /// /// Add the capability to be initialized with an array literal to your own /// custom types by declaring an `init(arrayLiteral:)` initializer. The /// following example shows the array literal initializer for a hypothetical /// `OrderedSet` type, which has setlike semantics but maintains the order of /// its elements. /// /// struct OrderedSet<Element: Hashable>: Collection, SetAlgebra { /// // implementation details /// } /// /// extension OrderedSet: ExpressibleByArrayLiteral { /// init(arrayLiteral: Element...) { /// self.init() /// for element in arrayLiteral { /// self.append(element) /// } /// } /// } public protocol ExpressibleByArrayLiteral { /// The type of the elements of an array literal. associatedtype Element /// Creates an instance initialized with the given elements. init(arrayLiteral elements: Element...) } /// A type that can be initialized using a dictionary literal. /// /// A dictionary literal is a simple way of writing a list of key-value pairs. /// You write each key-value pair with a colon (`:`) separating the key and /// the value. The dictionary literal is made up of one or more key-value /// pairs, separated by commas and surrounded with square brackets. /// /// To declare a dictionary, assign a dictionary literal to a variable or /// constant: /// /// let countryCodes = ["BR": "Brazil", "GH": "Ghana", /// "JP": "Japan", "US": "United States"] /// // 'countryCodes' has type [String: String] /// /// print(countryCodes["BR"]!) /// // Prints "Brazil" /// /// When the context provides enough type information, you can use a special /// form of the dictionary literal, square brackets surrounding a single /// colon, to initialize an empty dictionary. /// /// var frequencies: [String: Int] = [:] /// print(frequencies.count) /// // Prints "0" /// /// - Note: A dictionary literal is *not* the same as an instance of /// `Dictionary` or the similarly named `DictionaryLiteral` type. You can't /// initialize a type that conforms to `ExpressibleByDictionaryLiteral` simply /// by assigning an instance of one of these types. /// /// Conforming to the ExpressibleByDictionaryLiteral Protocol /// ========================================================= /// /// To add the capability to be initialized with a dictionary literal to your /// own custom types, declare an `init(dictionaryLiteral:)` initializer. The /// following example shows the dictionary literal initializer for a /// hypothetical `CountedSet` type, which uses setlike semantics while keeping /// track of the count for duplicate elements: /// /// struct CountedSet<Element: Hashable>: Collection, SetAlgebra { /// // implementation details /// /// /// Updates the count stored in the set for the given element, /// /// adding the element if necessary. /// /// /// /// - Parameter n: The new count for `element`. `n` must be greater /// /// than or equal to zero. /// /// - Parameter element: The element to set the new count on. /// mutating func updateCount(_ n: Int, for element: Element) /// } /// /// extension CountedSet: ExpressibleByDictionaryLiteral { /// init(dictionaryLiteral elements: (Element, Int)...) { /// self.init() /// for (element, count) in elements { /// self.updateCount(count, for: element) /// } /// } /// } public protocol ExpressibleByDictionaryLiteral { /// The key type of a dictionary literal. associatedtype Key /// The value type of a dictionary literal. associatedtype Value /// Creates an instance initialized with the given key-value pairs. init(dictionaryLiteral elements: (Key, Value)...) } /// A type that can be initialized by string interpolation with a string /// literal that includes expressions. /// /// Use string interpolation to include one or more expressions in a string /// literal, wrapped in a set of parentheses and prefixed by a backslash. For /// example: /// /// let price = 2 /// let number = 3 /// let message = "One cookie: $\(price), \(number) cookies: $\(price * number)." /// print(message) /// // Prints "One cookie: $2, 3 cookies: $6." /// /// Conforming to the ExpressibleByStringInterpolation Protocol /// =========================================================== /// /// To use string interpolation to initialize instances of your custom type, /// implement the required initializers for `ExpressibleByStringInterpolation` /// conformance. String interpolation is a multiple-step initialization /// process. When you use string interpolation, the following steps occur: /// /// 1. The string literal is broken into pieces. Each segment of the string /// literal before, between, and after any included expressions, along with /// the individual expressions themselves, are passed to the /// `init(stringInterpolationSegment:)` initializer. /// 2. The results of those calls are passed to the /// `init(stringInterpolation:)` initializer in the order in which they /// appear in the string literal. /// /// In other words, initializing the `message` constant in the example above /// using string interpolation is equivalent to the following code: /// /// let message = String(stringInterpolation: /// String(stringInterpolationSegment: "One cookie: $"), /// String(stringInterpolationSegment: price), /// String(stringInterpolationSegment: ", "), /// String(stringInterpolationSegment: number), /// String(stringInterpolationSegment: " cookies: $"), /// String(stringInterpolationSegment: price * number), /// String(stringInterpolationSegment: ".")) @available(*, deprecated, message: "it will be replaced or redesigned in Swift 4.0. Instead of conforming to 'ExpressibleByStringInterpolation', consider adding an 'init(_:String)'") public typealias ExpressibleByStringInterpolation = _ExpressibleByStringInterpolation public protocol _ExpressibleByStringInterpolation { /// Creates an instance by concatenating the given values. /// /// Do not call this initializer directly. It is used by the compiler when /// you use string interpolation. For example: /// /// let s = "\(5) x \(2) = \(5 * 2)" /// print(s) /// // Prints "5 x 2 = 10" /// /// After calling `init(stringInterpolationSegment:)` with each segment of /// the string literal, this initializer is called with their string /// representations. /// /// - Parameter strings: An array of instances of the conforming type. init(stringInterpolation strings: Self...) /// Creates an instance containing the appropriate representation for the /// given value. /// /// Do not call this initializer directly. It is used by the compiler for /// each string interpolation segment when you use string interpolation. For /// example: /// /// let s = "\(5) x \(2) = \(5 * 2)" /// print(s) /// // Prints "5 x 2 = 10" /// /// This initializer is called five times when processing the string literal /// in the example above; once each for the following: the integer `5`, the /// string `" x "`, the integer `2`, the string `" = "`, and the result of /// the expression `5 * 2`. /// /// - Parameter expr: The expression to represent. init<T>(stringInterpolationSegment expr: T) } /// A type that can be initialized using a color literal (e.g. /// `#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)`). public protocol _ExpressibleByColorLiteral { /// Creates an instance initialized with the given properties of a color /// literal. /// /// Do not call this initializer directly. Instead, initialize a variable or /// constant using a color literal. init(colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float) } /// A type that can be initialized using an image literal (e.g. /// `#imageLiteral(resourceName: "hi.png")`). public protocol _ExpressibleByImageLiteral { /// Creates an instance initialized with the given resource name. /// /// Do not call this initializer directly. Instead, initialize a variable or /// constant using an image literal. init(imageLiteralResourceName path: String) } /// A type that can be initialized using a file reference literal (e.g. /// `#fileLiteral(resourceName: "resource.txt")`). public protocol _ExpressibleByFileReferenceLiteral { /// Creates an instance initialized with the given resource name. /// /// Do not call this initializer directly. Instead, initialize a variable or /// constant using a file reference literal. init(fileReferenceLiteralResourceName path: String) } /// A container is destructor safe if whether it may store to memory on /// destruction only depends on its type parameters destructors. /// For example, whether `Array<Element>` may store to memory on destruction /// depends only on `Element`. /// If `Element` is an `Int` we know the `Array<Int>` does not store to memory /// during destruction. If `Element` is an arbitrary class /// `Array<MemoryUnsafeDestructorClass>` then the compiler will deduce may /// store to memory on destruction because `MemoryUnsafeDestructorClass`'s /// destructor may store to memory on destruction. /// If in this example during `Array`'s destructor we would call a method on any /// type parameter - say `Element.extraCleanup()` - that could store to memory, /// then Array would no longer be a _DestructorSafeContainer. public protocol _DestructorSafeContainer { } @available(*, unavailable, renamed: "Bool") public typealias BooleanType = Bool // Deprecated by SE-0115. @available(*, deprecated, renamed: "ExpressibleByNilLiteral") public typealias NilLiteralConvertible = ExpressibleByNilLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinIntegerLiteral") public typealias _BuiltinIntegerLiteralConvertible = _ExpressibleByBuiltinIntegerLiteral @available(*, deprecated, renamed: "ExpressibleByIntegerLiteral") public typealias IntegerLiteralConvertible = ExpressibleByIntegerLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinFloatLiteral") public typealias _BuiltinFloatLiteralConvertible = _ExpressibleByBuiltinFloatLiteral @available(*, deprecated, renamed: "ExpressibleByFloatLiteral") public typealias FloatLiteralConvertible = ExpressibleByFloatLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinBooleanLiteral") public typealias _BuiltinBooleanLiteralConvertible = _ExpressibleByBuiltinBooleanLiteral @available(*, deprecated, renamed: "ExpressibleByBooleanLiteral") public typealias BooleanLiteralConvertible = ExpressibleByBooleanLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinUnicodeScalarLiteral") public typealias _BuiltinUnicodeScalarLiteralConvertible = _ExpressibleByBuiltinUnicodeScalarLiteral @available(*, deprecated, renamed: "ExpressibleByUnicodeScalarLiteral") public typealias UnicodeScalarLiteralConvertible = ExpressibleByUnicodeScalarLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinExtendedGraphemeClusterLiteral") public typealias _BuiltinExtendedGraphemeClusterLiteralConvertible = _ExpressibleByBuiltinExtendedGraphemeClusterLiteral @available(*, deprecated, renamed: "ExpressibleByExtendedGraphemeClusterLiteral") public typealias ExtendedGraphemeClusterLiteralConvertible = ExpressibleByExtendedGraphemeClusterLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinStringLiteral") public typealias _BuiltinStringLiteralConvertible = _ExpressibleByBuiltinStringLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinUTF16StringLiteral") public typealias _BuiltinUTF16StringLiteralConvertible = _ExpressibleByBuiltinUTF16StringLiteral @available(*, deprecated, renamed: "ExpressibleByStringLiteral") public typealias StringLiteralConvertible = ExpressibleByStringLiteral @available(*, deprecated, renamed: "ExpressibleByArrayLiteral") public typealias ArrayLiteralConvertible = ExpressibleByArrayLiteral @available(*, deprecated, renamed: "ExpressibleByDictionaryLiteral") public typealias DictionaryLiteralConvertible = ExpressibleByDictionaryLiteral @available(*, deprecated, message: "it will be replaced or redesigned in Swift 4.0. Instead of conforming to 'StringInterpolationConvertible', consider adding an 'init(_:String)'") public typealias StringInterpolationConvertible = ExpressibleByStringInterpolation @available(*, deprecated, renamed: "_ExpressibleByColorLiteral") public typealias _ColorLiteralConvertible = _ExpressibleByColorLiteral @available(*, deprecated, renamed: "_ExpressibleByImageLiteral") public typealias _ImageLiteralConvertible = _ExpressibleByImageLiteral @available(*, deprecated, renamed: "_ExpressibleByFileReferenceLiteral") public typealias _FileReferenceLiteralConvertible = _ExpressibleByFileReferenceLiteral
apache-2.0
44373a3c1b887e8e9eb7d44d1100279b
40.177305
183
0.696722
4.813597
false
false
false
false
naoyashiga/LegendTV
LegendTV/SettingCollectionViewController.swift
1
4833
// // SettingCollectionViewController.swift // LegendTV // // Created by naoyashiga on 2015/08/24. // Copyright (c) 2015年 naoyashiga. All rights reserved. // import UIKit struct settingReuseId { static let cell = "SettingCollectionViewCell" static let headerView = "SettingHeaderView" } class SettingCollectionViewController: BaseCollectionViewController { var reviewMenu = [ "レビューを書いて応援する", "他のアプリを見る" ] var snsMenu = [ "Twitterでつぶやく", "LINEに送る" ] var shareText = "" override func viewDidLoad() { super.viewDidLoad() cellSize.width = view.bounds.width cellSize.height = 80 if let collectionView = collectionView { collectionView.contentInset = UIEdgeInsetsMake(10, cellMargin.horizontal / 2, 0, cellMargin.horizontal / 2) collectionView.applyHeaderNib(headerNibName: settingReuseId.headerView) collectionView.applyCellNib(cellNibName: settingReuseId.cell) } let localizedshareText = "お笑い動画アプリ " shareText = localizedshareText + AppConstraints.appStoreURLString } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 2 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { return reviewMenu.count } else { return snsMenu.count } } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { switch kind { case UICollectionElementKindSectionHeader: let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: settingReuseId.headerView, forIndexPath: indexPath) as! SettingHeaderView switch indexPath.section { case 0: headerView.titleLabel.text = "応援" case 1: headerView.titleLabel.text = "シェア" default: break } return setCornerRadius(headerView: headerView) default: assert(false, "error") return UICollectionReusableView() } } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(settingReuseId.cell, forIndexPath: indexPath) as! SettingCollectionViewCell switch indexPath.section { case 0: cell.titleLabel.text = reviewMenu[indexPath.row] case 1: cell.titleLabel.text = snsMenu[indexPath.row] default: break; } return getSelectedBackgroundViewCell(cell: cell) } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { switch indexPath.section { case 0: if indexPath.row == 0 { transitionToReviewPage() } else { transitionToOtherAppPage() } case 1: switch indexPath.row { case 0: postToTwitter() case 1: postToLINE() default: break } break default: break } } private func getSelectedBackgroundViewCell(cell cell: SettingCollectionViewCell) -> SettingCollectionViewCell { //通常の背景 let backgroundView = UIView() backgroundView.bounds = cell.bounds backgroundView.backgroundColor = UIColor.cellLightBackgroundColor() cell.backgroundView = backgroundView //選択時の背景 let selectedBackgroundView = UIView() selectedBackgroundView.bounds = cell.bounds selectedBackgroundView.backgroundColor = UIColor.cellSelectedBackgroundColor() cell.selectedBackgroundView = selectedBackgroundView return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: cellSize.width, height: 50) } }
mit
d1fbfd6ac14a509670b03c4350cb056d
31.163265
183
0.624709
5.960908
false
false
false
false
RoRoche/iOSSwiftStarter
iOSSwiftStarter/iOSSwiftStarter/Classes/Common/Store/API/ApiService.swift
1
1749
// // ApiService.swift // iOSSwiftStarter // // Created by Romain Rochegude on 11/12/2015. // Copyright © 2015 Romain Rochegude. All rights reserved. // import Alamofire enum ApiService: URLRequestConvertible { static let baseURLString: String = "https://api.github.com"; // MARK: API methods definitions case ListRepos(user: String, sort: ListReposSort?); // MARK: Parameters values for API methods enum ListReposSort { case DESC; case ASC; var value: String { switch self { case .ASC: return "asc"; case .DESC: return "desc"; } } } // MARK: Verb definition according to API method var method: Alamofire.Method { switch self { case .ListRepos: return .GET; } } // MARK: Path definition according to API method var path: (lastSegmentPath: String, parameters: [String: AnyObject]?) { switch self { case .ListRepos(let user, let sort) where sort != nil: return ("/users/\(user)/repos", ["sort": sort!.value]); case .ListRepos(let user, _): return ("/users/\(user)/repos", nil); } } // MARK: URLRequestConvertible var URLRequest: NSMutableURLRequest { let URL = NSURL(string: ApiService.baseURLString)!; let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path.lastSegmentPath)); mutableURLRequest.HTTPMethod = method.rawValue; let encoding = Alamofire.ParameterEncoding.URL; return encoding.encode(mutableURLRequest, parameters: path.parameters).0; } }
apache-2.0
1bb4f140f741d7e1debcdd579e69402e
26.761905
112
0.590961
4.828729
false
false
false
false
RevenueCat/purchases-ios
Tests/UnitTests/Mocks/MockPurchases.swift
1
11913
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // MockPurchases.swift // // Created by Nacho Soto on 10/10/22. @testable import RevenueCat final class MockPurchases { @_disfavoredOverload fileprivate func unimplemented() { let _: Void = self.unimplemented() } fileprivate func unimplemented<T>() -> T { fatalError("Mocked method not implemented") } // MARK: - var invokedGetCustomerInfo = false var mockedCustomerInfoResponse: Result<CustomerInfo, PublicError> = .failure( ErrorUtils.unknownError().asPublicError ) var invokedGetOfferings = false var invokedGetOfferingsParameters: OfferingsManager.FetchPolicy? var mockedOfferingsResponse: Result<Offerings, PublicError> = .failure( ErrorUtils.unknownError().asPublicError ) var invokedHealthRequest = false var mockedHealthRequestResponse: Result<Void, PublicError> = .success(()) } extension MockPurchases: InternalPurchasesType { @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func healthRequest() async throws { return try self.mockedHealthRequestResponse.get() } } extension MockPurchases: PurchasesType { func getCustomerInfo(completion: @escaping ((CustomerInfo?, PublicError?) -> Void)) { self.invokedGetCustomerInfo = true completion(self.mockedCustomerInfoResponse.value, self.mockedCustomerInfoResponse.error) } func getCustomerInfo( fetchPolicy: CacheFetchPolicy, completion: @escaping (CustomerInfo?, PublicError?) -> Void ) { self.getCustomerInfo(completion: completion) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func customerInfo() async throws -> CustomerInfo { self.invokedGetCustomerInfo = true return try self.mockedCustomerInfoResponse.get() } func getOfferings(completion: @escaping ((Offerings?, PublicError?) -> Void)) { self.invokedGetOfferings = true completion(self.mockedOfferingsResponse.value, self.mockedOfferingsResponse.error) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func offerings() async throws -> Offerings { return try await self.offerings(fetchPolicy: .default) } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func offerings(fetchPolicy: OfferingsManager.FetchPolicy) async throws -> Offerings { self.invokedGetOfferings = true self.invokedGetOfferingsParameters = fetchPolicy return try self.mockedOfferingsResponse.get() } // MARK: - Unimplemented var appUserID: String { self.unimplemented() } var isAnonymous: Bool { self.unimplemented() } var finishTransactions: Bool { get { self.unimplemented() } // swiftlint:disable:next unused_setter_value set { self.unimplemented() } } var delegate: PurchasesDelegate? { get { self.unimplemented() } // swiftlint:disable:next unused_setter_value set { self.unimplemented() } } func logIn( _ appUserID: String, completion: @escaping (CustomerInfo?, Bool, PublicError? ) -> Void) { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func logIn( _ appUserID: String ) async throws -> (customerInfo: CustomerInfo, created: Bool) { self.unimplemented() } func logOut(completion: ((CustomerInfo?, PublicError?) -> Void)?) { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func logOut() async throws -> CustomerInfo { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func customerInfo(fetchPolicy: CacheFetchPolicy) async throws -> CustomerInfo { self.unimplemented() } func getProducts(_ productIdentifiers: [String], completion: @escaping ([StoreProduct]) -> Void) { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func products(_ productIdentifiers: [String]) async -> [StoreProduct] { self.unimplemented() } func purchase(product: StoreProduct, completion: @escaping PurchaseCompletedBlock) { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func purchase(product: StoreProduct) async throws -> PurchaseResultData { self.unimplemented() } func purchase(package: Package, completion: @escaping PurchaseCompletedBlock) { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func purchase(package: Package) async throws -> PurchaseResultData { self.unimplemented() } func purchase( product: StoreProduct, promotionalOffer: PromotionalOffer, completion: @escaping PurchaseCompletedBlock ) { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func purchase( product: StoreProduct, promotionalOffer: PromotionalOffer ) async throws -> PurchaseResultData { self.unimplemented() } func purchase( package: Package, promotionalOffer: PromotionalOffer, completion: @escaping PurchaseCompletedBlock ) { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func purchase( package: Package, promotionalOffer: PromotionalOffer ) async throws -> PurchaseResultData { self.unimplemented() } func restorePurchases(completion: ((CustomerInfo?, PublicError?) -> Void)?) { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func restorePurchases() async throws -> CustomerInfo { self.unimplemented() } func syncPurchases(completion: ((CustomerInfo?, PublicError?) -> Void)?) { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func syncPurchases() async throws -> CustomerInfo { self.unimplemented() } func checkTrialOrIntroDiscountEligibility( productIdentifiers: [String], completion receiveEligibility: @escaping ([String: IntroEligibility]) -> Void ) { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func checkTrialOrIntroDiscountEligibility( productIdentifiers: [String] ) async -> [String: IntroEligibility] { self.unimplemented() } func checkTrialOrIntroDiscountEligibility( product: StoreProduct, completion: @escaping (IntroEligibilityStatus) -> Void ) { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func checkTrialOrIntroDiscountEligibility( product: StoreProduct ) async -> IntroEligibilityStatus { self.unimplemented() } func getPromotionalOffer( forProductDiscount discount: StoreProductDiscount, product: StoreProduct, completion: @escaping ((PromotionalOffer?, PublicError?) -> Void) ) { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func promotionalOffer( forProductDiscount discount: StoreProductDiscount, product: StoreProduct ) async throws -> PromotionalOffer { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func eligiblePromotionalOffers(forProduct product: StoreProduct) async -> [PromotionalOffer] { self.unimplemented() } func invalidateCustomerInfoCache() { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func beginRefundRequest(forProduct productID: String) async throws -> RefundRequestStatus { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func beginRefundRequest(forEntitlement entitlementID: String) async throws -> RefundRequestStatus { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func beginRefundRequestForActiveEntitlement() async throws -> RefundRequestStatus { self.unimplemented() } #if os(iOS) func presentCodeRedemptionSheet() { self.unimplemented() } #endif func showPriceConsentIfNeeded() { self.unimplemented() } func showManageSubscriptions(completion: @escaping (PublicError?) -> Void) { self.unimplemented() } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func showManageSubscriptions() async throws { self.unimplemented() } var attribution: Attribution { self.unimplemented() } func setAttributes(_ attributes: [String: String]) { self.unimplemented() } var allowSharingAppStoreAccount: Bool { get { self.unimplemented() } // swiftlint:disable:next unused_setter_value set { self.unimplemented() } } func setEmail(_ email: String?) { self.unimplemented() } func setPhoneNumber(_ phoneNumber: String?) { self.unimplemented() } func setDisplayName(_ displayName: String?) { self.unimplemented() } func setPushToken(_ pushToken: Data?) { self.unimplemented() } func setPushTokenString(_ pushToken: String?) { self.unimplemented() } func setAdjustID(_ adjustID: String?) { self.unimplemented() } func setAppsflyerID(_ appsflyerID: String?) { self.unimplemented() } func setFBAnonymousID(_ fbAnonymousID: String?) { self.unimplemented() } func setMparticleID(_ mparticleID: String?) { self.unimplemented() } func setOnesignalID(_ onesignalID: String?) { self.unimplemented() } func setMediaSource(_ mediaSource: String?) { self.unimplemented() } func setCampaign(_ campaign: String?) { self.unimplemented() } func setAdGroup(_ adGroup: String?) { self.unimplemented() } func setAd(_ value: String?) { self.unimplemented() } func setKeyword(_ keyword: String?) { self.unimplemented() } func setCreative(_ creative: String?) { self.unimplemented() } func setCleverTapID(_ cleverTapID: String?) { self.unimplemented() } func setMixpanelDistinctID(_ mixpanelDistinctID: String?) { self.unimplemented() } func setFirebaseAppInstanceID(_ firebaseAppInstanceID: String?) { self.unimplemented() } func collectDeviceIdentifiers() { self.unimplemented() } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) extension MockPurchases: PurchasesSwiftType { var customerInfoStream: AsyncStream<CustomerInfo> { self.unimplemented() } func beginRefundRequest( forProduct productID: String, completion: @escaping (Result<RefundRequestStatus, PublicError>) -> Void ) { self.unimplemented() } func beginRefundRequest( forEntitlement entitlementID: String, completion: @escaping (Result<RefundRequestStatus, PublicError>) -> Void ) { self.unimplemented() } func beginRefundRequestForActiveEntitlement( completion: @escaping (Result<RefundRequestStatus, PublicError>) -> Void ) { self.unimplemented() } }
mit
944ebb1264076f7f01159954aa7442ee
26.576389
103
0.644758
4.492081
false
false
false
false
jeancarlosaps/swift
Swift em 4 Semanas/Playgrounds/Semana 1/1-Conheça o Playground.playground/Contents.swift
2
658
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // Exemplo #01 var linguagem = "Obj-C" linguagem = "Swift" // Exemplo #02 var idade = 18 var novaIdade = idade + 2 // Exemplo #03: for 10 times. 100 times. for i in 0..<50 { i*i } // Exemplo #04 var preço = 3.46 var avaliação: String switch preço { case 0...10: avaliação = "Aproveita! o preço está bom!" case 11...50: avaliação = "Caro, não?" default: avaliação = "Espera por uma melhor oportunidade de compra." } // Exemplo Extra: let color = UIColor.greenColor()
mit
556d566fe6758c2b26815ef786837236
10.12069
63
0.59845
2.816594
false
false
false
false
clonezer/FreeForm
FreeForm/Classes/FreeFormSwitchCell.swift
1
1274
// // FreeFormSwitchCell.swift // Pods // // Created by Peerasak Unsakon on 1/4/17. // // import UIKit public class FreeFormSwitchRow: FreeFormRow { override public init(tag: String, title: String, value: AnyObject?) { super.init(tag: tag, title: title, value: value) self.cellType = String(describing: FreeFormSwitchCell.self) } public func isOn() -> Bool { guard let value = self.value as? Bool else { return false } return value } } public class FreeFormSwitchCell: FreeFormCell { @IBOutlet public weak var titleLabel: UILabel! @IBOutlet public weak var cellSwitch: UISwitch! override public func update() { super.update() guard let row = self.row as? FreeFormSwitchRow else { return } self.titleLabel.text = row.title guard let value = row.value as? Bool else { return } self.cellSwitch.setOn(value, animated: true) } @IBAction func cellSwitchValueChanged(_ sender: Any) { guard let row = self.row as? FreeFormSwitchRow else { return } row.value = self.cellSwitch.isOn as AnyObject? guard let block = row.didChanged else { return } block(row.value as AnyObject, row) } }
mit
0091a925f2f3c957487b4c357ee279db
26.106383
73
0.631868
4.177049
false
false
false
false
sschiau/swift
benchmark/single-source/ReduceInto.swift
6
3245
//===--- ReduceInto.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils public let ReduceInto = [ BenchmarkInfo(name: "FilterEvenUsingReduce", runFunction: run_FilterEvenUsingReduce, tags: [.validation, .api], legacyFactor: 10), BenchmarkInfo(name: "FilterEvenUsingReduceInto", runFunction: run_FilterEvenUsingReduceInto, tags: [.validation, .api]), BenchmarkInfo(name: "FrequenciesUsingReduce", runFunction: run_FrequenciesUsingReduce, tags: [.validation, .api]), BenchmarkInfo(name: "FrequenciesUsingReduceInto", runFunction: run_FrequenciesUsingReduceInto, tags: [.validation, .api]), BenchmarkInfo(name: "SumUsingReduce", runFunction: run_SumUsingReduce, tags: [.validation, .api]), BenchmarkInfo(name: "SumUsingReduceInto", runFunction: run_SumUsingReduceInto, tags: [.validation, .api]), ] // Sum @inline(never) public func run_SumUsingReduce(_ N: Int) { let numbers = [Int](0..<1000) var c = 0 for _ in 1...N*1000 { c = c &+ numbers.reduce(0) { (acc: Int, num: Int) -> Int in acc &+ num } } CheckResults(c != 0) } @inline(never) public func run_SumUsingReduceInto(_ N: Int) { let numbers = [Int](0..<1000) var c = 0 for _ in 1...N*1000 { c = c &+ numbers.reduce(into: 0) { (acc: inout Int, num: Int) in acc = acc &+ num } } CheckResults(c != 0) } // Filter @inline(never) public func run_FilterEvenUsingReduce(_ N: Int) { let numbers = [Int](0..<100) var c = 0 for _ in 1...N*10 { let a = numbers.reduce([]) { (acc: [Int], num: Int) -> [Int] in var a = acc if num % 2 == 0 { a.append(num) } return a } c = c &+ a.count } CheckResults(c != 0) } @inline(never) public func run_FilterEvenUsingReduceInto(_ N: Int) { let numbers = [Int](0..<100) var c = 0 for _ in 1...N*100 { let a = numbers.reduce(into: []) { (acc: inout [Int], num: Int) in if num % 2 == 0 { acc.append(num) } } c = c &+ a.count } CheckResults(c != 0) } // Frequencies @inline(never) public func run_FrequenciesUsingReduce(_ N: Int) { let s = "thequickbrownfoxjumpsoverthelazydogusingasmanycharacteraspossible123456789" var c = 0 for _ in 1...N*100 { let a = s.reduce([:]) { (acc: [Character: Int], c: Character) -> [Character: Int] in var d = acc d[c, default: 0] += 1 return d } c = c &+ a.count } CheckResults(c != 0) } @inline(never) public func run_FrequenciesUsingReduceInto(_ N: Int) { let s = "thequickbrownfoxjumpsoverthelazydogusingasmanycharacteraspossible123456789" var c = 0 for _ in 1...N*100 { let a = s.reduce(into: [:]) { (acc: inout [Character: Int], c: Character) in acc[c, default: 0] += 1 } c = c &+ a.count } CheckResults(c != 0) }
apache-2.0
3e6cb6965759ab4ba17cc2f004f290e1
26.041667
132
0.604931
3.546448
false
false
false
false
yariksmirnov/Forms
Sources/FormValidator.swift
1
3509
// // FormValidator.swift // Forms // // Created by Yaroslav Smirnov on 16/06/2017. // Copyright © 2017 Yaroslav Smirnov. All rights reserved. // import Foundation import CoreTelephony public enum ValidationResult { case valid case invalid(message: String) public var isValid: Bool { switch self { case .valid: return true default: return false } } } public protocol FieldValidator { typealias ValidatorCompletion = (ValidationResult) -> Void func validate(_ input: String, mode: ValidationMode, completion: @escaping ValidatorCompletion) func offlineValidation(_ input: String) -> ValidationResult func onlineValidation(_ input: String, completion: @escaping ValidatorCompletion) } public extension FieldValidator { func validate(_ input: String, mode: ValidationMode, completion: @escaping ValidatorCompletion) { let result = offlineValidation(input) var isOnSlowNetwork = false if let radio = CTTelephonyNetworkInfo().currentRadioAccessTechnology { isOnSlowNetwork = radio == CTRadioAccessTechnologyEdge || radio == CTRadioAccessTechnologyGPRS } if mode == .online && result.isValid && !isOnSlowNetwork { onlineValidation(input, completion: completion) } else { completion(result) } } } public final class EmailValidator: FieldValidator { public class func regularExpression() -> String { return "(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}" + "~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" + "x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-" + "z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5" + "]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" + "9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" + "-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])" } private let regex: NSPredicate public init() { let exp = type(of: self).regularExpression() regex = NSPredicate(format: "SELF MATCHES %@", exp) } public func onlineValidation(_ input: String, completion: @escaping (ValidationResult) -> Void) { completion(.valid) } public func offlineValidation(_ input: String) -> ValidationResult { if regex.evaluate(with: input) { return .valid } return .invalid(message: Parameters.invalidEmailMessage) } } public final class PasswordValidator: FieldValidator { public class func regularExpression() -> String { return "^.{6,}$" } private let regexp: NSPredicate public init() { let exp = type(of: self).regularExpression() regexp = NSPredicate(format: "SELF MATCHES %@", exp) } public func onlineValidation(_ input: String, completion: @escaping (ValidationResult) -> Void) { completion(.valid) } public func offlineValidation(_ input: String) -> ValidationResult { if regexp.evaluate(with: input) { return .valid } else { return .invalid(message: Parameters.invalidPasswordMessage) } } }
mit
b7f240b51958bad09b1240c9a07101a6
30.044248
106
0.558723
4.036824
false
false
false
false
PJayRushton/stats
Stats/GamesHeaderCell.swift
1
865
// // GamesHeaderCell.swift // Stats // // Created by Parker Rushton on 6/10/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import UIKit struct TeamRecord { var gamesWon: Int var gamesLost: Int } class GamesHeaderCell: UITableViewCell, AutoReuseIdentifiable { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var gamesWonLabel: UILabel! @IBOutlet weak var gamesLostLabel: UILabel! @IBOutlet weak var recordStack: UIStackView! func update(withTitle title: String, record: TeamRecord?) { backgroundColor = .secondaryAppColor titleLabel.text = title if let record = record { gamesWonLabel.text = String(record.gamesWon) gamesLostLabel.text = String(record.gamesLost) } else { recordStack.isHidden = true } } }
mit
e9cd6e47957500a4174cf810cdaae807
23
63
0.649306
4.32
false
false
false
false
alloyapple/GooseGtk
Sources/Example1/ExampleViewController.swift
1
2002
// // Created by color on 12/8/17. // import Foundation import GooseGtk class ExampleViewController: GTKViewController { public func viewDidLoad() { // let box = GTKBox(orientation: .VERTICAL, spacing: 5) // // let stack = GTKStack() // // let scrolled = GtkScrolledWindow() // scrolled.hexpand = true // scrolled.vexpand = true // // let textView = GTKTextView() // textView.editable = false // textView.cursorVisible = false // scrolled.add(textView) // stack.addTitled(subView: scrolled, name: "Test", title: "Text") // // let label = GTKLabel("eeeee") //// stack.addTitled(subView: label, name: "test1", title: "test2") // let entry = GTKEntry() // entry.setIconFromIconName(iconPos: .ENTRY_ICON_SECONDARY, iconName: "edit-clear") // entry.text = "Hello World" // stack.addTitled(subView: entry, name: "test1", title: "test2") // // textView.text = """ // which clang // /home/color/Application/swift-4.0/usr/bin/swiftc --driver-mode=swift -L /home/color/Application/swift-4.0/usr/lib/swift/pm/4 -lPackageDescription -swift-version 4 -I /home/color/Application/swift-4.0/usr/lib/swift/pm/4 -sdk / /home/color/Dev/GooseGtk/Package.swift -fileno 6 // /home/c // """ // // let stackSwitcher = GTKStackSwitcher() // stackSwitcher.stack = stack // // let hbox = GTKBox(orientation: .HORIZONTAL, spacing: 0) // hbox.packStart(subView: GTKLabel(""), expand: true, fill: true, padding: 1) // hbox.packStart(subView: stackSwitcher, expand: false, fill: false, padding: 1) // hbox.packStart(subView: GTKLabel(""), expand: true, fill: true, padding: 1) // //hbox.setHomogeneous(true) // // // box.packStart(subView: hbox, expand: false, fill: false, padding: 1) // box.packStart(subView: stack, expand: true, fill: true, padding: 1) // // self.view.addSubView(box) } }
apache-2.0
98ce65421ddfcc436fcfdcc039fe089f
36.792453
288
0.614885
3.376054
false
true
false
false
yanif/circator
MetabolicCompass/AddEventMenu/PathMenuItem.swift
1
4037
// // PathMenuItem.swift // PathMenu // // Created by pixyzehn on 12/27/14. // Copyright (c) 2014 pixyzehn. All rights reserved. // import Foundation import UIKit public protocol PathMenuItemDelegate: class { func pathMenuItemTouchesBegin(item: PathMenuItem) func pathMenuItemTouchesEnd(item: PathMenuItem) } public class PathMenuItem: UIImageView { public var contentImageView: UIImageView? public var contentLabel: UILabel! public var startPoint: CGPoint? public var endPoint: CGPoint? public var nearPoint: CGPoint? public var farPoint: CGPoint? public weak var delegate: PathMenuItemDelegate? override public var highlighted: Bool { didSet { contentImageView?.highlighted = highlighted } } override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } convenience public init(image: UIImage, highlightedImage himg: UIImage? = nil, contentImage cimg: UIImage? = nil, highlightedContentImage hcimg: UIImage? = nil, contentText text: String? = nil) { self.init(frame: CGRectZero) self.image = image self.highlightedImage = himg self.contentImageView = UIImageView(image: cimg) self.contentImageView?.highlightedImage = hcimg self.contentLabel = UILabel(frame: CGRect.zero) self.contentLabel.text = text self.contentLabel.font = UIFont(name: "GothamBook", size: 14.0) self.contentLabel.textColor = .lightGrayColor() self.userInteractionEnabled = true self.addSubview(contentImageView!) self.contentLabel.translatesAutoresizingMaskIntoConstraints = false self.addSubview(contentLabel) let constraints: [NSLayoutConstraint] = [ contentLabel.topAnchor.constraintEqualToAnchor(bottomAnchor, constant: 10.0), //contentLabel.heightAnchor.constraintEqualToConstant(25.0), contentLabel.leadingAnchor.constraintEqualToAnchor(leadingAnchor), contentLabel.trailingAnchor.constraintEqualToAnchor(trailingAnchor) ] self.addConstraints(constraints) } private func ScaleRect(rect: CGRect, n: CGFloat) -> CGRect { let width = rect.size.width let height = rect.size.height return CGRectMake((width - width * n)/2, (height - height * n)/2, width * n, height * n) } //MARK: UIView's methods override public func layoutSubviews() { super.layoutSubviews() if let image = image { bounds = CGRectMake(0, 0, image.size.width, image.size.height) } if let imageView = contentImageView, let width = imageView.image?.size.width, let height = imageView.image?.size.height { imageView.frame = CGRectMake(bounds.size.width/2 - width/2, bounds.size.height/2 - height/2, width, height) } } public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { highlighted = true delegate?.pathMenuItemTouchesBegin(self) } public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if let location = touches.first?.locationInView(self) { if !CGRectContainsPoint(ScaleRect(bounds, n: 2.0), location) { highlighted = false } } } public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { highlighted = false if let location = touches.first?.locationInView(self) { if CGRectContainsPoint(ScaleRect(bounds, n: 2.0), location) { delegate?.pathMenuItemTouchesEnd(self) } } } public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { highlighted = false } }
apache-2.0
9510fd3cb3c769d737f7f2bf66ec8202
31.556452
119
0.642556
4.869723
false
false
false
false
Madimo/LifeTime-Swift
LifeTime/BirthdayPickerView.swift
1
2858
// // BirthdayPickerView.swift // LifeTime // // Created by Madimo on 14-6-11. // Copyright (c) 2014年 Madimo. All rights reserved. // import UIKit protocol BirthdayPickerViewDelegate { func finishPick(date: NSDate) } class BirthdayPickerView: NSObject { var delegate: BirthdayPickerViewDelegate? let _window: UIWindow! let _datePicker: UIDatePicker! let _toolbar: UIToolbar! init(height: CGFloat) { super.init() self._window = UIWindow() self._datePicker = UIDatePicker() self._toolbar = UIToolbar() self._window.frame = UIScreen.mainScreen().bounds var frame = UIScreen.mainScreen().bounds frame.size.height = height frame.origin.y = CGRectGetHeight(self._window.frame) self._toolbar.frame = frame frame.origin = CGPointMake(0, 0) self._datePicker.frame = frame self._datePicker.datePickerMode = .Date self._datePicker.date = NSDate() self._datePicker.calendar = NSCalendar.currentCalendar() self._datePicker.timeZone = NSTimeZone.localTimeZone() self._datePicker.minimumDate = NSDate(timeIntervalSinceNow: -3600 * 24 * 365 * 100) self._datePicker.maximumDate = NSDate() self._toolbar.addSubview(self._datePicker) self._window.addSubview(self._toolbar) let recognizer = UITapGestureRecognizer(target: self, action: Selector("handleTapGesture:")) self._window.addGestureRecognizer(recognizer) } func show() { if !self._window.hidden { return } self._window.makeKeyAndVisible() UIView.animateWithDuration(0.2, animations: { self._window.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5) var frame = self._toolbar.frame frame.origin.y = self._window.bounds.height - CGRectGetHeight(frame) self._toolbar.frame = frame }, completion: nil) } func hide() { if self._window.hidden { return } UIView.animateWithDuration(0.2, animations: { self._window.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0) var frame = self._toolbar.frame frame.origin.y = CGRectGetHeight(self._window.frame) self._toolbar.frame = frame }, completion: { (finished: Bool) in self._window.hidden = true }) self.delegate?.finishPick(self._datePicker.date) } func handleTapGesture(sender: UITapGestureRecognizer) { self.hide() } }
gpl-3.0
c6cfe52b8e205cb533f03d1998ab786c
28.142857
100
0.568277
4.8
false
false
false
false
vector-im/riot-ios
Riot/Modules/KeyVerification/Common/Verify/Scanning/KeyVerificationVerifyByScanningViewController.swift
1
13448
// File created from ScreenTemplate // $ createScreen.sh Verify KeyVerificationVerifyByScanning /* Copyright 2020 New Vector Ltd 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 UIKit final class KeyVerificationVerifyByScanningViewController: UIViewController { // MARK: - Constants // MARK: - Properties // MARK: Outlets @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet private weak var closeButton: UIButton! @IBOutlet private weak var titleView: UIView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var informationLabel: UILabel! @IBOutlet private weak var codeImageView: UIImageView! @IBOutlet private weak var scanCodeButton: UIButton! @IBOutlet private weak var cannotScanButton: UIButton! @IBOutlet private weak var qrCodeContainerView: UIView! @IBOutlet private weak var scanButtonContainerView: UIView! // MARK: Private private var viewModel: KeyVerificationVerifyByScanningViewModelType! private var theme: Theme! private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! private var cameraAccessAlertPresenter: CameraAccessAlertPresenter! private var cameraAccessManager: CameraAccessManager! private weak var qrCodeReaderViewController: QRCodeReaderViewController? private var alertPresentingViewController: UIViewController { return self.qrCodeReaderViewController ?? self } // MARK: - Setup class func instantiate(with viewModel: KeyVerificationVerifyByScanningViewModelType) -> KeyVerificationVerifyByScanningViewController { let viewController = StoryboardScene.KeyVerificationVerifyByScanningViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupViews() self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.cameraAccessAlertPresenter = CameraAccessAlertPresenter() self.cameraAccessManager = CameraAccessManager() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .loadData) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Hide back button self.navigationItem.setHidesBackButton(true, animated: animated) } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.titleLabel.textColor = theme.textPrimaryColor self.informationLabel.textColor = theme.textPrimaryColor if let themableCloseButton = self.closeButton as? Themable { themableCloseButton.update(theme: theme) } theme.applyStyle(onButton: self.scanCodeButton) theme.applyStyle(onButton: self.cannotScanButton) } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in self?.cancelButtonAction() } self.titleView.isHidden = self.navigationController != nil self.navigationItem.rightBarButtonItem = cancelBarButtonItem self.title = VectorL10n.keyVerificationVerifyQrCodeTitle self.titleLabel.text = VectorL10n.keyVerificationVerifyQrCodeTitle self.informationLabel.text = VectorL10n.keyVerificationVerifyQrCodeInformation self.scanCodeButton.setTitle(VectorL10n.keyVerificationVerifyQrCodeScanCodeAction, for: .normal) self.cannotScanButton.setTitle(VectorL10n.keyVerificationVerifyQrCodeCannotScanAction, for: .normal) } private func render(viewState: KeyVerificationVerifyByScanningViewState) { switch viewState { case .loading: self.renderLoading() case .loaded(viewData: let viewData): self.renderLoaded(viewData: viewData) case .error(let error): self.render(error: error) case .scannedCodeValidated(let isValid): self.renderScannedCode(valid: isValid) case .cancelled(let reason): self.renderCancelled(reason: reason) case .cancelledByMe(let reason): self.renderCancelledByMe(reason: reason) } } private func renderLoading() { self.activityPresenter.presentActivityIndicator(on: self.view, animated: true) } private func renderLoaded(viewData: KeyVerificationVerifyByScanningViewData) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) let hideQRCodeImage: Bool if let qrCodePayloadData = viewData.qrCodeData { hideQRCodeImage = false self.codeImageView.image = self.qrCodeImage(from: qrCodePayloadData) } else { hideQRCodeImage = true } self.title = viewData.verificationKind.verificationTitle self.titleLabel.text = viewData.verificationKind.verificationTitle self.qrCodeContainerView.isHidden = hideQRCodeImage self.scanButtonContainerView.isHidden = !viewData.showScanAction if viewData.qrCodeData == nil && viewData.showScanAction == false { // Update the copy if QR code scanning is not possible at all self.informationLabel.text = VectorL10n.keyVerificationVerifyQrCodeEmojiInformation self.cannotScanButton.setTitle(VectorL10n.keyVerificationVerifyQrCodeStartEmojiAction, for: .normal) } else { let informationText: String switch viewData.verificationKind { case .user: informationText = VectorL10n.keyVerificationVerifyQrCodeInformation default: informationText = VectorL10n.keyVerificationVerifyQrCodeInformationOtherDevice } self.informationLabel.text = informationText } } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil) } private func qrCodeImage(from data: Data) -> UIImage? { let codeGenerator = QRCodeGenerator() return codeGenerator.generateCode(from: data, with: self.codeImageView.frame.size) } private func presentQRCodeReader(animated: Bool) { let qrCodeViewController = QRCodeReaderViewController.instantiate() qrCodeViewController.delegate = self self.present(qrCodeViewController, animated: animated, completion: nil) self.qrCodeReaderViewController = qrCodeViewController } private func renderScannedCode(valid: Bool) { if valid { self.stopQRCodeScanningIfPresented() self.presentCodeValidated(animated: true) { self.dismissQRCodeScanningIfPresented(animated: true, completion: { self.viewModel.process(viewAction: .acknowledgeMyUserScannedOtherCode) }) } } } private func renderCancelled(reason: MXTransactionCancelCode) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.stopQRCodeScanningIfPresented() self.errorPresenter.presentError(from: self.alertPresentingViewController, title: "", message: VectorL10n.deviceVerificationCancelled, animated: true) { self.dismissQRCodeScanningIfPresented(animated: false) self.viewModel.process(viewAction: .cancel) } } private func renderCancelledByMe(reason: MXTransactionCancelCode) { if reason.value != MXTransactionCancelCode.user().value { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: alertPresentingViewController, title: "", message: VectorL10n.deviceVerificationCancelledByMe(reason.humanReadable), animated: true) { self.dismissQRCodeScanningIfPresented(animated: false) self.viewModel.process(viewAction: .cancel) } } else { self.activityPresenter.removeCurrentActivityIndicator(animated: true) } } private func presentCodeValidated(animated: Bool, completion: @escaping (() -> Void)) { let alert = UIAlertController(title: VectorL10n.keyVerificationVerifyQrCodeScanOtherCodeSuccessTitle, message: VectorL10n.keyVerificationVerifyQrCodeScanOtherCodeSuccessMessage, preferredStyle: .alert) let okAction = UIAlertAction(title: Bundle.mxk_localizedString(forKey: "ok"), style: .default, handler: { _ in completion() }) alert.addAction(okAction) if let qrCodeReaderViewController = self.qrCodeReaderViewController { qrCodeReaderViewController.present(alert, animated: animated, completion: nil) } } private func checkCameraAccessAndPresentQRCodeReader(animated: Bool) { guard self.cameraAccessManager.isCameraAvailable else { self.cameraAccessAlertPresenter.presentCameraUnavailableAlert(from: self, animated: animated) return } self.cameraAccessManager.askAndRequestCameraAccessIfNeeded { (granted) in if granted { self.presentQRCodeReader(animated: animated) } else { self.cameraAccessAlertPresenter.presentPermissionDeniedAlert(from: self, animated: animated) } } } private func stopQRCodeScanningIfPresented() { guard let qrCodeReaderViewController = self.qrCodeReaderViewController else { return } qrCodeReaderViewController.view.isUserInteractionEnabled = false qrCodeReaderViewController.stopScanning() } private func dismissQRCodeScanningIfPresented(animated: Bool, completion: (() -> Void)? = nil) { guard self.qrCodeReaderViewController?.presentingViewController != nil else { return } self.dismiss(animated: animated, completion: completion) } // MARK: - Actions @IBAction private func scanButtonAction(_ sender: Any) { self.checkCameraAccessAndPresentQRCodeReader(animated: true) } @IBAction private func cannotScanAction(_ sender: Any) { self.viewModel.process(viewAction: .cannotScan) } @IBAction private func closeButtonAction(_ sender: Any) { self.viewModel.process(viewAction: .cancel) } private func cancelButtonAction() { self.viewModel.process(viewAction: .cancel) } } // MARK: - KeyVerificationVerifyByScanningViewModelViewDelegate extension KeyVerificationVerifyByScanningViewController: KeyVerificationVerifyByScanningViewModelViewDelegate { func keyVerificationVerifyByScanningViewModel(_ viewModel: KeyVerificationVerifyByScanningViewModelType, didUpdateViewState viewSate: KeyVerificationVerifyByScanningViewState) { self.render(viewState: viewSate) } } // MARK: - QRCodeReaderViewControllerDelegate extension KeyVerificationVerifyByScanningViewController: QRCodeReaderViewControllerDelegate { func qrCodeReaderViewController(_ viewController: QRCodeReaderViewController, didFound payloadData: Data) { self.viewModel.process(viewAction: .scannedCode(payloadData: payloadData)) } func qrCodeReaderViewControllerDidCancel(_ viewController: QRCodeReaderViewController) { self.dismissQRCodeScanningIfPresented(animated: true) } }
apache-2.0
0f5a2161757b95e10e7eb60d49f00d38
38.321637
185
0.69133
6.049483
false
false
false
false
cfilipov/MuscleBook
MuscleBook/SplitSwipeView.swift
1
3369
/* Muscle Book Copyright (C) 2016 Cristian Filipov This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import UIKit @IBDesignable class SplitSwipeView: UIView, UIScrollViewDelegate { enum Side: CGFloat { case Both = 1 case Left = 0 case Right = 2 } var visibleSide: Side = .Both { didSet { let offset = CGPoint(x: bounds.width * visibleSide.rawValue, y: 0) pageView.setContentOffset(offset, animated: true) } } private let divider = UIView() private let pageView = UIScrollView() private let leftMaskLayer = CAShapeLayer() private let rightMaskLayer = CAShapeLayer() var left = UIView() { didSet(oldValue) { insertSubview(left, atIndex: 0) oldValue.removeFromSuperview() } } var right = UIView() { didSet(oldValue) { oldValue.removeFromSuperview() insertSubview(right, atIndex: 1) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } private func commonInit() { insertSubview(left, atIndex: 0) insertSubview(right, atIndex: 1) pageView.delegate = self pageView.pagingEnabled = true pageView.scrollEnabled = true pageView.alwaysBounceVertical = false pageView.alwaysBounceHorizontal = true pageView.directionalLockEnabled = true pageView.showsHorizontalScrollIndicator = false pageView.showsVerticalScrollIndicator = false addSubview(pageView) divider.backgroundColor = UIColor.blackColor() addSubview(divider) } override func layoutSubviews() { super.layoutSubviews() divider.frame = CGRect(x: bounds.midX, y: 0, width: 0.5, height: bounds.height) pageView.frame = bounds pageView.contentSize = CGSize(width: bounds.width * 3, height: bounds.width) pageView.contentOffset = CGPoint(x: bounds.width * visibleSide.rawValue, y: 0) left.frame = bounds left.layer.mask = rightMaskLayer right.frame = bounds right.layer.mask = leftMaskLayer; updateMaskLayerPath() } private func updateMaskLayerPath() { let div = pageView.contentOffset.x / 2 let (leftMaskRect, rightMaskRect) = bounds.divide(div, fromEdge: .MaxXEdge) leftMaskLayer.path = CGPathCreateWithRect(leftMaskRect, nil) rightMaskLayer.path = CGPathCreateWithRect(rightMaskRect, nil) divider.frame.origin.x = leftMaskRect.minX } @objc func scrollViewDidScroll(scrollView: UIScrollView) { updateMaskLayerPath() } }
gpl-3.0
acde6b12f33d167f72082bec697edae7
30.783019
87
0.661027
4.792319
false
false
false
false
touchopia/daisywheel
DaisyWheel/ReminderViewController.swift
1
1724
// // TableViewController.swift // // // Created by Phil Wright on 1/10/16. // Copyright © 2016 Touchopia, LLC. All rights reserved. // import UIKit class ReminderViewController: UITableViewController { @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var datePicker: UIDatePicker! open var dateToggle = true lazy var dateFormatter: DateFormatter = { var formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .short return formatter }() override func viewDidLoad() { super.viewDidLoad() datePickerChanged() } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if dateToggle && (indexPath as NSIndexPath).section == 0 && (indexPath as NSIndexPath).row == 1 { return 0 } else { return super.tableView(tableView, heightForRowAt: indexPath) } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if (indexPath as NSIndexPath).section == 0 && (indexPath as NSIndexPath).row == 0 { toggleDatePickerForSelectedIndexPath(indexPath) } } @IBAction func datePickerHasChanged(_ sender: AnyObject) { datePickerChanged() } func datePickerChanged () { dateLabel.text = dateFormatter.string(from: datePicker.date) } func toggleDatePickerForSelectedIndexPath(_ indexPath: IndexPath) { dateToggle = (dateToggle == true) ? false : true tableView.beginUpdates() tableView.deselectRow(at: indexPath, animated: true) tableView.endUpdates() } }
mit
f79dc264831bf17f75b6606b1509283a
29.767857
105
0.645386
5.158683
false
false
false
false
nayutaya/web-mercator-swift
WebMercator/Projector.swift
1
1704
public class Projector { public static let LATITUDE_MAXIMUM_IN_DEGREES = Projector.mercatorYToLatitude(+1.0) public static let LATITUDE_MINIMUM_IN_DEGREES = Projector.mercatorYToLatitude(-1.0) public static let LATITUDE_DELTA_IN_DEGREES = LATITUDE_MAXIMUM_IN_DEGREES - LATITUDE_MINIMUM_IN_DEGREES public static let LONGITUDE_MAXIMUM_IN_DEGREES = Projector.mercatorXToLongitude(+1.0) public static let LONGITUDE_MINIMUM_IN_DEGREES = Projector.mercatorXToLongitude(-1.0) public static let LONGITUDE_DELTA_IN_DEGREES = LONGITUDE_MAXIMUM_IN_DEGREES - LONGITUDE_MINIMUM_IN_DEGREES // 度をラジアンに変換するための係数 private static let DEGREE_TO_RADIAN = M_PI / 180.0 // ラジアンを度に変換するための係数 private static let RADIAN_TO_DEGREE = 180.0 / M_PI // 緯度をメルカトルY座標に変換する public class func latitudeToMercatorY(latitudeInDegrees: Double) -> Double { return atanh(sin(latitudeInDegrees * DEGREE_TO_RADIAN)) / M_PI } // 経度をメルカトルX座標に変換する public class func longitudeToMercatorX(longitudeInDegrees: Double) -> Double { return longitudeInDegrees / 180.0 } // メルカトルY座標を緯度に変換する public class func mercatorYToLatitude(mercatorY: Double) -> Double { return asin(tanh(mercatorY * M_PI)) * RADIAN_TO_DEGREE } // メルカトルX座標を経度に変換する public class func mercatorXToLongitude(mercatorX: Double) -> Double { var x = mercatorX while ( x < -1.0 ) { x += 2.0 } while ( x > +1.0 ) { x -= 2.0 } return x * 180.0 } }
mit
7f8ce4dba4765add6d77e67d0cd9ea76
40.081081
110
0.686842
3.680387
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/Source/Common/PointData.swift
1
1092
// // PointData.swift // SwiftGL // // Created by jerry on 2015/6/4. // Copyright (c) 2015年 Scott Bennett. All rights reserved. // import Foundation import SwiftGL public struct PointData:Initable { //the struct to store basic paint unit, saving data public var paintPoint:PaintPoint! public var timestamps:Double = 0 public init(){ } public init(paintPoint:PaintPoint,t:Double) { self.paintPoint = paintPoint timestamps = t } public var tojson:String { var str = "{" str += "\"time\":\(timestamps)" str += ",\"pos\":\(paintPoint.position.tojson)" str += ",\"force\":\(paintPoint.force)" str += ",\"alt\":\(paintPoint.altitude)" str += ",\"azi\":\(paintPoint.azimuth.tojson)" str += ",\"vel\":\(paintPoint.velocity.tojson)" str += "}" return str } } extension Sequence where Iterator.Element == PointData { public var jsonArray:String { return "{\"points\":[" + self.map {$0.tojson}.joined(separator: ",") + "]}" } }
mit
a616ef1554d94c3a72ba0863b748ac07
23.222222
83
0.573394
4.113208
false
false
false
false
GianniCarlo/Audiobook-Player
BookPlayer/Settings/IconsViewController.swift
1
4371
// // IconsViewController.swift // BookPlayer // // Created by Gianni Carlo on 2/19/19. // Copyright © 2019 Tortuga Power. All rights reserved. // import BookPlayerKit import Themeable import UIKit import WidgetKit class IconsViewController: UIViewController, TelemetryProtocol { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var bannerView: PlusBannerView! @IBOutlet weak var bannerHeightConstraint: NSLayoutConstraint! let userDefaults = UserDefaults(suiteName: Constants.ApplicationGroupIdentifier) var icons: [Icon]! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "settings_app_icon_title".localized self.icons = self.getIcons() self.tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: 1)) if !UserDefaults.standard.bool(forKey: Constants.UserDefaults.donationMade.rawValue) { NotificationCenter.default.addObserver(self, selector: #selector(self.donationMade), name: .donationMade, object: nil) } else { self.donationMade() } setUpTheming() self.sendSignal(.appIconsScreen, with: nil) } @objc func donationMade() { self.bannerView.isHidden = true self.bannerHeightConstraint.constant = 0 self.tableView.reloadData() } func getIcons() -> [Icon] { guard let iconsFile = Bundle.main.url(forResource: "Icons", withExtension: "json"), let data = try? Data(contentsOf: iconsFile, options: .mappedIfSafe), let icons = try? JSONDecoder().decode([Icon].self, from: data) else { return [] } return icons } func changeIcon(to iconName: String) { guard UIApplication.shared.supportsAlternateIcons else { return } self.userDefaults?.set(iconName, forKey: Constants.UserDefaults.appIcon.rawValue) let icon = iconName == "Default" ? nil : iconName UIApplication.shared.setAlternateIconName(icon, completionHandler: { error in if #available(iOS 14.0, *) { WidgetCenter.shared.reloadAllTimelines() } guard error != nil else { return } self.showAlert("error_title".localized, message: "icon_error_description".localized) }) } } extension IconsViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.icons.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // swiftlint:disable force_cast let cell = tableView.dequeueReusableCell(withIdentifier: "IconCellView", for: indexPath) as! IconCellView // swiftlint:enable force_cast let item = self.icons[indexPath.row] cell.titleLabel.text = item.title cell.authorLabel.text = item.author cell.iconImage = UIImage(named: item.imageName) cell.isLocked = item.isLocked && !UserDefaults.standard.bool(forKey: Constants.UserDefaults.donationMade.rawValue) let currentAppIcon = self.userDefaults?.string(forKey: Constants.UserDefaults.appIcon.rawValue) ?? "Default" cell.accessoryType = item.id == currentAppIcon ? .checkmark : .none return cell } } extension IconsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let cell = tableView.cellForRow(at: indexPath) as? IconCellView else { return } defer { tableView.reloadData() } guard !cell.isLocked else { return } let item = self.icons[indexPath.row] self.changeIcon(to: item.id) self.sendSignal(.appIconAction, with: ["icon": item.title]) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 86 } } extension IconsViewController: Themeable { func applyTheme(_ theme: Theme) { self.view.backgroundColor = theme.systemGroupedBackgroundColor self.tableView.backgroundColor = theme.systemGroupedBackgroundColor self.tableView.separatorColor = theme.separatorColor } }
gpl-3.0
98f9311d82a884159c0aa9ffd7cf5133
31.61194
130
0.665904
4.775956
false
false
false
false
robb/swamp
swamp.swift
1
3471
#!/usr/bin/xcrun swift import AppKit extension NSImage { func bitmapRepresentation() -> NSBitmapImageRep { let cgRef = self.CGImageForProposedRect(nil, context: nil, hints: nil) return NSBitmapImageRep(CGImage: cgRef!.takeRetainedValue()) } } struct Swamp { let icon: NSImage let textAttributes: Dictionary<String, AnyObject> let fontName = "HelveticaNeue-Light" init(icon: NSImage) { self.icon = icon self.textAttributes = [ NSShadowAttributeName: { let unit = icon.size.height / 64 let shadow = NSShadow() shadow.shadowOffset = CGSizeMake(0, -unit) shadow.shadowBlurRadius = unit shadow.shadowColor = NSColor.controlDarkShadowColor() return shadow }(), NSParagraphStyleAttributeName: { let paragraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle paragraphStyle.alignment = NSTextAlignment.CenterTextAlignment paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping; return paragraphStyle }(), NSForegroundColorAttributeName: NSColor.whiteColor() ] } func addText(text: String) { let offset = self.icon.size.height / 20 let containerSize = CGSize(width: self.icon.size.width, height: self.icon.size.height - 2 * offset) var fontSize = self.icon.size.height / 4 var textContainer: NSTextContainer var textStorage: NSTextStorage var layoutManager: NSLayoutManager var renderedRange: NSRange var usedRect: CGRect // Keep decreasing the font size until it's either 8 pts or the text // fits completely do { textContainer = NSTextContainer(containerSize: containerSize) textStorage = NSTextStorage(string: text, attributes:textAttributes) textStorage.font = NSFont(name:self.fontName, size: fontSize) layoutManager = NSLayoutManager() layoutManager.addTextContainer(textContainer) layoutManager.textStorage = textStorage renderedRange = layoutManager.glyphRangeForTextContainer(textContainer) usedRect = layoutManager.usedRectForTextContainer(textContainer) fontSize -= 0.1 } while renderedRange.length < countElements(text) && fontSize > 8 let point = CGPointMake(0, self.icon.size.height - usedRect.size.height - offset) self.icon.lockFocusFlipped(true) layoutManager.drawGlyphsForGlyphRange(renderedRange, atPoint:point) self.icon.unlockFocus() } func save(path: String) { self.icon .bitmapRepresentation() .representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:])? .writeToFile(path, atomically:true) } } if Process.arguments.count < 4 { println("Usage: stamp.swift -- [input] [output] [text]") exit(1) } let input = Process.arguments[1] let output = Process.arguments[2] let text = Process.arguments[3] let icon: NSImage? = NSImage(data: NSData(contentsOfFile: input)!) if icon == nil { println("Could not load file \(input)") exit(1) } let swamp = Swamp(icon: icon!) swamp.addText(text) swamp.save(output)
apache-2.0
70bbd53e276b7260a2a3da8b44baf1bb
32.375
118
0.635552
5.142222
false
false
false
false
steelwheels/KiwiGraphics
UnitTest/OSX/UTFontTable/ViewController.swift
1
867
/** * @file ViewController.swift * @brief View controller UTFontTable * @par Copyright * Copyright (C) 2017 Steel Wheels Project */ import Cocoa import KiwiGraphics class ViewController: NSViewController { @IBOutlet weak var mTextField0: NSTextField! @IBOutlet weak var mTextField1: NSTextField! @IBOutlet weak var mTextField2: NSTextField! @IBOutlet weak var mTextField3: NSTextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let table = KGFontTable.sharedFontTable mTextField0.font = table.font(withStyle: .Title) mTextField1.font = table.font(withStyle: .Headline) mTextField2.font = table.font(withStyle: .Body) mTextField3.font = table.font(withStyle: .Caption) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
gpl-2.0
77c9b40fb2cf246f7f30377f63c71f14
22.432432
53
0.740484
3.642857
false
false
false
false
orta/eidolon
KioskTests/Models/BidderPositionTests.swift
1
816
import Quick import Nimble class BidderPositionTests: QuickSpec { override func spec() { it("converts from JSON") { let id = "saf32sadasd" let maxBidAmountCents = 123123123 let bidID = "saf32sadasd" let bidAmount = 100000 let bidData:[String: AnyObject] = ["id": bidID, "amount_cents" : bidAmount ] let data:[String: AnyObject] = ["id":id , "max_bid_amount_cents" : maxBidAmountCents, "highest_bid":bidData] let position = BidderPosition.fromJSON(data) as BidderPosition expect(position.id) == id expect(position.maxBidAmountCents) == maxBidAmountCents expect(position.highestBid.id) == bidID expect(position.highestBid.amountCents) == bidAmount } } }
mit
379c75049b8da49ca300dd0f269f2d47
30.384615
121
0.606618
4.410811
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Vender/TransitionAnimation/SlideTransitionAnimation.swift
1
4433
// // SlideTransitionAnimation.swift // TransitionTreasury // // Created by DianQK on 16/1/21. // Copyright © 2016年 TransitionTreasury. All rights reserved. // import UIKit //import TransitionTreasury public class SlideTransitionAnimation: NSObject, TRViewControllerAnimatedTransitioning, TabBarTransitionInteractiveable { public var transitionStatus: TransitionStatus public var transitionContext: UIViewControllerContextTransitioning? public var completion: (() -> Void)? public var gestureRecognizer: UIGestureRecognizer? { didSet { gestureRecognizer?.addTarget(self, action: #selector(SlideTransitionAnimation.interactiveTransition(_:))) } } public var percentTransition: UIPercentDrivenInteractiveTransition = UIPercentDrivenInteractiveTransition() public var interactivePrecent: CGFloat = 0.3 public var interacting: Bool = false private var tabBarTransitionDirection: TabBarTransitionDirection = .right public init(status: TransitionStatus = .tabBar) { transitionStatus = status super.init() } public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) let containView = transitionContext.containerView guard let tabBarController = fromVC?.tabBarController else { fatalError("No TabBarController.") } guard let fromVCIndex = tabBarController.viewControllers?.index(of: fromVC!) , let toVCIndex = tabBarController.viewControllers?.index(of: toVC!) else { fatalError("VC not in TabBarController.") } let fromVCStartOriginX: CGFloat = 0 var fromVCEndOriginX: CGFloat = -UIScreen.main.bounds.width var toVCStartOriginX: CGFloat = UIScreen.main.bounds.width let toVCEndOriginX: CGFloat = 0 tabBarTransitionDirection = TabBarTransitionDirection.TransitionDirection(fromVCIndex, toVCIndex: toVCIndex) if tabBarTransitionDirection == .left { swap(&fromVCEndOriginX, &toVCStartOriginX) } containView.addSubview(fromVC!.view) containView.addSubview(toVC!.view) fromVC?.view.frame.origin.x = fromVCStartOriginX toVC?.view.frame.origin.x = toVCStartOriginX UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveEaseInOut, animations: { fromVC?.view.frame.origin.x = fromVCEndOriginX toVC?.view.frame.origin.x = toVCEndOriginX }) { finished in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) if !transitionContext.transitionWasCancelled && finished { self.completion?() self.completion = nil } } } public func interactiveTransition(_ sender: UIPanGestureRecognizer) { guard let view = sender.view else { return } let offsetX = tabBarTransitionDirection == .left ? sender.translation(in: view).x : -sender.translation(in: view).x var percent = offsetX / view.bounds.size.width percent = min(1.0, max(0, percent)) switch sender.state { case .began : percentTransition.startInteractiveTransition(transitionContext!) interacting = true case .changed : interacting = true percentTransition.update(percent) default : interacting = false if percent > interactivePrecent { percentTransition.completionSpeed = 1.0 - percentTransition.percentComplete percentTransition.finish() gestureRecognizer?.removeTarget(self, action: #selector(SlideTransitionAnimation.interactiveTransition(_:))) } else { percentTransition.cancel() } } } }
mit
84b3eabd9cd676ae9657946deb188c5b
38.553571
132
0.664334
6.127248
false
false
false
false
peymojo/filehaven
Filehaven/Projects/Filehaven/FilehavenApp/VaultOutlineView.swift
1
1233
// // Filehaven // Copyright (C) 2017 Paul Young (aka peymojo) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import AppKit protocol VaultOutlineViewDelegate: NSOutlineViewDelegate { func outlineView(_ outlineView: NSOutlineView, menuForItem item: Any) -> NSMenu? } class VaultOutlineView: NSOutlineView { override func menu(for event: NSEvent) -> NSMenu? { let point = self.convert(event.locationInWindow, from: nil) let row = self.row(at: point) let item = self.item(atRow: row) if (item == nil) { return nil } return (self.delegate as! VaultOutlineViewDelegate).outlineView(self, menuForItem: item!) } }
gpl-3.0
ee6a7f1de0986938bee2e3685d95303d
35.264706
91
0.737226
3.759146
false
false
false
false
Dan2552/Luncheon
Example/Luncheon/PostDetailViewController.swift
1
944
import UIKit class PostDetailViewController: UITableViewController { var post = Post() var comments: [Comment]? @IBOutlet weak var commentsLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var bodyLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! override func viewDidLoad() { titleLabel.text = post.title bodyLabel.text = post.body User.remote.find(post.userId!) { (user: User?) in self.authorLabel.text = user?.name } post.remote.associated(Comment.self).all { (comments: [Comment]) in self.comments = comments self.populateComments() } } func populateComments() { if let c = comments { if c.count > 0 { commentsLabel.text = "\(c.count) comments" } else { commentsLabel.text = "No comments" } } } }
mit
f7ee235d38c6ec40103d5361d2484c9a
25.222222
75
0.577331
4.696517
false
false
false
false
soleiltw/ios-swift-basic
Swift-Advance/Subscripts.playground/Contents.swift
1
1239
//: Playground - noun: a place where people can play // Here’s an example of a read-only subscript implementation, which defines a TimesTable structure to represent an n-times-table of integers struct TimesTable { let multiplier: Int subscript(index: Int) -> Int { return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) print("six times three is \(threeTimesTable[6])") // Prints "six times three is 18" // https://medium.com/@abhimuralidharan/subscripts-in-swift-51e73cc5ddb5 class Daysofaweek { private var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "saturday"] subscript(index: Int) -> String { get { return days[index] } set(newValue) { self.days[index] = newValue } } } var daysOfWeek = Daysofaweek() print(daysOfWeek[0]) // prints sunday daysOfWeek[0] = "Monday" print(daysOfWeek[0]) // prints Monday struct subexample { let decrementer: Int subscript(index: Int) -> Int { return decrementer / index } } let division = subexample(decrementer: 100) print("The number is divisible by \(division[9]) times") print("The number is divisible by \(division[2]) times")
mit
f6fb2ec616072c4832f2c7a41d13dcda
27.767442
140
0.666128
3.817901
false
false
false
false
ChristianKienle/highway
Sources/Git/GitTool.swift
1
2530
import ZFile import Url import Task import Arguments import SourceryAutoProtocols public struct GitTool: AutoGenerateProtocol { // MARK: - Init public init(system: SystemProtocol) { self.system = system } // MARK: - Properties private let system: SystemProtocol // MARK: - Helper private func _git(with arguments: Arguments, at url: FolderProtocol) throws -> Task { let task = try system.task(named: "git") task.arguments = arguments task.currentDirectoryUrl = url return task } } extension GitTool: GitToolProtocol { public func addAll(at url: FolderProtocol) throws { try system.execute(try _git(with: ["add", "."], at: url)) } public func commit(at url: FolderProtocol, message: String) throws { try system.execute(try _git(with: ["commit", "-m", message], at: url)) } public func pushToMaster(at url: FolderProtocol) throws { try system.execute(try _git(with: ["push", "origin", "master"], at: url)) } public func pushTagsToMaster(at url: FolderProtocol) throws { try system.execute(try _git(with: ["push", "--tags"], at: url)) } public func pull(at url: FolderProtocol) throws { try system.execute(try _git(with: ["pull"], at: url)) } public func currentTag(at url: FolderProtocol) throws -> String { let task = try _git(with: ["describe", "--tags"], at: url) task.enableReadableOutputDataCapturing() try system.execute(task) guard let rawTag = task.trimmedOutput else { throw "Failed to get current tag." } guard rawTag.isEmpty == false else { throw "Failed to get current tag." } guard rawTag.hasPrefix("v") else { throw "'\(rawTag)' is not a valid version number: Must start with 'v'." } let numberOfDots = rawTag.reduce(0) { (result, char) -> Int in return char == "." ? result + 1 : result } guard numberOfDots == 2 else { throw "'\(rawTag)' is not a valid version number: Must contain two '.'." } return rawTag } public func clone(with options: CloneOptions) throws { let input: [String] = ["clone"] + (options.performMirror ? ["--mirror"] : []) + [options.remoteUrl, options.localPath.path] let arguments = Arguments(input) try system.execute(try _git(with: arguments, at: try Folder(path: "/"))) } }
mit
ba732e8f63287115812c6a8f2fcf30ac
32.733333
131
0.598024
4.266442
false
false
false
false
roosmaa/Octowire-iOS
Octowire/EventsBrowserState.swift
1
639
// // EventsState.swift // Octowire // // Created by Mart Roosmaa on 24/02/2017. // Copyright © 2017 Mart Roosmaa. All rights reserved. // import Foundation import ReSwift enum EventsFilter { case repoEvents case starEvents case pullRequestEvents case forkEvents } struct EventsBrowserState: StateType { var isVisible: Bool = false var scrollTopDistance: Float32 = 0 var isPreloadingEvents: Bool = false var preloadedEvents: [(EventModel, eta: UInt16)] = [] var activeFilters: [EventsFilter] = [] var unfilteredEvents: [EventModel] = [] var filteredEvents: [EventModel] = [] }
mit
9e5deb5d0f788a2522f36e4dcc4fc643
21
57
0.683386
3.797619
false
false
false
false
jcheng77/missfit-ios
missfit/missfit/TeacherImageTableViewCell.swift
1
2009
// // TeacherImageTableViewCell.swift // missfit // // Created by Hank Liang on 4/30/15. // Copyright (c) 2015 Hank Liang. All rights reserved. // import UIKit class TeacherImageTableViewCell: UITableViewCell, UIScrollViewDelegate { let aspectRatio: CGFloat = 640.0 / 718.0 var imageArray: [String]? @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var pageControl: UIPageControl! override func awakeFromNib() { super.awakeFromNib() // Initialization code self.scrollView.delegate = self self.pageControl.pageIndicatorTintColor = UIColor.whiteColor() self.pageControl.currentPageIndicatorTintColor = MissFitTheme.theme.colorPink } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setData(images: [String]) { self.imageArray = images let width: CGFloat = MissFitUtils.shortestScreenWidth() let height: CGFloat = width / aspectRatio for var i = 0; i < self.imageArray!.count; i++ { let subView: UIImageView = UIImageView(frame: CGRectMake(width * CGFloat(i), 0, width, height)) subView.contentMode = .ScaleAspectFill subView.clipsToBounds = true subView.setImageWithURL(NSURL(string: self.imageArray![i]), placeholderImage: UIImage(named: "default-pic")) self.scrollView.addSubview(subView) } self.scrollView.contentSize = CGSizeMake(width * CGFloat(self.imageArray!.count), height) self.pageControl.numberOfPages = self.imageArray!.count } func scrollViewDidScroll(scrollView: UIScrollView) { let pageWidth = self.scrollView.frame.size.width let currentPage: Int = Int(floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1) self.pageControl.currentPage = currentPage } }
mit
ff1471879ab3ee930704252a79dd41a4
36.203704
120
0.668492
4.9
false
false
false
false
cloudinary/cloudinary_ios
Cloudinary/Classes/Core/BaseNetwork/CLDNError.swift
1
19744
// // CLDNError.swift // // 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 /// `CLDNError` is the error type returned by Cloudinary. It encompasses a few different types of errors, each with /// their own associated reasons. /// /// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`. /// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process. /// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails. /// - responseValidationFailed: Returned when a `validate()` call fails. /// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process. internal enum CLDNError: Error { /// The underlying reason the parameter encoding error occurred. /// /// - missingURL: The URL request did not have a URL to encode. /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the /// encoding process. /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during /// encoding process. internal enum ParameterEncodingFailureReason { case missingURL case jsonEncodingFailed(error: Error) case propertyListEncodingFailed(error: Error) } /// The underlying reason the multipart encoding error occurred. /// /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a /// file URL. /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty /// `lastPathComponent` or `pathExtension. /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable. /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw /// an error. /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory. /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by /// the system. /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided /// threw an error. /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`. /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the /// encoded data to disk. /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file /// already exists at the provided `fileURL`. /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is /// not a file URL. /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an /// underlying error. /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with /// underlying system error. internal enum MultipartEncodingFailureReason { case bodyPartURLInvalid(url: URL) case bodyPartFilenameInvalid(in: URL) case bodyPartFileNotReachable(at: URL) case bodyPartFileNotReachableWithError(atURL: URL, error: Error) case bodyPartFileIsDirectory(at: URL) case bodyPartFileSizeNotAvailable(at: URL) case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) case bodyPartInputStreamCreationFailed(for: URL) case outputStreamCreationFailed(for: URL) case outputStreamFileAlreadyExists(at: URL) case outputStreamURLInvalid(url: URL) case outputStreamWriteFailed(error: Error) case inputStreamReadFailed(error: Error) } /// The underlying reason the response validation error occurred. /// /// - dataFileNil: The data file containing the server response did not exist. /// - dataFileReadFailed: The data file containing the server response could not be read. /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes` /// provided did not contain wildcard type. /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided /// `acceptableContentTypes`. /// - unacceptableStatusCode: The response status code was not acceptable. internal enum ResponseValidationFailureReason { case dataFileNil case dataFileReadFailed(at: URL) case missingContentType(acceptableContentTypes: [String]) case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) case unacceptableStatusCode(code: Int) } /// The underlying reason the response serialization error occurred. /// /// - inputDataNil: The server response contained no data. /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length. /// - inputFileNil: The file containing the server response did not exist. /// - inputFileReadFailed: The file containing the server response could not be read. /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`. /// - jsonSerializationFailed: JSON serialization failed with an underlying system error. /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error. internal enum ResponseSerializationFailureReason { case inputDataNil case inputDataNilOrZeroLength case inputFileNil case inputFileReadFailed(at: URL) case stringSerializationFailed(encoding: String.Encoding) case jsonSerializationFailed(error: Error) case propertyListSerializationFailed(error: Error) } case invalidURL(url: CLDNURLConvertible) case parameterEncodingFailed(reason: ParameterEncodingFailureReason) case multipartEncodingFailed(reason: MultipartEncodingFailureReason) case responseValidationFailed(reason: ResponseValidationFailureReason) case responseSerializationFailed(reason: ResponseSerializationFailureReason) } // MARK: - Adapt Error struct AdaptError: Error { let error: Error } extension Error { var underlyingAdaptError: Error? { return (self as? AdaptError)?.error } } // MARK: - Error Booleans extension CLDNError { /// Returns whether the CLDNError is an invalid URL error. internal var isInvalidURLError: Bool { if case .invalidURL = self { return true } return false } /// Returns whether the CLDNError is a parameter encoding error. When `true`, the `underlyingError` property will /// contain the associated value. internal var isParameterEncodingError: Bool { if case .parameterEncodingFailed = self { return true } return false } /// Returns whether the CLDNError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties /// will contain the associated values. internal var isMultipartEncodingError: Bool { if case .multipartEncodingFailed = self { return true } return false } /// Returns whether the `CLDNError` is a response validation error. When `true`, the `acceptableContentTypes`, /// `responseContentType`, and `responseCode` properties will contain the associated values. internal var isResponseValidationError: Bool { if case .responseValidationFailed = self { return true } return false } /// Returns whether the `CLDNError` is a response serialization error. When `true`, the `failedStringEncoding` and /// `underlyingError` properties will contain the associated values. internal var isResponseSerializationError: Bool { if case .responseSerializationFailed = self { return true } return false } } // MARK: - Convenience Properties extension CLDNError { /// The `URLConvertible` associated with the error. var urlConvertible: CLDNURLConvertible? { switch self { case .invalidURL(let url): return url default: return nil } } /// The `URL` associated with the error. internal var url: URL? { switch self { case .multipartEncodingFailed(let reason): return reason.url default: return nil } } /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. internal var underlyingError: Error? { switch self { case .parameterEncodingFailed(let reason): return reason.underlyingError case .multipartEncodingFailed(let reason): return reason.underlyingError case .responseSerializationFailed(let reason): return reason.underlyingError default: return nil } } /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. internal var acceptableContentTypes: [String]? { switch self { case .responseValidationFailed(let reason): return reason.acceptableContentTypes default: return nil } } /// The response `Content-Type` of a `.responseValidationFailed` error. internal var responseContentType: String? { switch self { case .responseValidationFailed(let reason): return reason.responseContentType default: return nil } } /// The response code of a `.responseValidationFailed` error. internal var responseCode: Int? { switch self { case .responseValidationFailed(let reason): return reason.responseCode default: return nil } } /// The `String.Encoding` associated with a failed `.stringResponse()` call. internal var failedStringEncoding: String.Encoding? { switch self { case .responseSerializationFailed(let reason): return reason.failedStringEncoding default: return nil } } } extension CLDNError.ParameterEncodingFailureReason { var underlyingError: Error? { switch self { case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): return error default: return nil } } } extension CLDNError.MultipartEncodingFailureReason { var url: URL? { switch self { case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): return url default: return nil } } var underlyingError: Error? { switch self { case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): return error default: return nil } } } extension CLDNError.ResponseValidationFailureReason { var acceptableContentTypes: [String]? { switch self { case .missingContentType(let types), .unacceptableContentType(let types, _): return types default: return nil } } var responseContentType: String? { switch self { case .unacceptableContentType(_, let responseType): return responseType default: return nil } } var responseCode: Int? { switch self { case .unacceptableStatusCode(let code): return code default: return nil } } } extension CLDNError.ResponseSerializationFailureReason { var failedStringEncoding: String.Encoding? { switch self { case .stringSerializationFailed(let encoding): return encoding default: return nil } } var underlyingError: Error? { switch self { case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): return error default: return nil } } } // MARK: - Error Descriptions extension CLDNError: LocalizedError { internal var errorDescription: String? { switch self { case .invalidURL(let url): return "URL is not valid: \(url)" case .parameterEncodingFailed(let reason): return reason.localizedDescription case .multipartEncodingFailed(let reason): return reason.localizedDescription case .responseValidationFailed(let reason): return reason.localizedDescription case .responseSerializationFailed(let reason): return reason.localizedDescription } } } extension CLDNError.ParameterEncodingFailureReason { var localizedDescription: String { switch self { case .missingURL: return "URL request to encode was missing a URL" case .jsonEncodingFailed(let error): return "JSON could not be encoded because of error:\n\(error.localizedDescription)" case .propertyListEncodingFailed(let error): return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)" } } } extension CLDNError.MultipartEncodingFailureReason { var localizedDescription: String { switch self { case .bodyPartURLInvalid(let url): return "The URL provided is not a file URL: \(url)" case .bodyPartFilenameInvalid(let url): return "The URL provided does not have a valid filename: \(url)" case .bodyPartFileNotReachable(let url): return "The URL provided is not reachable: \(url)" case .bodyPartFileNotReachableWithError(let url, let error): return ( "The system returned an error while checking the provided URL for " + "reachability.\nURL: \(url)\nError: \(error)" ) case .bodyPartFileIsDirectory(let url): return "The URL provided is a directory: \(url)" case .bodyPartFileSizeNotAvailable(let url): return "Could not fetch the file size from the provided URL: \(url)" case .bodyPartFileSizeQueryFailedWithError(let url, let error): return ( "The system returned an error while attempting to fetch the file size from the " + "provided URL.\nURL: \(url)\nError: \(error)" ) case .bodyPartInputStreamCreationFailed(let url): return "Failed to create an InputStream for the provided URL: \(url)" case .outputStreamCreationFailed(let url): return "Failed to create an OutputStream for URL: \(url)" case .outputStreamFileAlreadyExists(let url): return "A file already exists at the provided URL: \(url)" case .outputStreamURLInvalid(let url): return "The provided OutputStream URL is invalid: \(url)" case .outputStreamWriteFailed(let error): return "OutputStream write failed with error: \(error)" case .inputStreamReadFailed(let error): return "InputStream read failed with error: \(error)" } } } extension CLDNError.ResponseSerializationFailureReason { var localizedDescription: String { switch self { case .inputDataNil: return "Response could not be serialized, input data was nil." case .inputDataNilOrZeroLength: return "Response could not be serialized, input data was nil or zero length." case .inputFileNil: return "Response could not be serialized, input file was nil." case .inputFileReadFailed(let url): return "Response could not be serialized, input file could not be read: \(url)." case .stringSerializationFailed(let encoding): return "String could not be serialized with encoding: \(encoding)." case .jsonSerializationFailed(let error): return "JSON could not be serialized because of error:\n\(error.localizedDescription)" case .propertyListSerializationFailed(let error): return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)" } } } extension CLDNError.ResponseValidationFailureReason { var localizedDescription: String { switch self { case .dataFileNil: return "Response could not be validated, data file was nil." case .dataFileReadFailed(let url): return "Response could not be validated, data file could not be read: \(url)." case .missingContentType(let types): return ( "Response Content-Type was missing and acceptable content types " + "(\(types.joined(separator: ","))) do not match \"*/*\"." ) case .unacceptableContentType(let acceptableTypes, let responseType): return ( "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + "\(acceptableTypes.joined(separator: ","))." ) case .unacceptableStatusCode(let code): return "Response status code was unacceptable: \(code)." } } }
mit
a81c6a1d5a14c98958f1f7a238ec2aa5
42.10917
124
0.648906
5.553868
false
false
false
false
blitzagency/events
Tests/EventsTests/TestChannel.swift
1
4803
// // TestChannel.swift // Events // // Created by Adam Venturella on 7/27/16. // Copyright © 2016 BLITZ. All rights reserved. // import Foundation import XCTest @testable import Events class TestChannel: XCTestCase { func test0ArgRequest(){ let done = expectation(description: "done") let channel = Channel(label: "test") channel.reply("lucy"){ return "woof" } channel.request("lucy"){ (value: String) in XCTAssert(value == "woof") done.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func test1ArgRequest(){ let done = expectation(description: "done") let channel = Channel(label: "test") channel.reply("lucy"){ (v1: String) -> String in return v1 } channel.request("lucy", "woof"){ (value: String) in XCTAssert(value == "woof") done.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func test2ArgRequest(){ let done = expectation(description: "done") let channel = Channel(label: "test") channel.reply("lucy"){ (v1: String, v2: String) -> String in return "\(v1):\(v2)" } channel.request("lucy", "woof", "chaseSquirrels"){ (value: String) in XCTAssert(value == "woof:chaseSquirrels") done.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testDoesNotReplyToArgumentCountMismatch(){ let done = expectation(description: "done") let channel = Channel(label: "test") channel.reply("lucy"){ (v1: String, v2: String) -> String in return "\(v1):\(v2)" } channel.request("lucy", "woof"){ (value: String) in XCTFail("Should not have triggered") } delay(0.5){ done.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testEventManagerHostListenToChannel(){ let done = expectation(description: "done") let channel = Channel(label: "test") let cat = Cat(id: "1") cat.listenTo(channel, event: "lucy"){ done.fulfill() } channel.trigger("lucy") waitForExpectations(timeout: 1, handler: nil) } func testEventManagerHostListenToChannelPublisherCallback(){ let done = expectation(description: "done") let channel = Channel(label: "test") let cat = Cat(id: "1") cat.listenTo(channel, event: "lucy"){ (sender: Channel) in XCTAssert(sender.channelId == channel.channelId) done.fulfill() } channel.trigger("lucy") waitForExpectations(timeout: 1, handler: nil) } func testEventManagerHostListenToChannelPublisherDataCallback(){ let done = expectation(description: "done") let channel = Channel(label: "test") let cat = Cat(id: "1") cat.listenTo(channel, event: "lucy"){ (sender: Channel, data: String) in XCTAssert(sender.channelId == channel.channelId) XCTAssert(data == "woof") done.fulfill() } channel.trigger("lucy", data: "woof") waitForExpectations(timeout: 1, handler: nil) } func testEventManagerHostListenToChannelPublisherDataCallbackExplicit(){ let done = expectation(description: "done") let channel = Channel(label: "test") let cat = Cat(id: "1") let callback : (Channel, String) -> () = { (sender, data) in XCTAssert(sender.channelId == channel.channelId) XCTAssert(data == "woof") done.fulfill() } cat.listenTo(channel, event: "lucy", callback: callback) channel.trigger("lucy", data: "woof") waitForExpectations(timeout: 1, handler: nil) } func testEmbedded(){ let done = expectation(description: "done") let driver = LocalChannelDriver() let channel = driver.get("test") let foo = Foo(channel: channel, done: done) channel.trigger("lucy", data: "woof") waitForExpectations(timeout: 1, handler: nil) } } class Foo: EventManagerHost{ let eventManager = EventManager() let channel: Channel let done: XCTestExpectation lazy var onEvent: (Channel, String) -> () = {[unowned self] (sender, data) in self.done.fulfill() } init(channel: Channel, done: XCTestExpectation){ self.channel = channel self.done = done listenTo(channel, event: "lucy", callback: onEvent) } }
mit
d64281691abc6f3bf5dad33e1264629c
24.273684
76
0.563932
4.43398
false
true
false
false
brentdax/swift
stdlib/public/core/SmallString.swift
1
25290
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @usableFromInline // FIXME(sil-serialize-all) internal typealias _SmallUTF16StringBuffer = _FixedArray16<UInt16> // // NOTE: Small string is not available on 32-bit platforms (not enough bits!), // but we don't want to #if-def all use sites (at least for now). So, provide a // minimal unavailable interface. // #if arch(i386) || arch(arm) // Helper method for declaring something as not supported in 32-bit. Use inside // a function body inside a #if block so that callers don't have to be // conditional. @_transparent @inlinable func unsupportedOn32bit() -> Never { _conditionallyUnreachable() } // Trivial type declaration for type checking. Never present at runtime. @_fixed_layout public struct _SmallUTF8String {} #else // // The low byte of the first word (low) stores the first code unit. Up to 15 // such code units are encodable, with the second-highest byte of the second // word (high) being the final code unit. The high byte of the final word // stores the count. // // The low and high values are automatically stored in little-endian byte order // by the _RawBitPattern struct, which reverses the byte order as needed to // convert between the little-endian storage format and the host byte order. // The memory layout of the _RawBitPattern struct will therefore be identical // on both big- and little-endian machines. The values of 'high' and 'low' // will also appear to be identical. Routines which build, manipulate and // convert small strings should therefore always assume little-endian byte // order. // // Storage layout: // // |0 1 2 3 4 5 6 7 8 9 a b c d e f| ← offset // | low | high | ← properties // | string | | ← encoded layout // ↑ ↑ // first (low) byte count // // Examples: // ! o l l e H 6 // |H e l l o ! ░ ░ ░ ░ ░ ░ ░ ░ ░|6| → low=0x0000216f6c6c6548 high=0x0600000000000000 // // W , o l l e H 13 ! d l r o // |H e l l o , W o r l d ! ░ ░|d| → low=0x57202c6f6c6c6548 high=0x0d000021646c726f // @_fixed_layout @usableFromInline internal struct _SmallUTF8String { @_fixed_layout @usableFromInline internal struct _RawBitPattern: Equatable { // high and low are stored in little-endian byte order @usableFromInline internal var _storage: (low: UInt, high: UInt) @inlinable var low: UInt { @inline(__always) get { return _storage.low.littleEndian } @inline(__always) set { _storage.low = newValue.littleEndian } } @inlinable var high: UInt { @inline(__always) get { return _storage.high.littleEndian } @inline(__always) set { _storage.high = newValue.littleEndian } } @inlinable @inline(__always) init(low l: UInt, high h: UInt) { // host byte order to little-endian byte order _storage.low = l.littleEndian _storage.high = h.littleEndian } @inlinable @inline(__always) static func == (lhs: _RawBitPattern, rhs: _RawBitPattern) -> Bool { return lhs._storage == rhs._storage } } @usableFromInline var _storage: _RawBitPattern @inlinable @inline(__always) init() { self._storage = _RawBitPattern(low: 0, high: 0) } } #endif // 64-bit // // Small string creation interface // extension _SmallUTF8String { @inlinable static internal var capacity: Int { return 15 } #if _runtime(_ObjC) @usableFromInline internal init?(_cocoaString cocoa: _CocoaString) { #if arch(i386) || arch(arm) return nil // Never form small strings on 32-bit #else self.init() let len = self._withAllUnsafeMutableBytes { bufPtr -> Int? in guard let len = _bridgeASCIICocoaString(cocoa, intoUTF8: bufPtr), len <= _SmallUTF8String.capacity else { return nil } return len } guard let count = len else { return nil } _sanityCheck(self.count == 0, "overwrote count early?") self.count = count _invariantCheck() #endif } #endif // _runtime(_ObjC) @inlinable internal init?<C: RandomAccessCollection>(_ codeUnits: C) where C.Element == UInt16 { #if arch(i386) || arch(arm) return nil // Never form small strings on 32-bit #else guard codeUnits.count <= _SmallUTF8String.capacity else { return nil } // TODO(TODO: JIRA): Just implement this directly self.init() var bufferIdx = 0 for encodedScalar in Unicode._ParsingIterator( codeUnits: codeUnits.makeIterator(), parser: Unicode.UTF16.ForwardParser() ) { guard let transcoded = Unicode.UTF8.transcode( encodedScalar, from: Unicode.UTF16.self ) else { // FIXME: can this fail with unpaired surrogates? _sanityCheckFailure("UTF-16 should be transcodable to UTF-8") return nil } _sanityCheck(transcoded.count <= 4, "how?") guard bufferIdx + transcoded.count <= _SmallUTF8String.capacity else { return nil } for i in transcoded.indices { self._uncheckedSetCodeUnit(at: bufferIdx, to: transcoded[i]) bufferIdx += 1 } } _sanityCheck(self.count == 0, "overwrote count early?") self.count = bufferIdx // FIXME: support transcoding if !self.isASCII { return nil } _invariantCheck() #endif } @inline(__always) @inlinable @_effects(readonly) public // @testable init?(_ codeUnits: UnsafeBufferPointer<UInt8>) { #if arch(i386) || arch(arm) return nil // Never form small strings on 32-bit #else let count = codeUnits.count guard count <= _SmallUTF8String.capacity else { return nil } let addr = codeUnits.baseAddress._unsafelyUnwrappedUnchecked var high: UInt let lowCount: Int if count > 8 { lowCount = 8 high = _bytesToUInt(addr + 8, count &- 8) } else { lowCount = count high = 0 } high |= (UInt(count) &<< (8*15)) let low = _bytesToUInt(addr, lowCount) _storage = _RawBitPattern(low: low, high: high) // FIXME: support transcoding if !self.isASCII { return nil } _invariantCheck() #endif } @inlinable public // @testable init?(_ scalar: Unicode.Scalar) { #if arch(i386) || arch(arm) return nil // Never form small strings on 32-bit #else // FIXME: support transcoding guard scalar.value <= 0x7F else { return nil } self.init() self.count = 1 self[0] = UInt8(truncatingIfNeeded: scalar.value) #endif } } @inline(__always) @inlinable func _bytesToUInt(_ input: UnsafePointer<UInt8>, _ c: Int) -> UInt { var r: UInt = 0 var shift: Int = 0 for idx in 0..<c { r = r | (UInt(input[idx]) &<< shift) shift = shift &+ 8 } return r } // // Small string read interface // extension _SmallUTF8String { @inlinable @inline(__always) func withUTF8CodeUnits<Result>( _ body: (UnsafeBufferPointer<UInt8>) throws -> Result ) rethrows -> Result { #if arch(i386) || arch(arm) unsupportedOn32bit() #else return try _withAllUnsafeBytes { bufPtr in let ptr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked .assumingMemoryBound(to: UInt8.self) return try body(UnsafeBufferPointer(start: ptr, count: self.count)) } #endif } @inlinable @inline(__always) public // @testable func withTranscodedUTF16CodeUnits<Result>( _ body: (UnsafeBufferPointer<UInt16>) throws -> Result ) rethrows -> Result { #if arch(i386) || arch(arm) unsupportedOn32bit() #else var (transcoded, transcodedCount) = self.transcoded return try Swift.withUnsafeBytes(of: &transcoded.storage) { bufPtr -> Result in let ptr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked .assumingMemoryBound(to: UInt16.self) return try body(UnsafeBufferPointer(start: ptr, count: transcodedCount)) } #endif } @inlinable @inline(__always) func withUnmanagedUTF16<Result>( _ body: (_UnmanagedString<UInt16>) throws -> Result ) rethrows -> Result { #if arch(i386) || arch(arm) unsupportedOn32bit() #else return try withTranscodedUTF16CodeUnits { return try body(_UnmanagedString($0)) } #endif } @inlinable @inline(__always) func withUnmanagedASCII<Result>( _ body: (_UnmanagedString<UInt8>) throws -> Result ) rethrows -> Result { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(self.isASCII) return try withUTF8CodeUnits { return try body(_UnmanagedString($0)) } #endif } } extension _SmallUTF8String { @inlinable public // @testable // FIXME: internal(set) var count: Int { @inline(__always) get { #if arch(i386) || arch(arm) unsupportedOn32bit() #else return Int(bitPattern: UInt(self._uncheckedCodeUnit(at: 15))) #endif } @inline(__always) set { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(newValue <= _SmallUTF8String.capacity, "out of bounds") self._uncheckedSetCodeUnit( at: 15, to: UInt8(truncatingIfNeeded: UInt(bitPattern: newValue))) #endif } } @inlinable public // @testable var capacity: Int { @inline(__always) get { return 15 } } @inlinable public // @testable var unusedCapacity: Int { @inline(__always) get { return capacity - count } } @inlinable public // @testable var isASCII: Bool { @inline(__always) get { #if arch(i386) || arch(arm) unsupportedOn32bit() #else // TODO (TODO: JIRA): Consider using our last bit for this _sanityCheck(_uncheckedCodeUnit(at: 15) & 0xF0 == 0) let topBitMask: UInt = 0x8080_8080_8080_8080 return (_storage.low | _storage.high) & topBitMask == 0 #endif } } @inlinable func _invariantCheck() { #if arch(i386) || arch(arm) unsupportedOn32bit() #else #if INTERNAL_CHECKS_ENABLED _sanityCheck(count <= _SmallUTF8String.capacity) _sanityCheck(self.isASCII, "UTF-8 currently unsupported") #endif // INTERNAL_CHECKS_ENABLED #endif } internal func _dump() { #if arch(i386) || arch(arm) unsupportedOn32bit() #else #if INTERNAL_CHECKS_ENABLED print(""" smallUTF8: count: \(self.count), codeUnits: \( self.map { String($0, radix: 16) }.dropLast() ) """) #endif // INTERNAL_CHECKS_ENABLED #endif } @inlinable // FIXME(sil-serialize-all) internal func _copy<TargetCodeUnit>( into target: UnsafeMutableBufferPointer<TargetCodeUnit> ) where TargetCodeUnit : FixedWidthInteger & UnsignedInteger { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(target.count >= self.count) guard count > 0 else { return } if _fastPath(TargetCodeUnit.bitWidth == 8) { _sanityCheck(TargetCodeUnit.self == UInt8.self) let target = _castBufPtr(target, to: UInt8.self) // TODO: Inspect generated code. Consider checking count for alignment so // we can just copy our UInts directly when possible. var ptr = target.baseAddress._unsafelyUnwrappedUnchecked for cu in self { ptr[0] = cu ptr += 1 } return } _sanityCheck(TargetCodeUnit.self == UInt16.self) self.transcode(_uncheckedInto: _castBufPtr(target, to: UInt16.self)) #endif } } extension _SmallUTF8String: RandomAccessCollection { public // @testable typealias Index = Int public // @testable typealias Element = UInt8 public // @testable typealias SubSequence = _SmallUTF8String @inlinable public // @testable var startIndex: Int { @inline(__always) get { return 0 } } @inlinable public // @testable var endIndex: Int { @inline(__always) get { return count } } @inlinable public // @testable subscript(_ idx: Int) -> UInt8 { @inline(__always) get { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(idx >= 0 && idx <= count) return _uncheckedCodeUnit(at: idx) #endif } @inline(__always) set { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(idx >= 0 && idx <= count) _uncheckedSetCodeUnit(at: idx, to: newValue) #endif } } @inlinable public // @testable subscript(_ bounds: Range<Index>) -> SubSequence { @inline(__always) get { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(bounds.lowerBound >= 0 && bounds.upperBound <= count) return self._uncheckedClamp( lowerBound: bounds.lowerBound, upperBound: bounds.upperBound) #endif } } } extension _SmallUTF8String { @inlinable public // @testable func _repeated(_ n: Int) -> _SmallUTF8String? { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(n > 1) let finalCount = self.count * n guard finalCount <= 15 else { return nil } var ret = self for _ in 0..<(n &- 1) { ret = ret._appending(self)._unsafelyUnwrappedUnchecked } return ret #endif } @inlinable public // @testable func _appending<C: RandomAccessCollection>(_ other: C) -> _SmallUTF8String? where C.Element == UInt8 { #if arch(i386) || arch(arm) unsupportedOn32bit() #else guard other.count <= self.unusedCapacity else { return nil } // TODO: as _copyContents var result = self result._withMutableExcessCapacityBytes { rawBufPtr in var i = 0 for cu in other { rawBufPtr[i] = cu i += 1 } } result.count = self.count &+ other.count return result #endif } @inlinable func _appending<C: RandomAccessCollection>(_ other: C) -> _SmallUTF8String? where C.Element == UInt16 { #if arch(i386) || arch(arm) unsupportedOn32bit() #else guard other.count <= self.unusedCapacity else { return nil } // TODO: as _copyContents var result = self let success = result._withMutableExcessCapacityBytes { rawBufPtr -> Bool in var i = 0 for cu in other { guard cu <= 0x7F else { // TODO: transcode and communicate count back return false } rawBufPtr[i] = UInt8(truncatingIfNeeded: cu) i += 1 } return true } guard success else { return nil } result.count = self.count &+ other.count return result #endif } // NOTE: This exists to facilitate _fromCodeUnits, which is awful for this use // case. Please don't call this from anywhere else. @inlinable init?<S: Sequence, Encoding: Unicode.Encoding>( _fromCodeUnits codeUnits: S, utf16Length: Int, isASCII: Bool, _: Encoding.Type = Encoding.self ) where S.Element == Encoding.CodeUnit { #if arch(i386) || arch(arm) return nil // Never form small strings on 32-bit #else guard utf16Length <= 15 else { return nil } // TODO: transcode guard isASCII else { return nil } self.init() var bufferIdx = 0 for encodedScalar in Unicode._ParsingIterator( codeUnits: codeUnits.makeIterator(), parser: Encoding.ForwardParser() ) { guard let transcoded = Unicode.UTF8.transcode( encodedScalar, from: Encoding.self ) else { fatalError("Somehow un-transcodable?") } _sanityCheck(transcoded.count <= 4, "how?") guard bufferIdx + transcoded.count <= 15 else { return nil } for i in transcoded.indices { self._uncheckedSetCodeUnit(at: bufferIdx, to: transcoded[i]) bufferIdx += 1 } } _sanityCheck(self.count == 0, "overwrote count early?") self.count = bufferIdx // FIXME: support transcoding if !self.isASCII { return nil } _invariantCheck() #endif } } extension _SmallUTF8String { #if arch(i386) || arch(arm) @_fixed_layout @usableFromInline struct UnicodeScalarIterator { @inlinable @inline(__always) func next() -> Unicode.Scalar? { unsupportedOn32bit() } } @inlinable @inline(__always) func makeUnicodeScalarIterator() -> UnicodeScalarIterator { unsupportedOn32bit() } #else // FIXME (TODO: JIRA): Just make a real decoding iterator @_fixed_layout @usableFromInline // FIXME(sil-serialize-all) struct UnicodeScalarIterator { @usableFromInline // FIXME(sil-serialize-all) var buffer: _SmallUTF16StringBuffer @usableFromInline // FIXME(sil-serialize-all) var count: Int @usableFromInline // FIXME(sil-serialize-all) var _offset: Int @inlinable // FIXME(sil-serialize-all) init(_ base: _SmallUTF8String) { (self.buffer, self.count) = base.transcoded self._offset = 0 } @inlinable // FIXME(sil-serialize-all) mutating func next() -> Unicode.Scalar? { if _slowPath(_offset == count) { return nil } let u0 = buffer[_offset] if _fastPath(UTF16._isScalar(u0)) { _offset += 1 return Unicode.Scalar(u0) } if UTF16.isLeadSurrogate(u0) && _offset + 1 < count { let u1 = buffer[_offset + 1] if UTF16.isTrailSurrogate(u1) { _offset += 2 return UTF16._decodeSurrogates(u0, u1) } } _offset += 1 return Unicode.Scalar._replacementCharacter } } @inlinable func makeUnicodeScalarIterator() -> UnicodeScalarIterator { return UnicodeScalarIterator(self) } #endif // 64-bit } #if arch(i386) || arch(arm) #else extension _SmallUTF8String { @inlinable @inline(__always) init(_rawBits: (low: UInt, high: UInt)) { self.init() self._storage.low = _rawBits.low self._storage.high = _rawBits.high _invariantCheck() } @inlinable @inline(__always) init(low: UInt, high: UInt, count: Int) { self.init() self._storage.low = low self._storage.high = high self.count = count _invariantCheck() } @inlinable internal var _rawBits: _RawBitPattern { @inline(__always) get { return _storage } } @inlinable internal var lowUnpackedBits: UInt { @inline(__always) get { return _storage.low } } @inlinable internal var highUnpackedBits: UInt { @inline(__always) get { return _storage.high & 0x00FF_FFFF_FFFF_FFFF } } @inlinable internal var unpackedBits: (low: UInt, high: UInt, count: Int) { @inline(__always) get { return (lowUnpackedBits, highUnpackedBits, count) } } } extension _SmallUTF8String { // Operate with a pointer to the entire struct, including unused capacity // and inline count. You should almost never call this directly. @inlinable @inline(__always) mutating func _withAllUnsafeMutableBytes<Result>( _ body: (UnsafeMutableRawBufferPointer) throws -> Result ) rethrows -> Result { var copy = self defer { self = copy } return try Swift.withUnsafeMutableBytes(of: &copy._storage) { try body($0) } } @inlinable @inline(__always) func _withAllUnsafeBytes<Result>( _ body: (UnsafeRawBufferPointer) throws -> Result ) rethrows -> Result { var copy = self return try Swift.withUnsafeBytes(of: &copy._storage) { try body($0) } } @inlinable @inline(__always) mutating func _withMutableExcessCapacityBytes<Result>( _ body: (UnsafeMutableRawBufferPointer) throws -> Result ) rethrows -> Result { let unusedCapacity = self.unusedCapacity let count = self.count return try self._withAllUnsafeMutableBytes { allBufPtr in let ptr = allBufPtr.baseAddress._unsafelyUnwrappedUnchecked + count return try body( UnsafeMutableRawBufferPointer(start: ptr, count: unusedCapacity)) } } } extension _SmallUTF8String { @inlinable @inline(__always) func _uncheckedCodeUnit(at i: Int) -> UInt8 { _sanityCheck(i >= 0 && i <= 15) if i < 8 { return _storage.low._uncheckedGetByte(at: i) } else { return _storage.high._uncheckedGetByte(at: i &- 8) } } @inlinable @inline(__always) mutating func _uncheckedSetCodeUnit(at i: Int, to: UInt8) { // TODO(TODO: JIRA): in-register operation instead self._withAllUnsafeMutableBytes { $0[i] = to } } } extension _SmallUTF8String { @inlinable @inline(__always) internal func _uncheckedClamp(upperBound: Int) -> _SmallUTF8String { _sanityCheck(upperBound <= self.count) guard upperBound >= 8 else { var low = self.lowUnpackedBits let shift = upperBound &* 8 let mask: UInt = (1 &<< shift) &- 1 low &= mask return _SmallUTF8String(low: low, high: 0, count: upperBound) } let shift = (upperBound &- 8) &* 8 _sanityCheck(shift % 8 == 0) var high = self.highUnpackedBits high &= (1 &<< shift) &- 1 return _SmallUTF8String( low: self.lowUnpackedBits, high: high, count: upperBound) } @inlinable @inline(__always) internal func _uncheckedClamp(lowerBound: Int) -> _SmallUTF8String { _sanityCheck(lowerBound < self.count) let low: UInt let high: UInt if lowerBound < 8 { let shift: UInt = UInt(bitPattern: lowerBound) &* 8 let newLowHigh: UInt = self.highUnpackedBits & ((1 &<< shift) &- 1) low = (self.lowUnpackedBits &>> shift) | (newLowHigh &<< (64 &- shift)) high = self.highUnpackedBits &>> shift } else { high = 0 low = self.highUnpackedBits &>> ((lowerBound &- 8) &* 8) } return _SmallUTF8String( low: low, high: high, count: self.count &- lowerBound) } @inlinable @inline(__always) internal func _uncheckedClamp( lowerBound: Int, upperBound: Int ) -> _SmallUTF8String { // TODO: More efficient to skip the intermediary shifts and just mask up // front. _sanityCheck(upperBound >= lowerBound) if lowerBound == upperBound { return _SmallUTF8String() } let dropTop = self._uncheckedClamp(upperBound: upperBound) return dropTop._uncheckedClamp(lowerBound: lowerBound) } } extension _SmallUTF8String {//}: _StringVariant { @usableFromInline internal typealias TranscodedBuffer = _SmallUTF16StringBuffer @inlinable @discardableResult func transcode( _uncheckedInto buffer: UnsafeMutableBufferPointer<UInt16> ) -> Int { if _fastPath(isASCII) { _sanityCheck(buffer.count >= self.count) var bufferIdx = 0 for cu in self { buffer[bufferIdx] = UInt16(cu) bufferIdx += 1 } return bufferIdx } let length = _transcodeNonASCII(_uncheckedInto: buffer) _sanityCheck(length <= buffer.count) // TODO: assert ahead-of-time return length } @inlinable @inline(__always) func transcode(into buffer: UnsafeMutablePointer<TranscodedBuffer>) -> Int { let ptr = UnsafeMutableRawPointer(buffer).assumingMemoryBound( to: UInt16.self) return transcode( _uncheckedInto: UnsafeMutableBufferPointer(start: ptr, count: count)) } @inlinable var transcoded: (TranscodedBuffer, count: Int) { @inline(__always) get { // TODO: in-register zero-extension for ascii var buffer = TranscodedBuffer(allZeros:()) let count = transcode(into: &buffer) return (buffer, count: count) } } @usableFromInline @inline(never) // @outlined func _transcodeNonASCII( _uncheckedInto buffer: UnsafeMutableBufferPointer<UInt16> ) -> Int { _sanityCheck(!isASCII) // TODO(TODO: JIRA): Just implement this directly var bufferIdx = 0 for encodedScalar in Unicode._ParsingIterator( codeUnits: self.makeIterator(), parser: Unicode.UTF8.ForwardParser() ) { guard let transcoded = Unicode.UTF16.transcode( encodedScalar, from: Unicode.UTF8.self ) else { fatalError("Somehow un-transcodable?") } switch transcoded.count { case 1: buffer[bufferIdx] = transcoded.first! bufferIdx += 1 case 2: buffer[bufferIdx] = transcoded.first! buffer[bufferIdx+1] = transcoded.dropFirst().first! bufferIdx += 2 case _: fatalError("Somehow, not transcoded or more than 2?") } } _sanityCheck(bufferIdx <= buffer.count) // TODO: assert earlier return bufferIdx } } @inlinable @inline(__always) internal func _castBufPtr<A, B>( _ bufPtr: UnsafeMutableBufferPointer<A>, to: B.Type = B.self ) -> UnsafeMutableBufferPointer<B> { let numBytes = bufPtr.count &* MemoryLayout<A>.stride _sanityCheck(numBytes % MemoryLayout<B>.stride == 0) let ptr = UnsafeMutableRawPointer( bufPtr.baseAddress._unsafelyUnwrappedUnchecked ).assumingMemoryBound(to: B.self) let count = numBytes / MemoryLayout<B>.stride return UnsafeMutableBufferPointer(start: ptr, count: count) } #endif // 64-bit extension UInt { // Fetches the `i`th byte, from least-significant to most-significant @inlinable @inline(__always) func _uncheckedGetByte(at i: Int) -> UInt8 { _sanityCheck(i >= 0 && i < MemoryLayout<UInt>.stride) let shift = UInt(bitPattern: i) &* 8 return UInt8(truncatingIfNeeded: (self &>> shift)) } }
apache-2.0
7e8cd0bc777356ca11624e33a240aebb
27.248322
87
0.644532
4.032897
false
false
false
false
tenebreux/realm-cocoa
RealmSwift-swift2.0/Object.swift
15
13120
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // 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 import Realm import Realm.Private /** In Realm you define your model classes by subclassing `Object` and adding properties to be persisted. You then instantiate and use your custom subclasses instead of using the Object class directly. ```swift class Dog: Object { dynamic var name: String = "" dynamic var adopted: Bool = false let siblings = List<Dog>() } ``` ### Supported property types - `String`, `NSString` - `Int` - `Float` - `Double` - `Bool` - `NSDate` - `NSData` - `RealmOptional<T>` for optional numeric properties - `Object` subclasses for to-one relationships - `List<T: Object>` for to-many relationships `String`, `NSString`, `NSDate`, `NSData` and `Object` subclass properties can be optional. `Int`, `Float`, `Double`, `Bool` and `List` properties cannot. To store an optional number, instead use `RealmOptional<Int>`, `RealmOptional<Float>`, `RealmOptional<Double>`, or `RealmOptional<Bool>` instead, which wraps an optional value of the generic type. All property types except for `List` and `RealmOptional` *must* be declared as `dynamic var`. `List` and `RealmOptional` properties must be declared as non-dynamic `let` properties. ### Querying You can gets `Results` of an Object subclass via tha `objects(_:)` free function or the `objects(_:)` instance method on `Realm`. ### Relationships See our [Cocoa guide](http://realm.io/docs/cocoa) for more details. */ public class Object: RLMObjectBase { // MARK: Initializers /** Initialize a standalone (unpersisted) Object. Call `add(_:)` on a `Realm` to add standalone objects to a realm. - see: Realm().add(_:) */ public required override init() { super.init() } /** Initialize a standalone (unpersisted) `Object` with values from an `Array<AnyObject>` or `Dictionary<String, AnyObject>`. Call `add(_:)` on a `Realm` to add standalone objects to a realm. - parameter value: The value used to populate the object. This can be any key/value coding compliant object, or a JSON object such as those returned from the methods in `NSJSONSerialization`, or an `Array` with one object for each persisted property. An exception will be thrown if any required properties are not present and no default is set. */ public init(value: AnyObject) { self.dynamicType.sharedSchema() // ensure this class' objectSchema is loaded in the partialSharedSchema super.init(value: value, schema: RLMSchema.partialSharedSchema()) } // MARK: Properties /// The `Realm` this object belongs to, or `nil` if the object /// does not belong to a realm (the object is standalone). public var realm: Realm? { if let rlmReam = RLMObjectBaseRealm(self) { return Realm(rlmReam) } return nil } /// The `ObjectSchema` which lists the persisted properties for this object. public var objectSchema: ObjectSchema { return ObjectSchema(RLMObjectBaseObjectSchema(self)) } /// Indicates if an object can no longer be accessed. /// /// An object can no longer be accessed if the object has been deleted from the containing /// `realm` or if `invalidate` is called on the containing `realm`. public override var invalidated: Bool { return super.invalidated } /// Returns a human-readable description of this object. public override var description: String { return super.description } #if os(OSX) /// Helper to return the class name for an Object subclass. public final override var className: String { return "" } #else /// Helper to return the class name for an Object subclass. public final var className: String { return "" } #endif // MARK: Object Customization /** Override to designate a property as the primary key for an `Object` subclass. Only properties of type String and Int can be designated as the primary key. Primary key properties enforce uniqueness for each value whenever the property is set which incurs some overhead. Indexes are created automatically for primary key properties. - returns: Name of the property designated as the primary key, or `nil` if the model has no primary key. */ public class func primaryKey() -> String? { return nil } /** Override to return an array of property names to ignore. These properties will not be persisted and are treated as transient. - returns: `Array` of property names to ignore. */ public class func ignoredProperties() -> [String] { return [] } /** Return an array of property names for properties which should be indexed. Only supported for string and int properties. - returns: `Array` of property names to index. */ public class func indexedProperties() -> [String] { return [] } // MARK: Inverse Relationships /** Get an `Array` of objects of type `className` which have this object as the given property value. This can be used to get the inverse relationship value for `Object` and `List` properties. - parameter className: The type of object on which the relationship to query is defined. - parameter property: The name of the property which defines the relationship. - returns: An `Array` of objects of type `className` which have this object as their value for the `propertyName` property. */ public func linkingObjects<T: Object>(type: T.Type, forProperty propertyName: String) -> [T] { // FIXME: use T.className() return RLMObjectBaseLinkingObjectsOfClass(self, (T.self as Object.Type).className(), propertyName) as! [T] } // MARK: Key-Value Coding & Subscripting /// Returns or sets the value of the property with the given name. public subscript(key: String) -> AnyObject? { get { if realm == nil { return self.valueForKey(key) } let property = RLMValidatedGetProperty(self, key) if property.type == .Array { return self.listForProperty(property) } return RLMDynamicGet(self, property) } set(value) { if realm == nil { self.setValue(value, forKey: key) } else { RLMDynamicValidatedSet(self, key, value) } } } // MARK: Dynamic list /** This method is useful only in specialized circumstances, for example, when building components that integrate with Realm. If you are simply building an app on Realm, it is recommended to use instance variables or cast the KVC returns. Returns a List of DynamicObjects for a property name - warning: This method is useful only in specialized circumstances - parameter propertyName: The name of the property to get a List<DynamicObject> - returns: A List of DynamicObjects :nodoc: */ public func dynamicList(propertyName: String) -> List<DynamicObject> { return unsafeBitCast(listForProperty(RLMValidatedGetProperty(self, propertyName)), List<DynamicObject>.self) } // MARK: Equatable /// Returns whether both objects are equal. /// Objects are considered equal when they are both from the same Realm /// and point to the same underlying object in the database. public override func isEqual(object: AnyObject?) -> Bool { return RLMObjectBaseAreEqual(self as RLMObjectBase?, object as? RLMObjectBase); } // MARK: Private functions // FIXME: None of these functions should be exposed in the public interface. /** WARNING: This is an internal initializer not intended for public use. :nodoc: */ public override init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm: realm, schema: schema) } /** WARNING: This is an internal initializer not intended for public use. :nodoc: */ public override init(value: AnyObject, schema: RLMSchema) { super.init(value: value, schema: schema) } // Helper for getting the list object for a property internal func listForProperty(prop: RLMProperty) -> RLMListBase { return object_getIvar(self, prop.swiftIvar) as! RLMListBase } } /// Object interface which allows untyped getters and setters for Objects. /// :nodoc: public final class DynamicObject: Object { private var listProperties = [String: List<DynamicObject>]() // Override to create List<DynamicObject> on access internal override func listForProperty(prop: RLMProperty) -> RLMListBase { if let list = listProperties[prop.name] { return list } let list = List<DynamicObject>() listProperties[prop.name] = list return list } /// :nodoc: public override func valueForUndefinedKey(key: String) -> AnyObject? { return self[key] } /// :nodoc: public override func setValue(value: AnyObject?, forUndefinedKey key: String) { self[key] = value } /// :nodoc: public override class func shouldIncludeInDefaultSchema() -> Bool { return false; } } /// :nodoc: /// Internal class. Do not use directly. public class ObjectUtil: NSObject { @objc private class func ignoredPropertiesForClass(type: AnyClass) -> NSArray? { if let type = type as? Object.Type { return type.ignoredProperties() as NSArray? } return nil } @objc private class func indexedPropertiesForClass(type: AnyClass) -> NSArray? { if let type = type as? Object.Type { return type.indexedProperties() as NSArray? } return nil } // Get the names of all properties in the object which are of type List<>. @objc private class func getGenericListPropertyNames(object: AnyObject) -> NSArray { return Mirror(reflecting: object).children.filter { (prop: Mirror.Child) in return prop.value.dynamicType is RLMListBase.Type }.flatMap { (prop: Mirror.Child) in return prop.label } } @objc private class func initializeListProperty(object: RLMObjectBase, property: RLMProperty, array: RLMArray) { (object as! Object).listForProperty(property)._rlmArray = array } @objc private class func getOptionalProperties(object: AnyObject) -> NSDictionary { return Mirror(reflecting: object).children.reduce([String:AnyObject]()) { (var properties: [String:AnyObject], prop: Mirror.Child) in guard let name = prop.label else { return properties } let mirror = Mirror(reflecting: prop.value) let type = mirror.subjectType if type is Optional<String>.Type || type is Optional<NSString>.Type { properties[name] = Int(PropertyType.String.rawValue) } else if type is Optional<NSDate>.Type { properties[name] = Int(PropertyType.Date.rawValue) } else if type is Optional<NSData>.Type { properties[name] = Int(PropertyType.Data.rawValue) } else if type is Optional<Object>.Type { properties[name] = Int(PropertyType.Object.rawValue) } else if type is RealmOptional<Int>.Type || type is RealmOptional<Int16>.Type || type is RealmOptional<Int32>.Type || type is RealmOptional<Int64>.Type { properties[name] = Int(PropertyType.Int.rawValue) } else if type is RealmOptional<Float>.Type { properties[name] = Int(PropertyType.Float.rawValue) } else if type is RealmOptional<Double>.Type { properties[name] = Int(PropertyType.Double.rawValue) } else if type is RealmOptional<Bool>.Type { properties[name] = Int(PropertyType.Bool.rawValue) } else if prop.value as? RLMOptionalBase != nil { throwRealmException("'\(type)' is not a a valid RealmOptional type.") } else if mirror.displayStyle == .Optional { properties[name] = NSNull() } return properties } } @objc private class func requiredPropertiesForClass(_: AnyClass) -> NSArray? { return nil } }
apache-2.0
00f1751e79afad2f243e9c7cae967b62
36.167139
141
0.65282
4.750181
false
false
false
false
MobileWorkshop/iOS
RestExample/HelloRest/HelloRest/ViewController.swift
1
2166
// // ViewController.swift // HelloRest // // Created by Venkat on 6/23/16. // Copyright © 2016 Venkat. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class ViewController: UIViewController{ @IBOutlet weak var tableView: UITableView! var tableAdapter: TableAdapter? var jsonResults: JSON = [] { didSet { self.tableAdapter?.items = jsonResults self.tableView?.reloadData() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.title = "Hello Rest!" self.tableAdapter = TableAdapter(jsonData: self.jsonResults) self.tableView?.dataSource = self.tableAdapter getData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getData() { Alamofire .request("http://localhost:8000/listall") .validate(statusCode: 200..<400) .responseJSON { [weak self] response in if let value = response.result.value { self?.jsonResults = JSON(value) } } } } class TableAdapter: NSObject, UITableViewDataSource { var items: JSON let cellIdentifier = "SOME_IDENTIFIER" init(jsonData: JSON) { self.items = jsonData super.init() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier) ?? UITableViewCell(style: .default, reuseIdentifier: self.cellIdentifier) cell.textLabel?.text = items[indexPath.row, "name"].stringValue return cell } func numberOfSections(in tableView: UITableView) -> Int { return 1 } }
mit
5a1f73e9d496c6fbe66d1a30f871796f
24.77381
176
0.609238
5.034884
false
false
false
false
lenssss/whereAmI
Whereami/Controller/Personal/View/UIButtonPointedExtension.swift
1
1023
// // UIButtonPointedExtension.swift // Whereami // // Created by 陈鹏宇 on 16/7/18. // Copyright © 2016年 WuQifei. All rights reserved. // import Foundation import UIKit extension UIButton { public override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { var viewController:UIViewController? = nil for var next = self.superview;(next != nil);next = next?.superview { let nextResponder = next?.nextResponder() if nextResponder!.isKindOfClass(UIViewController.self){ viewController = nextResponder as? UIViewController } } guard viewController != nil else{ return super.pointInside(point, withEvent: event) } var bounds = self.bounds let widthDelta = max(50-bounds.size.width, 0) let heightDelta = max(50-bounds.size.height, 0) bounds = CGRectInset(bounds, -0.5*widthDelta, -0.5*heightDelta) return CGRectContainsPoint(bounds, point) } }
mit
87a1b999f63a707bc2b5935af655c5cc
31.709677
89
0.643984
4.38961
false
false
false
false
rodrigoff/hackingwithswift
project2/Project2/ViewController.swift
1
2130
// // ViewController.swift // Project2 // // Created by Rodrigo F. Fernandes on 7/20/17. // Copyright © 2017 Rodrigo F. Fernandes. All rights reserved. // import GameplayKit import UIKit class ViewController: UIViewController { @IBOutlet weak var button1: UIButton! @IBOutlet weak var button2: UIButton! @IBOutlet weak var button3: UIButton! var countries = [String]() var correctAnswer = 0 var score = 0 override func viewDidLoad() { super.viewDidLoad() button1.layer.borderWidth = 1 button2.layer.borderWidth = 1 button3.layer.borderWidth = 1 button1.layer.borderColor = UIColor.lightGray.cgColor button2.layer.borderColor = UIColor.lightGray.cgColor button3.layer.borderColor = UIColor.lightGray.cgColor countries += ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"] askQuestion(action: nil) } func askQuestion(action: UIAlertAction!) { countries = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: countries) as! [String] button1.setImage(UIImage(named: countries[0]), for: .normal) button2.setImage(UIImage(named: countries[1]), for: .normal) button3.setImage(UIImage(named: countries[2]), for: .normal) correctAnswer = GKRandomSource.sharedRandom().nextInt(upperBound: 3) title = countries[correctAnswer].uppercased() } @IBAction func buttonTapped(_ sender: UIButton) { var title: String if sender.tag == correctAnswer { title = "Correct" score += 1 } else { title = "Wrong" score -= 1 } let ac = UIAlertController(title: title, message: "Your score is \(score).", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion)) present(ac, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
18d49ddb4bdd3a925876c5f162cece83
28.985915
135
0.624706
4.482105
false
false
false
false
TintPoint/Overlay
Sources/StyleProtocols/TextStyle.swift
1
6605
// // TextStyle.swift // Overlay // // Created by Justin Jia on 8/28/16. // Copyright © 2016 TintPoint. MIT license. // import UIKit /// A protocol that describes an item that can represent a text. /// - SeeAlso: `TextStyleGroup`, `TextGroup` public protocol TextStyle { /// Returns a `String` that will be used in normal state. /// - Returns: A `String` that will be used in normal state. func normal() -> String } /// A protocol that describes an item that can represent a text in different states (e.g. disabled). /// - SeeAlso: `TextStyle`, `TextGroup` public protocol TextStyleGroup: TextStyle { /// Returns a `String` that will be used in disabled state. /// - Returns: A `String` that will be used in disabled state, or `nil` if no text is set. func disabled() -> String? /// Returns a `String` that will be used in selected state. /// - Returns: A `String` that will be used in selected state, or `nil` if no text is set. func selected() -> String? /// Returns a `String` that will be used in highlighted state. /// - Returns: A `String` that will be used in highlighted state, or `nil` if no text is set. func highlighted() -> String? /// Returns a `String` that will be used in focused state. /// - Returns: A `String` that will be used in focused state, or `nil` if no text is set. func focused() -> String? } public extension TextStyleGroup { /// Returns `nil` by default. /// - Returns: `nil` by default. func disabled() -> String? { return nil } /// Returns `nil` by default. /// - Returns: `nil` by default. func selected() -> String? { return nil } /// Returns `nil` by default. /// - Returns: `nil` by default. func highlighted() -> String? { return nil } /// Returns `nil` by default. /// - Returns: `nil` by default. func focused() -> String? { return nil } } extension String: TextStyle { public func normal() -> String { return self } } /// A collection of `TextStyle` that can represent a text in different states (e.g. disabled). /// - SeeAlso: `TextStyle`, `TextStyleGroup` public struct TextGroup { /// The `TextStyle` that will be used in normal state. private let normalStorage: TextStyle /// The `TextStyle` that will be used in disabled state, or `nil` if no `TextStyle` is set. private let disabledStorage: TextStyle? /// The `TextStyle` that will be used in selected state, or `nil` if no `TextStyle` is set. private let selectedStorage: TextStyle? /// The `TextStyle` that will be used in highlighted state, or `nil` if no `TextStyle` is set. private let highlightedStorage: TextStyle? /// The `TextStyle` that will be used in focused state, or `nil` if no `TextStyle` is set. private let focusedStorage: TextStyle? /// Creates an instance with objects that conforms to `TextStyle`. /// - Parameter normal: A `TextStyle` that will be used in normal state. /// - Parameter disabled: A `TextStyle` that will be used in disabled state. /// - Parameter selected: A `TextStyle` that will be used in selected state. /// - Parameter highlighted: A `TextStyle` that will be used in highlighted state. /// - Parameter focused: A `TextStyle` that will be used in focused state. public init(normal: TextStyle, disabled: TextStyle? = nil, selected: TextStyle? = nil, highlighted: TextStyle? = nil, focused: TextStyle? = nil) { normalStorage = normal disabledStorage = disabled selectedStorage = selected highlightedStorage = highlighted focusedStorage = focused } } extension TextGroup: TextStyleGroup { public func normal() -> String { return normalStorage.normal() } public func disabled() -> String? { return disabledStorage?.normal() } public func selected() -> String? { return selectedStorage?.normal() } public func highlighted() -> String? { return highlightedStorage?.normal() } public func focused() -> String? { return focusedStorage?.normal() } } /// A protocol that describes a view that its texts can be represented by `TextStyle`. public protocol TextStyleRepresentable { /// Returns a `String` that will be used in current state. /// - Parameter style: A `TextStyle` that represents the text. /// - Parameter states: An array of `UIControlState` that should be treated as normal state. /// - Returns: A `String` that will be used in current state, or normal text if no text is set. func selectedText(from style: TextStyle, usingNormalFor states: [UIControlState]) -> String /// Customizes a text through a setter method. /// - Parameter style: A `TextStyle` that represents a text. /// - Parameter setter: A setter method that will customize a text in different states. /// - Parameter text: A `String` that will be used. /// - Parameter state: An `UIControlState` that will use the text. func customizeText(using style: TextStyle, through setter: (_ text: String?, _ state: UIControlState) -> Void) } public extension TextStyleRepresentable { func selectedText(from style: TextStyle, usingNormalFor states: [UIControlState] = []) -> String { guard let styleGroup = style as? TextStyleGroup else { return style.normal() } if let view = self as? ViewHighlightable, view.isHighlighted, !states.contains(.highlighted) { return styleGroup.highlighted() ?? styleGroup.normal() } else if let view = self as? ViewSelectable, view.isSelected, !states.contains(.selected) { return styleGroup.selected() ?? styleGroup.normal() } else if let view = self as? ViewDisable, !view.isEnabled, !states.contains(.disabled) { return styleGroup.disabled() ?? styleGroup.normal() } else if let view = self as? ViewFocusable, view.isFocused, !states.contains(.focused) { return styleGroup.focused() ?? styleGroup.normal() } else { return styleGroup.normal() } } func customizeText(using style: TextStyle, through setter: (_ text: String?, _ state: UIControlState) -> Void) { setter(style.normal(), .normal) if let styleGroup = style as? TextStyleGroup { setter(styleGroup.highlighted(), .highlighted) setter(styleGroup.disabled(), .disabled) setter(styleGroup.selected(), .selected) setter(styleGroup.focused(), .focused) } } }
mit
31e715876a892954f101af5e086d375a
38.076923
150
0.652786
4.34188
false
false
false
false
ashleymills/Reachability.swift
ReachabilityMacSample/ViewController.swift
1
3535
// // ViewController.swift // ReachabilityMacSample // // Created by Reda Lemeden on 28/11/2015. // Copyright © 2015 Ashley Mills. All rights reserved. // import Cocoa import Reachability class ViewController: NSViewController { @IBOutlet weak var networkStatus: NSTextField! @IBOutlet weak var hostNameLabel: NSTextField! var reachability: Reachability? let hostNames = [nil, "google.com", "invalidhost"] var hostIndex = 0 override func viewDidLoad() { super.viewDidLoad() view.wantsLayer = true startHost(at: 0) } func startHost(at index: Int) { stopNotifier() setupReachability(hostNames[index], useClosures: true) startNotifier() DispatchQueue.main.asyncAfter(deadline: .now() + 5) { self.startHost(at: (index + 1) % 3) } } func setupReachability(_ hostName: String?, useClosures: Bool) { let reachability: Reachability? if let hostName = hostName { reachability = try? Reachability(hostname: hostName) hostNameLabel.stringValue = hostName } else { reachability = try? Reachability() hostNameLabel.stringValue = "No host name" } self.reachability = reachability print("--- set up with host name: \(hostNameLabel.stringValue)") if useClosures { reachability?.whenReachable = { reachability in self.updateLabelColourWhenReachable(reachability) } reachability?.whenUnreachable = { reachability in self.updateLabelColourWhenNotReachable(reachability) } } else { NotificationCenter.default.addObserver( self, selector: #selector(ViewController.reachabilityChanged(_:)), name: .reachabilityChanged, object: reachability ) } } func startNotifier() { print("--- start notifier") do { try reachability?.startNotifier() } catch { networkStatus.textColor = .red networkStatus.stringValue = "Unable to start\nnotifier" return } } func stopNotifier() { print("--- stop notifier") reachability?.stopNotifier() NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: nil) reachability = nil } func updateLabelColourWhenReachable(_ reachability: Reachability) { print("\(reachability.description) - \(reachability.connection.description)") if reachability.connection == .wifi { self.networkStatus.textColor = .green } else { self.networkStatus.textColor = .blue } self.networkStatus.stringValue = "\(reachability.connection)" } func updateLabelColourWhenNotReachable(_ reachability: Reachability) { print("\(reachability.description) - \(reachability.connection)") self.networkStatus.textColor = .red self.networkStatus.stringValue = "\(reachability.connection)" } @objc func reachabilityChanged(_ note: Notification) { let reachability = note.object as! Reachability if reachability.connection != .unavailable { updateLabelColourWhenReachable(reachability) } else { updateLabelColourWhenNotReachable(reachability) } } }
mit
37e3939e48a994233a939d4f3ab2f600
30.837838
96
0.605546
5.582938
false
false
false
false
danielgindi/Charts
Source/Charts/Data/Implementations/Standard/BarLineScatterCandleBubbleChartDataSet.swift
2
1196
// // BarLineScatterCandleBubbleChartDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class BarLineScatterCandleBubbleChartDataSet: ChartDataSet, BarLineScatterCandleBubbleChartDataSetProtocol { // MARK: - Data functions and accessors // MARK: - Styling functions and accessors open var highlightColor = NSUIColor(red: 255.0/255.0, green: 187.0/255.0, blue: 115.0/255.0, alpha: 1.0) open var highlightLineWidth = CGFloat(0.5) open var highlightLineDashPhase = CGFloat(0.0) open var highlightLineDashLengths: [CGFloat]? // MARK: - NSCopying open override func copy(with zone: NSZone? = nil) -> Any { let copy = super.copy(with: zone) as! BarLineScatterCandleBubbleChartDataSet copy.highlightColor = highlightColor copy.highlightLineWidth = highlightLineWidth copy.highlightLineDashPhase = highlightLineDashPhase copy.highlightLineDashLengths = highlightLineDashLengths return copy } }
apache-2.0
be0311481f5de96a9e6ef8b5fb3ef87e
30.473684
111
0.718227
4.901639
false
false
false
false
xwu/swift
test/attr/attr_specialize.swift
1
17831
// RUN: %target-typecheck-verify-swift // RUN: %target-swift-ide-test -print-ast-typechecked -source-filename=%s -disable-objc-attr-requires-foundation-module -define-availability 'SwiftStdlib 5.5:macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0' | %FileCheck %s struct S<T> {} public protocol P { } extension Int: P { } public protocol ProtocolWithDep { associatedtype Element } public class C1 { } class Base {} class Sub : Base {} class NonSub {} // Specialize freestanding functions with the correct number of concrete types. // ---------------------------------------------------------------------------- // CHECK: @_specialize(exported: false, kind: full, where T == Int) @_specialize(where T == Int) // CHECK: @_specialize(exported: false, kind: full, where T == S<Int>) @_specialize(where T == S<Int>) @_specialize(where T == Int, U == Int) // expected-error{{cannot find type 'U' in scope}}, @_specialize(where T == T1) // expected-error{{cannot find type 'T1' in scope}} // expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} // expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}} public func oneGenericParam<T>(_ t: T) -> T { return t } // CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Int) @_specialize(where T == Int, U == Int) @_specialize(where T == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'U' in '_specialize' attribute}} public func twoGenericParams<T, U>(_ t: T, u: U) -> (T, U) { return (t, u) } @_specialize(where T == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'nonGenericParam(x:)'}} func nonGenericParam(x: Int) {} // Specialize contextual types. // ---------------------------- class G<T> { // CHECK: @_specialize(exported: false, kind: full, where T == Int) @_specialize(where T == Int) @_specialize(where T == T) // expected-warning{{redundant same-type constraint 'T' == 'T'}} // expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} // expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}} @_specialize(where T == S<T>) // expected-error{{same-type constraint 'T' == 'S<T>' is recursive}} // expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} // expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}} @_specialize(where T == Int, U == Int) // expected-error{{cannot find type 'U' in scope}} func noGenericParams() {} // CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Float) @_specialize(where T == Int, U == Float) // CHECK: @_specialize(exported: false, kind: full, where T == Int, U == S<Int>) @_specialize(where T == Int, U == S<Int>) @_specialize(where T == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note {{missing constraint for 'U' in '_specialize' attribute}} func oneGenericParam<U>(_ t: T, u: U) -> (U, T) { return (u, t) } } // Specialize with requirements. // ----------------------------- protocol Thing {} struct AThing : Thing {} // CHECK: @_specialize(exported: false, kind: full, where T == AThing) @_specialize(where T == AThing) @_specialize(where T == Int) // expected-error{{same-type constraint type 'Int' does not conform to required protocol 'Thing'}} // expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} // expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}} func oneRequirement<T : Thing>(_ t: T) {} protocol HasElt { associatedtype Element } struct IntElement : HasElt { typealias Element = Int } struct FloatElement : HasElt { typealias Element = Float } @_specialize(where T == FloatElement) @_specialize(where T == IntElement) // FIXME e/xpected-error{{'T.Element' cannot be equal to both 'IntElement.Element' (aka 'Int') and 'Float'}} func sameTypeRequirement<T : HasElt>(_ t: T) where T.Element == Float {} @_specialize(where T == Sub) @_specialize(where T == NonSub) // expected-error{{'T' requires that 'NonSub' inherit from 'Base'}} // expected-note@-1 {{same-type constraint 'T' == 'NonSub' implied here}} func superTypeRequirement<T : Base>(_ t: T) {} @_specialize(where X:_Trivial(8), Y == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'requirementOnNonGenericFunction(x:y:)'}} public func requirementOnNonGenericFunction(x: Int, y: Int) { } @_specialize(where Y == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}} public func missingRequirement<X:P, Y>(x: X, y: Y) { } @_specialize(where) // expected-error{{expected type}} @_specialize() // expected-error{{expected a parameter label or a where clause in '_specialize' attribute}} expected-error{{expected declaration}} public func funcWithEmptySpecializeAttr<X: P, Y>(x: X, y: Y) { } @_specialize(where X:_Trivial(8), Y:_Trivial(32), Z == Int) // expected-error{{cannot find type 'Z' in scope}} @_specialize(where X:_Trivial(8), Y:_Trivial(32, 4)) @_specialize(where X == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}} @_specialize(where Y:_Trivial(32)) // expected-error {{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}} @_specialize(where Y: P) // expected-error{{only same-type and layout requirements are supported by '_specialize' attribute}} @_specialize(where Y: MyClass) // expected-error{{cannot find type 'MyClass' in scope}} expected-error{{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}} @_specialize(where X:_Trivial(8), Y == Int) @_specialize(where X == Int, Y == Int) @_specialize(where X == Int, X == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}} // expected-warning@-1{{redundant same-type constraint 'X' == 'Int'}} // expected-note@-2{{same-type constraint 'X' == 'Int' written here}} @_specialize(where Y:_Trivial(32), X == Float) @_specialize(where X1 == Int, Y1 == Int) // expected-error{{cannot find type 'X1' in scope}} expected-error{{cannot find type 'Y1' in scope}} expected-error{{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}} public func funcWithTwoGenericParameters<X, Y>(x: X, y: Y) { } @_specialize(where X == Int, Y == Int) @_specialize(exported: true, where X == Int, Y == Int) @_specialize(exported: false, where X == Int, Y == Int) @_specialize(exported: false where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}} @_specialize(exported: yes, where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}} @_specialize(exported: , where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}} @_specialize(kind: partial, where X == Int, Y == Int) @_specialize(kind: partial, where X == Int) @_specialize(kind: full, where X == Int, Y == Int) @_specialize(kind: any, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}} @_specialize(kind: false, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}} @_specialize(kind: partial where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}} @_specialize(kind: partial, where X == Int, Y == Int) @_specialize(kind: , where X == Int, Y == Int) @_specialize(exported: true, kind: partial, where X == Int, Y == Int) @_specialize(exported: true, exported: true, where X == Int, Y == Int) // expected-error{{parameter 'exported' was already defined in '_specialize' attribute}} @_specialize(kind: partial, exported: true, where X == Int, Y == Int) @_specialize(kind: partial, kind: partial, where X == Int, Y == Int) // expected-error{{parameter 'kind' was already defined in '_specialize' attribute}} @_specialize(where X == Int, Y == Int, exported: true, kind: partial) // expected-error{{cannot find type 'exported' in scope}} expected-error{{cannot find type 'kind' in scope}} expected-error{{cannot find type 'partial' in scope}} expected-error{{expected type}} public func anotherFuncWithTwoGenericParameters<X: P, Y>(x: X, y: Y) { } @_specialize(where T: P) // expected-error{{only same-type and layout requirements are supported by '_specialize' attribute}} @_specialize(where T: Int) // expected-error{{type 'T' constrained to non-protocol, non-class type 'Int'}} expected-note {{use 'T == Int' to require 'T' to be 'Int'}} // expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} // expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}} @_specialize(where T: S1) // expected-error{{type 'T' constrained to non-protocol, non-class type 'S1'}} expected-note {{use 'T == S1' to require 'T' to be 'S1'}} // expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} // expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}} @_specialize(where T: C1) // expected-error{{only same-type and layout requirements are supported by '_specialize' attribute}} @_specialize(where Int: P) // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}} expected-error{{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} expected-note{{missing constraint for 'T' in '_specialize' attribute}} func funcWithForbiddenSpecializeRequirement<T>(_ t: T) { } @_specialize(where T: _Trivial(32), T: _Trivial(64), T: _Trivial, T: _RefCountedObject) // expected-error@-1{{type 'T' has conflicting constraints '_Trivial(64)' and '_Trivial(32)'}} // expected-error@-2{{type 'T' has conflicting constraints '_RefCountedObject' and '_Trivial(32)'}} // expected-warning@-3{{redundant constraint 'T' : '_Trivial'}} // expected-note@-4 {{constraint 'T' : '_Trivial' implied here}} // expected-note@-5 2{{constraint conflicts with 'T' : '_Trivial(32)'}} @_specialize(where T: _Trivial, T: _Trivial(64)) // expected-warning@-1{{redundant constraint 'T' : '_Trivial'}} // expected-note@-2 1{{constraint 'T' : '_Trivial' implied here}} @_specialize(where T: _RefCountedObject, T: _NativeRefCountedObject) // expected-warning@-1{{redundant constraint 'T' : '_RefCountedObject'}} // expected-note@-2 1{{constraint 'T' : '_RefCountedObject' implied here}} @_specialize(where Array<T> == Int) // expected-error{{generic signature requires types 'Array<T>' and 'Int' to be the same}} // expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} // expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}} @_specialize(where T.Element == Int) // expected-error{{only requirements on generic parameters are supported by '_specialize' attribute}} public func funcWithComplexSpecializeRequirements<T: ProtocolWithDep>(t: T) -> Int { return 55555 } public protocol Proto: class { } @_specialize(where T: _RefCountedObject) // expected-warning@-1 {{redundant constraint 'T' : '_RefCountedObject'}} // expected-error@-2 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} // expected-note@-3 {{missing constraint for 'T' in '_specialize' attribute}} @_specialize(where T: _Trivial) // expected-error@-1{{type 'T' has conflicting constraints '_Trivial' and '_NativeClass'}} // expected-error@-2 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} // expected-note@-3 {{missing constraint for 'T' in '_specialize' attribute}} @_specialize(where T: _Trivial(64)) // expected-error@-1{{type 'T' has conflicting constraints '_Trivial(64)' and '_NativeClass'}} // expected-error@-2 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} // expected-note@-3 {{missing constraint for 'T' in '_specialize' attribute}} public func funcWithABaseClassRequirement<T>(t: T) -> Int where T: C1 { return 44444 } public struct S1 { } @_specialize(exported: false, where T == Int64) public func simpleGeneric<T>(t: T) -> T { return t } @_specialize(exported: true, where S: _Trivial(64)) // Check that any bitsize size is OK, not only powers of 8. @_specialize(where S: _Trivial(60)) @_specialize(exported: true, where S: _RefCountedObject) @inline(never) public func copyValue<S>(_ t: S, s: inout S) -> Int64 where S: P{ return 1 } @_specialize(exported: true, where S: _Trivial) @_specialize(exported: true, where S: _Trivial(64)) @_specialize(exported: true, where S: _Trivial(32)) @_specialize(exported: true, where S: _RefCountedObject) @_specialize(exported: true, where S: _NativeRefCountedObject) @_specialize(exported: true, where S: _Class) @_specialize(exported: true, where S: _NativeClass) @inline(never) public func copyValueAndReturn<S>(_ t: S, s: inout S) -> S where S: P{ return s } struct OuterStruct<S> { struct MyStruct<T> { @_specialize(where T == Int, U == Float) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 2, but expected 3)}} expected-note{{missing constraint for 'S' in '_specialize' attribute}} public func foo<U>(u : U) { } @_specialize(where T == Int, U == Float, S == Int) public func bar<U>(u : U) { } } } // Check _TrivialAtMostN constraints. @_specialize(exported: true, where S: _TrivialAtMost(64)) @inline(never) public func copy2<S>(_ t: S, s: inout S) -> S where S: P{ return s } // Check missing alignment. @_specialize(where S: _Trivial(64, )) // expected-error{{expected non-negative alignment to be specified in layout constraint}} // Check non-numeric size. @_specialize(where S: _Trivial(Int)) // expected-error{{expected non-negative size to be specified in layout constraint}} // Check non-numeric alignment. @_specialize(where S: _Trivial(64, X)) // expected-error{{expected non-negative alignment to be specified in layout constraint}} @inline(never) public func copy3<S>(_ s: S) -> S { return s } public func funcWithWhereClause<T>(t: T) where T:P, T: _Trivial(64) { // expected-error{{layout constraints are only allowed inside '_specialize' attributes}} } // rdar://problem/29333056 public protocol P1 { associatedtype DP1 associatedtype DP11 } public protocol P2 { associatedtype DP2 : P1 } public struct H<T> { } public struct MyStruct3 : P1 { public typealias DP1 = Int public typealias DP11 = H<Int> } public struct MyStruct4 : P2 { public typealias DP2 = MyStruct3 } @_specialize(where T==MyStruct4) public func foo<T: P2>(_ t: T) where T.DP2.DP11 == H<T.DP2.DP1> { } public func targetFun<T>(_ t: T) {} @_specialize(exported: true, target: targetFun(_:), where T == Int) public func specifyTargetFunc<T>(_ t: T) { } public struct Container { public func targetFun<T>(_ t: T) {} } extension Container { @_specialize(exported: true, target: targetFun(_:), where T == Int) public func specifyTargetFunc<T>(_ t: T) { } @_specialize(exported: true, target: targetFun2(_:), where T == Int) // expected-error{{target function 'targetFun2' could not be found}} public func specifyTargetFunc2<T>(_ t: T) { } } // Make sure we don't complain that 'E' is not explicitly specialized here. // E becomes concrete via the combination of 'S == Set<String>' and // 'E == S.Element'. @_specialize(where S == Set<String>) public func takesSequenceAndElement<S, E>(_: S, _: E) where S : Sequence, E == S.Element {} // CHECK: @_specialize(exported: true, kind: full, availability: macOS 11, iOS 13, *; where T == Int) // CHECK: public func testAvailability<T>(_ t: T) @_specialize(exported: true, availability: macOS 11, iOS 13, *; where T == Int) public func testAvailability<T>(_ t: T) {} // CHECK: @_specialize(exported: true, kind: full, availability: macOS, introduced: 11; where T == Int) // CHECK: public func testAvailability2<T>(_ t: T) @_specialize(exported: true, availability: macOS 11, *; where T == Int) public func testAvailability2<T>(_ t: T) {} // CHECK: @_specialize(exported: true, kind: full, availability: macOS, introduced: 11; where T == Int) // CHECK: public func testAvailability3<T>(_ t: T) @_specialize(exported: true, availability: macOS, introduced: 11; where T == Int) public func testAvailability3<T>(_ t: T) {} // CHECK: @_specialize(exported: true, kind: full, availability: macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *; where T == Int) // CHECK: public func testAvailability4<T>(_ t: T) @_specialize(exported: true, availability: SwiftStdlib 5.5, *; where T == Int) public func testAvailability4<T>(_ t: T) {}
apache-2.0
d422e547756d440bbd257b53ae7ceaac
50.684058
393
0.69267
3.643441
false
false
false
false
ahoppen/swift
test/decl/func/default-values.swift
3
7138
// RUN: %target-typecheck-verify-swift var func5 : (_ fn : (Int,Int) -> ()) -> () // Default arguments for functions. func foo3(a: Int = 2, b: Int = 3) {} func functionCall() { foo3(a: 4) foo3() foo3(a : 4) foo3(b : 4) foo3(a : 2, b : 4) } func g() {} func h(_ x: () -> () = g) { x() } // Tuple types cannot have default values, but recover well here. func tupleTypes() { typealias ta1 = (a : Int = ()) // expected-error{{default argument not permitted in a tuple type}}{{28-32=}} // expected-error @-1{{cannot create a single-element tuple with an element label}}{{20-24=}} var c1 : (a : Int, b : Int, c : Int = 3, // expected-error{{default argument not permitted in a tuple type}}{{39-42=}} d = 4) = (1, 2, 3, 4) // expected-error{{default argument not permitted in a tuple type}}{{15-18=}} expected-error{{cannot find type 'd' in scope}} } func returnWithDefault() -> (a: Int, b: Int = 42) { // expected-error{{default argument not permitted in a tuple type}} {{45-49=}} return 5 // expected-error{{cannot convert return expression of type 'Int' to return type '(a: Int, b: Int)'}} } func selectorStyle(_ i: Int = 1, withFloat f: Float = 2) { } // Default arguments of constructors. struct Ctor { init (i : Int = 17, f : Float = 1.5) { } } Ctor() // expected-warning{{unused}} Ctor(i: 12) // expected-warning{{unused}} Ctor(f:12.5) // expected-warning{{unused}} // Default arguments for nested constructors/functions. struct Outer<T> { struct Inner { struct VeryInner { init (i : Int = 17, f : Float = 1.5) { } static func f(i: Int = 17, f: Float = 1.5) { } func g(i: Int = 17, f: Float = 1.5) { } } } } _ = Outer<Int>.Inner.VeryInner() _ = Outer<Int>.Inner.VeryInner(i: 12) _ = Outer<Int>.Inner.VeryInner(f:12.5) Outer<Int>.Inner.VeryInner.f() Outer<Int>.Inner.VeryInner.f(i: 12) Outer<Int>.Inner.VeryInner.f(f:12.5) var vi : Outer<Int>.Inner.VeryInner vi.g() vi.g(i: 12) vi.g(f:12.5) // <rdar://problem/14564964> crash on invalid func foo(_ x: WonkaWibble = 17) { } // expected-error{{cannot find type 'WonkaWibble' in scope}} // Default arguments for initializers. class SomeClass2 { init(x: Int = 5) {} } class SomeDerivedClass2 : SomeClass2 { init() { super.init() } } func shouldNotCrash(_ a : UndefinedType, bar b : Bool = true) { // expected-error {{cannot find type 'UndefinedType' in scope}} } // <rdar://problem/20749423> Compiler crashed while building simple subclass // code class SomeClass3 { init(x: Int = 5, y: Int = 5) {} } class SomeDerivedClass3 : SomeClass3 {} _ = SomeDerivedClass3() // Tuple types with default arguments are not materializable func identity<T>(_ t: T) -> T { return t } func defaultArgTuplesNotMaterializable(_ x: Int, y: Int = 0) {} defaultArgTuplesNotMaterializable(identity(5)) // <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands defaultArgTuplesNotMaterializable(identity((5, y: 10))) // expected-error@-1 {{conflicting arguments to generic parameter 'T' ('(Int, y: Int)' vs. 'Int')}} // rdar://problem/21799331 func foo<T>(_ x: T, y: Bool = true) {} foo(true ? "foo" : "bar") func foo2<T>(_ x: T, y: Bool = true) {} extension Array { func bar(_ x: (Element) -> Bool) -> Int? { return 0 } } foo2([].bar { $0 == "c" }!) // rdar://problem/21643052 let a = ["1", "2"].map { Int($0) } // Default arguments for static members used via ".foo" struct X<T> { static func foo(i: Int, j: Int = 0) -> X { return X() } static var bar: X { return X() } } let testXa: X<Int> = .foo(i: 0) let testXb: X<Int> = .bar // SR-10062 var aLiteral = 1 let bLiteral = 2 func inoutFuncWithDefaultArg1(x: inout Int = 1) {} // expected-error {{cannot provide default value to inout parameter 'x'}} func inoutFuncWithDefaultArg2(x: inout Int = bLiteral) {} // expected-error {{cannot provide default value to inout parameter 'x'}} func inoutFuncWithDefaultArg3(x: inout Int = aLiteral) {} // expected-error {{cannot provide default value to inout parameter 'x'}} func inoutFuncWithDefaultArg4(x: inout Int = &aLiteral) {} // expected-error {{cannot provide default value to inout parameter 'x'}} // expected-error@-1 {{'&' may only be used to pass an argument to inout parameter}} func inoutFuncWithDefaultArg5(x: inout Int = &bLiteral) {} // expected-error {{cannot provide default value to inout parameter 'x'}} // expected-error@-1 {{'&' may only be used to pass an argument to inout parameter}} func inoutFuncWithDefaultArg6(x: inout Int = #file) {} // expected-error {{cannot provide default value to inout parameter 'x'}} // expected-error@-1 {{default argument value of type 'String' cannot be converted to type 'Int'}} func inoutFuncWithDefaultArg7(_: inout Int = 1) {} // expected-error {{cannot provide default value to inout parameter '_'}} // SE-0242 - Test that memberwise constructor generates default values struct Foo { var a: Int var b: Bool = false let c: (Int, Bool) = (1, true) let d: Int var (e, f) = (0, false) var g: Int? let h: Bool? // The generated memberwise should look like the following: // init(a: Int, b: Bool = false, d: Int, e: Int, f: Bool, g: Int? = nil, h: Bool?) } // Here b = false and g = nil let fooThing1 = Foo(a: 0, d: 1, e: 2, f: false, h: nil) // ok // Here g = nil let fooThing2 = Foo(a: 0, b: true, d: 1, e: 2, f: false, h: nil) // ok // Here b = false let fooThing3 = Foo(a: 0, d: 1, e: 2, f: false, g: 10, h: nil) // ok // Use all the parameters let fooThing4 = Foo(a: 0, b: true, d: 1, e: 2, f: false, g: 10, h: nil) // ok // Ensure that tuple init is not allowed // Here b = false and g = nil, but we're checking that e and f don't get a default value let fooThing5 = Foo(a: 0, d: 1, h: nil) // expected-error {{missing arguments for parameters 'e', 'f' in call}} // expected-note@-25 {{'init(a:b:d:e:f:g:h:)' declared here}} // Here b = false and g = nil, but we're checking that f doesn't get a default value let fooThing6 = Foo(a: 0, d: 1, e: 2, h: nil) // expected-error {{missing argument for parameter 'f' in call}} // expected-note@-29 {{'init(a:b:d:e:f:g:h:)' declared here}} // SR-11085 func sr_11085(x: Int) {} func sr_11085(line: String = #line) {} // expected-error {{default argument value of type 'Int' cannot be converted to type 'String'}} sr_11085() class SR_11085_C { init(line: String = #line) {} } // expected-error {{default argument value of type 'Int' cannot be converted to type 'String'}} let _ = SR_11085_C() // SR-11623 func badGenericMagicLiteral<T : ExpressibleByIntegerLiteral>(_ x: T = #function) -> T { x } // expected-error {{default argument value of type 'String' cannot be converted to type 'T'}} let _: Int = badGenericMagicLiteral() func genericMagicLiteral<T : ExpressibleByIntegerLiteral>(_ x: T = #line) -> T { x } // expected-note {{where 'T' = 'String'}} let _: Int = genericMagicLiteral() let _: String = genericMagicLiteral() // expected-error {{global function 'genericMagicLiteral' requires that 'String' conform to 'ExpressibleByIntegerLiteral'}}
apache-2.0
2f7a1f9214ab5e207e9ee21d99063ed6
36.177083
185
0.645979
3.256387
false
false
false
false
swift-lang/swift-t
stc/tests/315-avg-1.swift
4
897
import assert; import stats; main { float a[]; int b[]; // Launch sum first assertEqual(avg(a), 2.5, "avg_float"); assertEqual(avg(b), 2.5, "avg_integer"); assertLT(std(a) - 1.1180339887498949, 0.0000001, "std_float"); assertLT(std(b)- 1.1180339887498949, 0.0000001, "std_integer"); float m; float stdev; (m, stdev) = stats(a); assertEqual(m, avg(a), "m"); assertEqual(stdev, std(a), "std"); a[0] = 1.0; a[id(1)] = fid(2.0); a[5] = fid(3.0); a[id(242)] = 4.0; b[0] = id(1); b[id(1)] = 2; b[5] = id(3); b[id(242)] = 4; } (float r) fid (float x) { r = x; } (int r) id (int x) { r = id2(x, 10); } (int r) id2 (int x, int recursions) { if (recursions <= 0) { r = x; } else { r = id2(x, recursions - 1); } }
apache-2.0
35d7d2514ad6878ba5ea185a84bb7192
17.6875
62
0.45262
2.630499
false
false
false
false
mbuchetics/RealmDataSource
Carthage/Checkouts/realm-cocoa/RealmSwift-swift1.2/Results.swift
1
10872
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // 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 import Realm // MARK: MinMaxType /// Types which can be used for min()/max(). public protocol MinMaxType {} extension Double: MinMaxType {} extension Float: MinMaxType {} extension Int: MinMaxType {} extension Int8: MinMaxType {} extension Int16: MinMaxType {} extension Int32: MinMaxType {} extension Int64: MinMaxType {} extension NSDate: MinMaxType {} // MARK: AddableType /// Types which can be used for average()/sum(). public protocol AddableType {} extension Double: AddableType {} extension Float: AddableType {} extension Int: AddableType {} extension Int8: AddableType {} extension Int16: AddableType {} extension Int32: AddableType {} extension Int64: AddableType {} /// :nodoc: /// Internal class. Do not use directly. public class ResultsBase: NSObject, NSFastEnumeration { internal let rlmResults: RLMResults /// Returns a human-readable description of the objects contained in these results. public override var description: String { let type = "Results<\(rlmResults.objectClassName)>" return gsub("RLMResults <0x[a-z0-9]+>", type, rlmResults.description) ?? type } // MARK: Initializers internal init(_ rlmResults: RLMResults) { self.rlmResults = rlmResults } // MARK: Fast Enumeration public func countByEnumeratingWithState(state: UnsafeMutablePointer<NSFastEnumerationState>, objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>, count len: Int) -> Int { let enumeration: NSFastEnumeration = rlmResults // FIXME: no idea why this is needed, but doesn't compile otherwise return enumeration.countByEnumeratingWithState(state, objects: buffer, count: len) } } /** `Results` is an auto-updating container type in Realm returned from object queries. Results can be queried with the same predicates as `List<T>` and you can chain queries to further filter query results. Results cannot be created directly. */ public final class Results<T: Object>: ResultsBase { /// Element type contained in this collection. typealias Element = T // MARK: Properties /// Returns the Realm these results are associated with. /// Despite returning an `Optional<Realm>` in order to conform to /// `RealmCollectionType`, it will always return `.Some()` since a `Results` /// cannot exist independently from a `Realm`. public var realm: Realm? { return Realm(rlmResults.realm) } /// Returns the number of objects in these results. public var count: Int { return Int(rlmResults.count) } // MARK: Initializers internal override init(_ rlmResults: RLMResults) { super.init(rlmResults) } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the results. :param: object The object whose index is being queried. :returns: The index of the given object, or `nil` if the object is not in the results. */ public func indexOf(object: T) -> Int? { return notFoundToNil(rlmResults.indexOfObject(unsafeBitCast(object, RLMObject.self))) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. :param: predicate The predicate to filter the objects. :returns: The index of the first matching object, or `nil` if no objects match. */ public func indexOf(predicate: NSPredicate) -> Int? { return notFoundToNil(rlmResults.indexOfObjectWithPredicate(predicate)) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. :param: predicateFormat The predicate format string which can accept variable arguments. :returns: The index of the first matching object, or `nil` if no objects match. */ public func indexOf(predicateFormat: String, _ args: CVarArgType...) -> Int? { return notFoundToNil(rlmResults.indexOfObjectWithPredicate(NSPredicate(format: predicateFormat, arguments: getVaList(args)))) } // MARK: Object Retrieval /** Returns the object at the given `index`. :param: index The index. :returns: The object at the given `index`. */ public subscript(index: Int) -> T { get { throwForNegativeIndex(index) return unsafeBitCast(rlmResults[UInt(index)], T.self) } } /// Returns the first object in the results, or `nil` if empty. public var first: T? { return unsafeBitCast(rlmResults.firstObject(), Optional<T>.self) } /// Returns the last object in the results, or `nil` if empty. public var last: T? { return unsafeBitCast(rlmResults.lastObject(), Optional<T>.self) } // MARK: KVC /** Returns an Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. :param: key The name of the property. :returns: Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. */ public override func valueForKey(key: String) -> AnyObject? { return rlmResults.valueForKey(key) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified value and key. :warning: This method can only be called during a write transaction. :param: value The object value. :param: key The name of the property. */ public override func setValue(value: AnyObject?, forKey key: String) { return rlmResults.setValue(value, forKey: key) } // MARK: Filtering /** Filters the results to the objects that match the given predicate. :param: predicateFormat The predicate format string which can accept variable arguments. :returns: Results containing objects that match the given predicate. */ public func filter(predicateFormat: String, _ args: CVarArgType...) -> Results<T> { return Results<T>(rlmResults.objectsWithPredicate(NSPredicate(format: predicateFormat, arguments: getVaList(args)))) } /** Filters the results to the objects that match the given predicate. :param: predicate The predicate to filter the objects. :returns: Results containing objects that match the given predicate. */ public func filter(predicate: NSPredicate) -> Results<T> { return Results<T>(rlmResults.objectsWithPredicate(predicate)) } // MARK: Sorting /** Returns `Results` with elements sorted by the given property name. :param: property The property name to sort by. :param: ascending The direction to sort by. :returns: `Results` with elements sorted by the given property name. */ public func sorted(property: String, ascending: Bool = true) -> Results<T> { return sorted([SortDescriptor(property: property, ascending: ascending)]) } /** Returns `Results` with elements sorted by the given sort descriptors. :param: sortDescriptors `SortDescriptor`s to sort by. :returns: `Results` with elements sorted by the given sort descriptors. */ public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<T> { return Results<T>(rlmResults.sortedResultsUsingDescriptors(map(sortDescriptors) { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum value of the given property. :warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. :param: property The name of a property conforming to `MinMaxType` to look for a minimum on. :returns: The minimum value for the property amongst objects in the Results, or `nil` if the Results is empty. */ public func min<U: MinMaxType>(property: String) -> U? { return rlmResults.minOfProperty(property) as! U? } /** Returns the maximum value of the given property. :warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. :param: property The name of a property conforming to `MinMaxType` to look for a maximum on. :returns: The maximum value for the property amongst objects in the Results, or `nil` if the Results is empty. */ public func max<U: MinMaxType>(property: String) -> U? { return rlmResults.maxOfProperty(property) as! U? } /** Returns the sum of the given property for objects in the Results. :warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. :param: property The name of a property conforming to `AddableType` to calculate sum on. :returns: The sum of the given property over all objects in the Results. */ public func sum<U: AddableType>(property: String) -> U { return rlmResults.sumOfProperty(property) as AnyObject as! U } /** Returns the average of the given property for objects in the Results. :warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. :param: property The name of a property conforming to `AddableType` to calculate average on. :returns: The average of the given property over all objects in the Results, or `nil` if the Results is empty. */ public func average<U: AddableType>(property: String) -> U? { return rlmResults.averageOfProperty(property) as! U? } } extension Results: RealmCollectionType { // MARK: Sequence Support /// Returns a `GeneratorOf<T>` that yields successive elements in the results. public func generate() -> RLMGenerator<T> { return RLMGenerator(collection: rlmResults) } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by zero or more applications of successor(). public var endIndex: Int { return count } }
mit
c3acd93f0fc02b9e0be5905852a2d53e
34.298701
184
0.690857
4.735192
false
false
false
false
arvedviehweger/swift
test/IRGen/abi_v7k.swift
4
10512
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -primary-file %s -module-name test_v7k | %FileCheck %s // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -S -primary-file %s -module-name test_v7k | %FileCheck -check-prefix=V7K %s // REQUIRES: CPU=armv7k // REQUIRES: OS=watchos // CHECK-LABEL: define hidden swiftcc float @_T08test_v7k9addFloats{{.*}}(float, float) // CHECK: fadd float %0, %1 // CHECK ret float // V7K-LABEL: __T08test_v7k9addFloats{{.*}} // V7K: vadd.f32 s0, s0, s1 func addFloats(x: Float, y : Float) -> Float { return x+y } // CHECK-LABEL: define hidden swiftcc double @_T08test_v7k10addDoubles{{.*}}(double, double, double) // CHECK: fadd double %0, %1 // CHECK: fadd double // CHECK: ret double // V7K-LABEL: __T08test_v7k10addDoubles // V7K: vadd.f64 d0, d0, d1 // V7K: vadd.f64 d0, d0, d2 func addDoubles(x: Double, y: Double, z: Double) -> Double { return x+y+z } // CHECK-LABEL: define hidden swiftcc float @_T08test_v7k6addFDF{{.*}}(float, double, float) // CHECK: fmul float // CHECK: ret float // V7K-LABEL: __T08test_v7k6addFDF // V7K: vmul.f32 s0, s0, s1 // z is back-filled to s1 func addFDF(x: Float, y: Double, z: Float) -> Float { return x*z } // CHECK-LABEL: define hidden swiftcc double @_T08test_v7k8addStackS{{.*}}(double, double, double, double, double, double, double, float, double) // CHECK: fadd double // CHECK: ret double // V7K-LABEL: __T08test_v7k8addStackS // V7K: vldr d16, [sp] // V7K: vadd.f64 d0, d6, d16 // a is assigned to d6, c is passed via stack func addStack(d0: Double, d1: Double, d2: Double, d3: Double, d4: Double, d5: Double, a: Double, b: Float, c: Double) -> Double { return a+c } // CHECK-LABEL: define hidden swiftcc float @_T08test_v7k9addStack2{{.*}}(double, double, double, double, double, double, double, float, double, float) // CHECK: fadd float // V7K-LABEL: __T08test_v7k9addStack2 // V7K: vldr s0, [sp, #8] // V7K: vadd.f32 s0, s14, s0 // a is assigned to s14, b is via stack, c is via stack since it can't be back-filled to s15 func addStack2(d0: Double, d1: Double, d2: Double, d3: Double, d4: Double, d5: Double, d6: Double, a: Float, b: Double, c: Float) -> Float { return a+c } // Passing various enums: // CHECK-LABEL: define hidden swiftcc void @_T08test_v7k0A5Empty{{.*}}() // V7K-LABEL: __T08test_v7k0A5Empty enum Empty {} func testEmpty(x: Empty) -> Empty { return x } // CHECK-LABEL: define hidden swiftcc i32 @_T08test_v7k0A6Single{{.*}}() // CHECK: ret i32 1 // V7K-LABEL: __T08test_v7k0A6Single // V7K: movw r0, #1 enum SingleCase { case X } func testSingle(x: SingleCase) -> Int32{ switch x { case SingleCase.X: return 1 } } // CHECK-LABEL: define hidden swiftcc double @_T08test_v7k0A4Data{{.*}}(i32, double) // CHECK: ret double // V7K-LABEL: __T08test_v7k0A4Data // V7K: vstr d0 // V7K: vmov.f64 d0 enum DataCase { case Y(Int, Double) } func testData(x: DataCase) -> Double { switch x { case let .Y(i, d): return d } } // CHECK-LABEL: define hidden swiftcc i32 @_T08test_v7k0A6Clike2{{.*}}(i8) // CHECK: [[ID:%[0-9]+]] = phi i32 [ 2, {{.*}} ], [ 1, {{.*}} ] // CHECK: ret i32 [[ID]] // V7K-LABEL: __T08test_v7k0A6Clike2 // V7K: tst r0, #1 // V7K: movw r0, #1 // V7K: movw r0, #2 enum CLike2 { case A case B } func testClike2(x: CLike2) -> Int { switch x { case CLike2.A: return 1 case CLike2.B: return 2 } } // CHECK-LABEL: define hidden swiftcc i32 @_T08test_v7k0A6Clike8{{.*}}(i32, i8) // CHECK: [[ID:%[0-9]+]] = phi i32 [ -1, {{.*}} ], [ 1, {{.*}} ] // CHECK: ret i32 [[ID]] // V7K-LABEL: __T08test_v7k0A6Clike8 // V7K: sxtb r1, r1 // V7K: cmp r1, #0 // V7K: movw r0, #1 // V7K: mvn r0, #0 enum CLike8 { case A case B case C case D case E case F case G case H } func testClike8(t: Int, x: CLike8) -> Int { switch x { case CLike8.A: return 1 default: return -1 } } // layout of the enum: the tag bit is set for the no-data cases, which are then // assigned values in the data area of the enum in declaration order // CHECK-LABEL: define hidden swiftcc double @_T08test_v7k0A7SingleP{{.*}}(i32, i32, i8) // CHECK: br i1 // CHECK: switch i32 [[ID:%[0-9]+]] // CHECK: [[FIRST:%[0-9]+]] = zext i32 %0 to i64 // CHECK: [[SECOND:%[0-9]+]] = zext i32 %1 to i64 // CHECK: [[TEMP:%[0-9]+]] = shl i64 [[SECOND]], 32 // CHECK: [[RESULT:%[0-9]+]] = or i64 [[FIRST]], [[TEMP]] // CHECK: bitcast i64 [[RESULT]] to double // CHECK: phi double [ 0.000000e+00, {{.*}} ] // V7K-LABEL: __T08test_v7k0A7SingleP // V7K: tst r2, #1 // V7K: vmov.f64 d0 enum SinglePayload { case Paragraph case Char(Double) case Chapter } func testSingleP(x: SinglePayload) -> Double { switch x { case let .Char(d): return d default: return 0.0 } } // CHECK-LABEL: define hidden swiftcc double @_T08test_v7k0A6MultiP{{.*}}(i32, i32, i8) // CHECK: [[FIRST:%[0-9]+]] = zext i32 %0 to i64 // CHECK: [[SECOND:%[0-9]+]] = zext i32 %1 to i64 // CHECK: [[TEMP:%[0-9]+]] = shl i64 [[SECOND]], 32 // CHECK: [[RESULT:%[0-9]+]] = or i64 [[FIRST]], [[TEMP]] // CHECK: bitcast i64 [[RESULT]] to double // CHECK: sitofp i32 {{.*}} to double // CHECK: phi double [ 0.000000e+00, {{.*}} ] // CHECK: ret double // V7K-LABEL: __T08test_v7k0A6MultiP // V7K: vldr d0 // Backend will assign r0, r1 and r2 for input parameters and d0 for return values. class Bignum {} enum MultiPayload { case X(Int) case Y(Double) case Z(Bignum) } func testMultiP(x: MultiPayload) -> Double { switch x { case let .X(i): return Double(i) case let .Y(d): return d default: return 0.0 } } // CHECK-LABEL: define hidden swiftcc float @_T08test_v7k0A3Opt{{.*}}(i32, i8) // CHECK: entry: // CHECK: [[TR:%.*]] = trunc i8 %1 // CHECK: br i1 [[TR]], {{.*}}, label %[[PAYLOADLABEL:.*]] // CHECK: <label>:[[PAYLOADLABEL]] // CHECK: [[ID:%[0-9]+]] = bitcast i32 %0 to float // CHECK: ret float // V7K-LABEL: __T08test_v7k0A3Opt // V7K: tst r1, #1 // V7K: str r0, [r7, #-4] // V7K: ldr r0, [r7, #-4] // V7K: vmov s0, r0 // V7K: mov sp, r7 // V7K: pop {r7, pc} func testOpt(x: Float?) -> Float { return x! } // Returning tuple: (Int, Int) // CHECK-LABEL: define hidden swiftcc { i32, i32 } @_T08test_v7k6minMaxS{{.*}}(i32, i32) // V7K-LABEL: __T08test_v7k6minMaxS // V7K: ldr r0 // V7K: ldr r1 func minMax(x : Int, y : Int) -> (min: Int, max: Int) { var currentMin = x var currentMax = y if y < x { currentMin = y currentMax = x } return (currentMin, currentMax) } // Returning struct: Double x 4; Int8, Double, Double; struct MyRect { var x : Double var y : Double var w : Double var h : Double } struct MyPoint { var x: Double var y: Double } struct MySize { var w: Double var h: Double } struct MyRect2 { var t: Int8 var p : MyPoint init() { t = 1 p = MyPoint(x : 0.0, y: 0.0) } } struct MyRect4 { var t: Int8 var p : MyPoint var s: MySize init() { t = 1 p = MyPoint(x : 0.0, y: 0.0) s = MySize(w: 1.0, h: 2.0) } } // CHECK-LABEL: define hidden swiftcc { double, double, double, double } @_T08test_v7k0A4Ret2{{.*}}(double, i32) // V7K-LABEL: __T08test_v7k0A4Ret2 // double in d0, i32 in r0, return in d0,...,d3 // V7K: vmov [[ID:s[0-9]+]], r0 // V7K: vcvt.f64.s32 [[ID2:d[0-9]+]], [[ID]] // V7K: vstr d0, [sp] // V7K: vmov.f64 d0, [[ID2]] // V7K: bl // V7K: vldr [[ID3:d[0-9]+]], [sp] // V7K: vmov.f64 d2, [[ID3]] func testRet2(w : Double, i : Int) -> MyRect { var r = MyRect(x : Double(i), y : 2.0, w : 3.0, h : 4.0) r.w = w return r } // CHECK-LABEL: define hidden swiftcc { i8, double, double } @_T08test_v7k0A4Ret3{{.*}}() // V7K-LABEL: __T08test_v7k0A4Ret3 func testRet3() -> MyRect2 { var r = MyRect2() return r } // Returning tuple?: (Int x 6)? // CHECK-LABEL: define hidden swiftcc void @_T08test_v7k7minMax2{{.*}}({{%TSi.*}} noalias nocapture sret, i32, i32) // V7K-LABEL: __T08test_v7k7minMax2 // We will indirectly return an optional with the address in r0, input parameters will be in r1 and r2 // V7K: cmp r1, r2 // V7K: str r0, [sp, [[IDX:#[0-9]+]]] // V7K: ldr [[R0_RELOAD:r[0-9]+]], [sp, [[IDX]]] // V7K: str {{.*}}, [{{.*}}[[R0_RELOAD]]] // V7K: str {{.*}}, [{{.*}}[[R0_RELOAD]], #4] // V7K: str {{.*}}, [{{.*}}[[R0_RELOAD]], #8] // V7K: str {{.*}}, [{{.*}}[[R0_RELOAD]], #12] // V7K: str {{.*}}, [{{.*}}[[R0_RELOAD]], #16] // V7K: str {{.*}}, [{{.*}}[[R0_RELOAD]], #20] // V7K: and {{.*}}, {{.*}}, #1 // V7K: strb {{.*}}, [{{.*}}[[R0_RELOAD]], #24] func minMax2(x : Int, y : Int) -> (min: Int, max: Int, min2: Int, max2: Int, min3: Int, max3: Int)? { if x == y { return nil } var currentMin = x var currentMax = y if y < x { currentMin = y currentMax = x } return (currentMin, currentMax, currentMin, currentMax, currentMin, currentMax) } // Returning struct?: {Int x 6}? // CHECK-LABEL: define hidden swiftcc void @_T08test_v7k7minMax3{{.*}}({{%T.*}} noalias nocapture sret, i32, i32) // V7K-LABEL: __T08test_v7k7minMax3 struct Ret { var min:Int var max:Int var min2, max2 : Int var min3, max3 : Int } func minMax3(x : Int, y : Int) -> Ret? { if x == y { return nil } var currentMin = x var currentMax = y if y < x { currentMin = y currentMax = x } var r = Ret(min:currentMin, max:currentMax, min2:currentMin, max2:currentMax, min3:currentMin, max3:currentMax) return r } // Passing struct: Int8, MyPoint x 10, MySize * 10 // CHECK-LABEL: define hidden swiftcc double @_T08test_v7k0A4Ret5{{.*}}(%T8test_v7k7MyRect3V* noalias nocapture dereferenceable(328)) // V7K-LABEL: __T08test_v7k0A4Ret5 // V7K: ldrb [[TMP1:r[0-9]+]], [r0] // V7K: vldr [[REG1:d[0-9]+]], [r0, #8] // V7K: vldr [[REG2:d[0-9]+]], [r0] // V7K: sxtb r0, [[TMP1]] // V7K: vmov [[TMP2:s[0-9]+]], r0 // V7K: vcvt.f64.s32 [[INTPART:d[0-9]+]], [[TMP2]] // V7K: vadd.f64 [[TMP3:d[0-9]+]], [[INTPART]], [[REG1]] // V7K: vadd.f64 d0, [[TMP3]], [[REG2]] struct MyRect3 { var t: Int8 var p: MyPoint var p2: MyPoint var s: MySize var s2: MySize var p3: MyPoint var p4: MyPoint var s3: MySize var s4: MySize var p5: MyPoint var p6: MyPoint var s5: MySize var s6: MySize var p7: MyPoint var p8: MyPoint var s7: MySize var s8: MySize var p9: MyPoint var p10: MyPoint var s9: MySize var s10: MySize } func testRet5(r: MyRect3) -> Double { return Double(r.t) + r.p.x + r.s9.w }
apache-2.0
524b86f927f84294b8a2ed1088d050b4
27.182306
151
0.601693
2.612975
false
true
false
false
mightydeveloper/swift
test/Driver/Dependencies/bindings-build-record.swift
9
3919
// rdar://problem/21515673 // REQUIRES: OS=macosx // RUN: rm -rf %t && cp -r %S/Inputs/bindings-build-record/ %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | FileCheck %s -check-prefix=MUST-EXEC // MUST-EXEC-NOT: warning // MUST-EXEC: inputs: ["./main.swift"], output: {{[{].*[}]}}, condition: run-without-cascading // MUST-EXEC: inputs: ["./other.swift"], output: {{[{].*[}]}}, condition: run-without-cascading // MUST-EXEC: inputs: ["./yet-another.swift"], output: {{[{].*[}]}}, condition: run-without-cascading // RUN: echo '{version: "'$(%swiftc_driver_plain -version | head -n1)'", inputs: {"./main.swift": [443865900, 0], "./other.swift": [443865900, 0], "./yet-another.swift": [443865900, 0]}, build_time: [443865901, 0]}' > %t/main~buildrecord.swiftdeps // RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | FileCheck %s -check-prefix=NO-EXEC // NO-EXEC: inputs: ["./main.swift"], output: {{[{].*[}]}}, condition: check-dependencies // NO-EXEC: inputs: ["./other.swift"], output: {{[{].*[}]}}, condition: check-dependencies // NO-EXEC: inputs: ["./yet-another.swift"], output: {{[{].*[}]}}, condition: check-dependencies // RUN: echo '{version: "'$(%swiftc_driver_plain -version | head -n1)'", inputs: {"./main.swift": [443865900, 0], "./other.swift": !private [443865900, 0], "./yet-another.swift": !dirty [443865900, 0]}, build_time: [443865901, 0]}' > %t/main~buildrecord.swiftdeps // RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | FileCheck %s -check-prefix=BUILD-RECORD // BUILD-RECORD: inputs: ["./main.swift"], output: {{[{].*[}]}}, condition: check-dependencies{{$}} // BUILD-RECORD: inputs: ["./other.swift"], output: {{[{].*[}]}}, condition: run-without-cascading{{$}} // BUILD-RECORD: inputs: ["./yet-another.swift"], output: {{[{].*[}]$}} // RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift ./added.swift -incremental -output-file-map %t/output.json 2>&1 > %t/added.txt // RUN: FileCheck %s -check-prefix=BUILD-RECORD < %t/added.txt // RUN: FileCheck %s -check-prefix=FILE-ADDED < %t/added.txt // FILE-ADDED: inputs: ["./added.swift"], output: {{[{].*[}]}}, condition: newly-added{{$}} // RUN: touch -t 201401240006 %t/main.swift // RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | FileCheck %s -check-prefix=BUILD-RECORD-PLUS-CHANGE // BUILD-RECORD-PLUS-CHANGE: inputs: ["./main.swift"], output: {{[{].*[}]}}, condition: run-without-cascading // BUILD-RECORD-PLUS-CHANGE: inputs: ["./other.swift"], output: {{[{].*[}]}}, condition: run-without-cascading{{$}} // BUILD-RECORD-PLUS-CHANGE: inputs: ["./yet-another.swift"], output: {{[{].*[}]$}} // RUN: touch -t 201401240005 %t/main.swift // RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift -incremental -output-file-map %t/output.json 2>&1 | FileCheck %s -check-prefix=FILE-REMOVED // FILE-REMOVED: inputs: ["./main.swift"], output: {{[{].*[}]}}, condition: run-without-cascading // FILE-REMOVED: inputs: ["./other.swift"], output: {{[{].*[}]}}, condition: run-without-cascading // FILE-REMOVED-NOT: yet-another.swift // RUN: echo '{version: "bogus", inputs: {"./main.swift": [443865900, 0], "./other.swift": !private [443865900, 0], "./yet-another.swift": !dirty [443865900, 0]}}' > %t/main~buildrecord.swiftdeps // RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | FileCheck %s -check-prefix=MUST-EXEC
apache-2.0
cd3e749e8e8d0b8cfe7b901cefbb37d9
78.979592
263
0.652207
3.443761
false
false
false
false
Eonil/Editor
Editor4/PlatformService.swift
1
4293
// // PlatformService.swift // Editor4 // // Created by Hoon H. on 2016/05/25. // Copyright © 2016 Eonil. All rights reserved. // import Dispatch import BoltsSwift import AppKit enum PlatformCommand { case CreateDirectoryWithIntermediateDirectories(NSURL) case CreateDataFileWithIntermediateDirectories(NSURL) case DeleteFileSubtrees([NSURL]) case OpenFileInFinder([NSURL]) case StoreWorkspace(WorkspaceState) case RestoreWorkspace(WorkspaceID, location: NSURL) case RenameFile(from: NSURL, to: NSURL) } enum PlatformNotification { @available(*,deprecated=0) case ReloadWorkspace(WorkspaceID, WorkspaceState) } enum PlatformError: ErrorType { case BadURLs([NSURL]) case MissingWorkspaceLocation case UTF8EncodingFailure case BadFileListFileContent } /// Provides a platform invoke service. /// /// - Note: /// Take care that some platform features need to be called from main-thread only. /// final class PlatformService: DriverAccessible { private let gcdq = dispatch_queue_create("\(PlatformService.self)", DISPATCH_QUEUE_SERIAL) func dispatch(command: PlatformCommand) -> Task<()> { return Task(()).continueWithTask(Executor.Queue(gcdq)) { [weak self] (task: Task<()>) throws -> Task<()> in guard let S = self else { return Task.cancelledTask() } return try S.step(command) } } private func step(command: PlatformCommand) throws -> Task<()> { switch command { case .CreateDirectoryWithIntermediateDirectories(let u): assert(u.fileURL) try NSFileManager.defaultManager().createDirectoryAtURL(u, withIntermediateDirectories: true, attributes: nil) return Task(()) case .CreateDataFileWithIntermediateDirectories(let u): assert(u.fileURL) try NSData().writeToURL(u, options: NSDataWritingOptions.DataWritingWithoutOverwriting) return Task(()) case .DeleteFileSubtrees(let us): assert(us.map { $0.fileURL }.reduce(true, combine: { $0 && $1 })) us.forEach { u in // Eat-up errors. let _ = try? NSFileManager.defaultManager().removeItemAtURL(u) } return Task(()) case .OpenFileInFinder(let urls): NSWorkspace.sharedWorkspace().activateFileViewerSelectingURLs(urls) // This method is safe to be called from any thread. return Task(()) case .StoreWorkspace(let workspaceState): guard let u = workspaceState.getFileListURL() else { throw PlatformError.MissingWorkspaceLocation } var bs = [UInt8]() debugLog(Array(try WorkspaceSerializationUtility.serialize(workspaceState))) try WorkspaceSerializationUtility.serialize(workspaceState).forEach({ bs.appendContentsOf($0.utf8) }) try bs.withUnsafeMutableBufferPointer({ (inout p: UnsafeMutableBufferPointer<UInt8>) -> () in let d = (p.count == 0) ? NSData() : NSData(bytesNoCopy: p.baseAddress, length: p.count, freeWhenDone: false) try d.writeToURL(u, options: NSDataWritingOptions.DataWritingAtomic) }) return Task(()) case .RestoreWorkspace(let workspaceID, let location): var tempWorkspaceState = WorkspaceState() tempWorkspaceState.location = location guard let u = tempWorkspaceState.getFileListURL() else { throw PlatformError.MissingWorkspaceLocation } let d = try NSData(contentsOfURL: u, options: []) guard let s = (NSString(data: d, encoding: NSUTF8StringEncoding) as String?) else { throw PlatformError.BadFileListFileContent } var newWorkspaceState = try WorkspaceSerializationUtility.deserialize(s) newWorkspaceState.location = location return driver.operation.reloadWorkspace(workspaceID, workspaceState: newWorkspaceState) case .RenameFile(let from, let to): try NSFileManager.defaultManager().moveItemAtURL(from, toURL: to) return Task(()) } } } private extension WorkspaceState { func getFileListURL() -> NSURL? { return location?.URLByAppendingPathComponent("Workspace.FileList") } }
mit
c21a67da3c7dc7de9f7d611b8504b568
35.067227
140
0.667987
4.844244
false
false
false
false
objcio/issue-14-xpc
Superfamous Images/ImageSet.swift
1
1796
// // ImageSet.swift // Superfamous Images // // Created by Daniel Eggert on 21/06/2014. // Copyright (c) 2014 objc.io. All rights reserved. // import Cocoa @objc protocol ImageSetChangeObserver { func imageSetDidChange(set: ImageSet) -> Void } class ImageSet : NSObject { weak var changeObserver: ImageSetChangeObserver! = nil var images: [NSImage!] = [] { didSet { self.changeObserver.imageSetDidChange(self) } } let imageLoader = ImageLoader() init(changeObserver observer: ImageSetChangeObserver) { changeObserver = observer } func startLoadingImages() { for urlString in self.imageURLs { let url = NSURL(string: urlString) self.imageLoader.retrieveImageAtURL(url) { image in dispatch_async(dispatch_get_main_queue()) { var i = self.images i.append(image) self.images = i } } } } // http://superfamous.com // Photographs are available under a CC Attribution 3.0 license. let imageURLs: [String] = [ "http://payload203.cargocollective.com/1/8/282864/6367350/DSC_0058_900.JPG", "http://payload175.cargocollective.com/1/8/282864/5815632/9042399407_bf04388aca_o_900.jpg", "http://payload88.cargocollective.com/1/8/282864/4071568/DSC_0817_900.jpg", "http://payload175.cargocollective.com/1/8/282864/5804803/DSC_0294_900.jpg", "http://payload175.cargocollective.com/1/8/282864/5815628/DSC_0631_1_900.jpg", "http://payload93.cargocollective.com/1/8/282864/4164574/DSC_0476%20copycrop_900.jpg", "http://payload116.cargocollective.com/1/8/282864/4631161/DSC_0624_900.jpg", ] }
mit
e3d34890c73e6c082b8c31b0b69866c1
29.965517
99
0.623608
3.718427
false
false
false
false
nerdishbynature/octokit.swift
Tests/OctoKitTests/GistTests.swift
1
7459
import Foundation import OctoKit import XCTest class GistTests: XCTestCase { // MARK: Actual Request tests func testGetMyGists() { let config = TokenConfiguration("user:12345") let headers = Helper.makeAuthHeader(username: "user", password: "12345") let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/gists?page=1&per_page=100", expectedHTTPMethod: "GET", expectedHTTPHeaders: headers, jsonFile: "gists", statusCode: 200) let task = Octokit(config).myGists(session) { response in switch response { case let .success(gists): XCTAssertEqual(gists.count, 1) case let .failure(error): XCTAssertNil(error) } } XCTAssertNotNil(task) XCTAssertTrue(session.wasCalled) } #if compiler(>=5.5.2) && canImport(_Concurrency) @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) func testGetMyGistsAsync() async throws { let config = TokenConfiguration("user:12345") let headers = Helper.makeAuthHeader(username: "user", password: "12345") let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/gists?page=1&per_page=100", expectedHTTPMethod: "GET", expectedHTTPHeaders: headers, jsonFile: "gists", statusCode: 200) let gists = try await Octokit(config).myGists(session) XCTAssertEqual(gists.count, 1) XCTAssertTrue(session.wasCalled) } #endif func testGetGists() { let config = TokenConfiguration("user:12345") let headers = Helper.makeAuthHeader(username: "user", password: "12345") let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/users/vincode-io/gists?page=1&per_page=100", expectedHTTPMethod: "GET", expectedHTTPHeaders: headers, jsonFile: "gists", statusCode: 200) let task = Octokit(config).gists(session, owner: "vincode-io") { response in switch response { case let .success(gists): XCTAssertEqual(gists.count, 1) case let .failure(error): XCTAssertNil(error) } } XCTAssertNotNil(task) XCTAssertTrue(session.wasCalled) } #if compiler(>=5.5.2) && canImport(_Concurrency) @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) func testGetGistsAsync() async throws { let config = TokenConfiguration("user:12345") let headers = Helper.makeAuthHeader(username: "user", password: "12345") let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/users/vincode-io/gists?page=1&per_page=100", expectedHTTPMethod: "GET", expectedHTTPHeaders: headers, jsonFile: "gists", statusCode: 200) let gists = try await Octokit(config).gists(session, owner: "vincode-io") XCTAssertEqual(gists.count, 1) XCTAssertTrue(session.wasCalled) } #endif func testGetGist() { let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/gists/aa5a315d61ae9438b18d", expectedHTTPMethod: "GET", jsonFile: "gist", statusCode: 200) let task = Octokit().gist(session, id: "aa5a315d61ae9438b18d") { response in switch response { case let .success(gist): XCTAssertEqual(gist.id, "aa5a315d61ae9438b18d") case .failure: XCTFail("should not get an error") } } XCTAssertNotNil(task) XCTAssertTrue(session.wasCalled) } #if compiler(>=5.5.2) && canImport(_Concurrency) @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) func testGetGistAsync() async throws { let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/gists/aa5a315d61ae9438b18d", expectedHTTPMethod: "GET", jsonFile: "gist", statusCode: 200) let gist = try await Octokit().gist(session, id: "aa5a315d61ae9438b18d") XCTAssertEqual(gist.id, "aa5a315d61ae9438b18d") XCTAssertTrue(session.wasCalled) } #endif func testPostGist() { let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/gists", expectedHTTPMethod: "POST", jsonFile: "gist", statusCode: 200) let task = Octokit().postGistFile(session, description: "Test Post", filename: "Hello-World.swift", fileContent: "Sample Program", publicAccess: true) { response in switch response { case let .success(gist): XCTAssertEqual(gist.id, "aa5a315d61ae9438b18d") case .failure: XCTFail("should not get an error") } } XCTAssertNotNil(task) XCTAssertTrue(session.wasCalled) } #if compiler(>=5.5.2) && canImport(_Concurrency) @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) func testPostGistAsync() async throws { let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/gists", expectedHTTPMethod: "POST", jsonFile: "gist", statusCode: 200) do { let gist = try await Octokit().postGistFile(session, description: "Test Post", filename: "Hello-World.swift", fileContent: "Sample Program", publicAccess: true) XCTAssertEqual(gist.id, "aa5a315d61ae9438b18d") XCTAssertTrue(session.wasCalled) } catch { XCTFail(error.localizedDescription) } } #endif func testPatchGist() { let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/gists/aa5a315d61ae9438b18d", expectedHTTPMethod: "POST", jsonFile: "gist", statusCode: 200) let task = Octokit().patchGistFile(session, id: "aa5a315d61ae9438b18d", description: "Test Post", filename: "Hello-World.swift", fileContent: "Sample Program") { response in switch response { case let .success(gist): XCTAssertEqual(gist.id, "aa5a315d61ae9438b18d") case .failure: XCTFail("should not get an error") } } XCTAssertNotNil(task) XCTAssertTrue(session.wasCalled) } #if compiler(>=5.5.2) && canImport(_Concurrency) @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) func testPatchGistAsync() async throws { let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/gists/aa5a315d61ae9438b18d", expectedHTTPMethod: "POST", jsonFile: "gist", statusCode: 200) let gist = try await Octokit().patchGistFile(session, id: "aa5a315d61ae9438b18d", description: "Test Post", filename: "Hello-World.swift", fileContent: "Sample Program") XCTAssertEqual(gist.id, "aa5a315d61ae9438b18d") XCTAssertTrue(session.wasCalled) } #endif }
mit
647dae7ff302a687aa90e24765928684
45.61875
181
0.588417
4.498794
false
true
false
false
lovemo/MVVMFramework-Swift
SwiftMVVMKitDemo/SwiftMVVMKitDemo/Classes/Src/firstExample/Controller/FirstVC.swift
1
1716
// // FirstVC.swift // SwiftMVVMKitDemo // // Created by yuantao on 16/3/7. // Copyright © 2016年 momo. All rights reserved. // import UIKit import MJRefresh let MyCellIdentifier = "BQCell" // `cellIdentifier` AND `NibName` HAS TO BE SAME ! class FirstVC: UIViewController { @IBOutlet weak var table: UITableView! lazy var viewModel = BQViewModel() override func viewDidLoad() { super.viewDidLoad() setupTableView() } /** tableView的一些初始化工作 */ func setupTableView() { table.separatorStyle = .None // 下拉刷新 table.mj_header = MJRefreshNormalHeader { [weak self] () -> Void in if let strongSelf = self { strongSelf.viewModel.smk_viewModelWithGetDataSuccessHandler({ (array) -> () in strongSelf.table.reloadData() }) // 结束刷新 self!.table.mj_header.endRefreshing() } } table.mj_header.automaticallyChangeAlpha = true table.tableHander = SMKBaseTableViewManger(cellIdentifiers: [MyCellIdentifier], didSelectBlock: { (_, _) -> Void in let vc = UIViewController.viewControllerWithStoryboardName("Main", vcIdentifier: "SecondVCID") self.navigationController?.pushViewController(vc, animated: true) }) viewModel.smk_viewModelWithGetDataSuccessHandler { (array) -> () in self.table.tableHander .getItemsWithModelArray({ () -> [AnyObject] in return array }, completion: { () -> () in self.table.reloadData() }) } } }
mit
37cff36228ad5eb0a2958bcc6cbd9602
29.017857
123
0.579417
4.789174
false
false
false
false
Boss-XP/ChatToolBar
BXPChatToolBar/BXPChatToolBar/Classes/BXPChat/BXPChatToolBar/Other/BXPEditableButton.swift
1
1075
// // BXPEditableButton.swift // BXPChatToolBar // // Created by Boos-XP on 17/2/25. // Copyright © 2017年 Boos-XP. All rights reserved. // import UIKit class BXPEditableButton: UIButton { var buttonInputView: UIView? { willSet(newButtonInputView) { self.textView.inputView = newButtonInputView } didSet { } } let viewx = UIView() override var canBecomeFocused: Bool { return true } override var canBecomeFirstResponder: Bool { return true } override var canResignFirstResponder: Bool { return true } override func becomeFirstResponder() -> Bool { return textView.becomeFirstResponder() } override func resignFirstResponder() -> Bool { return textView.resignFirstResponder() } lazy var textView: UITextView = { let tempTextView = UITextView(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) tempTextView.isHidden = true self.addSubview(tempTextView) return tempTextView }() }
apache-2.0
3d170e779278bd0d0e658e13fb38998d
20.36
85
0.624532
4.564103
false
false
false
false
austinzheng/swift
test/SILGen/access_marker_gen.swift
12
6121
// RUN: %target-swift-emit-silgen -module-name access_marker_gen -parse-as-library -Xllvm -sil-full-demangle -enforce-exclusivity=checked %s | %FileCheck %s func modify<T>(_ x: inout T) {} public struct S { var i: Int var o: AnyObject? } // CHECK-LABEL: sil hidden [noinline] [ossa] @$s17access_marker_gen5initSyAA1SVyXlSgF : $@convention(thin) (@guaranteed Optional<AnyObject>) -> @owned S { // CHECK: bb0(%0 : @guaranteed $Optional<AnyObject>): // CHECK: [[BOX:%.*]] = alloc_box ${ var S }, var, name "s" // CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [var] [[BOX]] : ${ var S } // CHECK: [[ADDR:%.*]] = project_box [[MARKED_BOX]] : ${ var S }, 0 // CHECK: cond_br %{{.*}}, bb1, bb2 // CHECK: bb1: // CHECK: [[ACCESS1:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S // CHECK: assign %{{.*}} to [[ACCESS1]] : $*S // CHECK: end_access [[ACCESS1]] : $*S // CHECK: bb2: // CHECK: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S // CHECK: assign %{{.*}} to [[ACCESS2]] : $*S // CHECK: end_access [[ACCESS2]] : $*S // CHECK: bb3: // CHECK: [[ACCESS3:%.*]] = begin_access [read] [unknown] [[ADDR]] : $*S // CHECK: [[RET:%.*]] = load [copy] [[ACCESS3]] : $*S // CHECK: end_access [[ACCESS3]] : $*S // CHECK: return [[RET]] : $S // CHECK-LABEL: } // end sil function '$s17access_marker_gen5initSyAA1SVyXlSgF' @inline(never) func initS(_ o: AnyObject?) -> S { var s: S if o == nil { s = S(i: 0, o: nil) } else { s = S(i: 1, o: o) } return s } @inline(never) func takeS(_ s: S) {} // CHECK-LABEL: sil [ossa] @$s17access_marker_gen14modifyAndReadSyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: %[[BOX:.*]] = alloc_box ${ var S }, var, name "s" // CHECK: %[[ADDRS:.*]] = project_box %[[BOX]] : ${ var S }, 0 // CHECK: %[[ACCESS1:.*]] = begin_access [modify] [unknown] %[[ADDRS]] : $*S // CHECK: %[[ADDRI:.*]] = struct_element_addr %[[ACCESS1]] : $*S, #S.i // CHECK: assign %{{.*}} to %[[ADDRI]] : $*Int // CHECK: end_access %[[ACCESS1]] : $*S // CHECK: %[[ACCESS2:.*]] = begin_access [read] [unknown] %[[ADDRS]] : $*S // CHECK: %{{.*}} = load [copy] %[[ACCESS2]] : $*S // CHECK: end_access %[[ACCESS2]] : $*S // CHECK-LABEL: } // end sil function '$s17access_marker_gen14modifyAndReadSyyF' public func modifyAndReadS() { var s = initS(nil) s.i = 42 takeS(s) } var global = S(i: 0, o: nil) func readGlobal() -> AnyObject? { return global.o } // CHECK-LABEL: sil hidden [ossa] @$s17access_marker_gen10readGlobalyXlSgyF // CHECK: [[ADDRESSOR:%.*]] = function_ref @$s17access_marker_gen6globalAA1SVvau : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]() // CHECK-NEXT: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*S // CHECK-NEXT: [[T2:%.*]] = begin_access [read] [dynamic] [[T1]] // CHECK-NEXT: [[T3:%.*]] = struct_element_addr [[T2]] : $*S, #S.o // CHECK-NEXT: [[T4:%.*]] = load [copy] [[T3]] // CHECK-NEXT: end_access [[T2]] // CHECK-NEXT: return [[T4]] public struct HasTwoStoredProperties { var f: Int = 7 var g: Int = 9 // CHECK-LABEL: sil hidden [ossa] @$s17access_marker_gen22HasTwoStoredPropertiesV027noOverlapOnAssignFromPropToM0yyF : $@convention(method) (@inout HasTwoStoredProperties) -> () // CHECK: [[ACCESS1:%.*]] = begin_access [read] [unknown] [[SELF_ADDR:%.*]] : $*HasTwoStoredProperties // CHECK-NEXT: [[G_ADDR:%.*]] = struct_element_addr [[ACCESS1]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.g // CHECK-NEXT: [[G_VAL:%.*]] = load [trivial] [[G_ADDR]] : $*Int // CHECK-NEXT: end_access [[ACCESS1]] : $*HasTwoStoredProperties // CHECK-NEXT: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*HasTwoStoredProperties // CHECK-NEXT: [[F_ADDR:%.*]] = struct_element_addr [[ACCESS2]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.f // CHECK-NEXT: assign [[G_VAL]] to [[F_ADDR]] : $*Int // CHECK-NEXT: end_access [[ACCESS2]] : $*HasTwoStoredProperties mutating func noOverlapOnAssignFromPropToProp() { f = g } } class C { final var x: Int = 0 let z: Int = 0 } func testClassInstanceProperties(c: C) { let y = c.x c.x = y } // CHECK-LABEL: sil hidden [ossa] @$s17access_marker_gen27testClassInstanceProperties1cyAA1CC_tF : // CHECK: bb0([[C:%.*]] : @guaranteed $C // CHECK-NEXT: debug_value // CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[CX]] : $*Int // CHECK-NEXT: [[Y:%.*]] = load [trivial] [[ACCESS]] // CHECK-NEXT: end_access [[ACCESS]] // CHECK-NEXT: debug_value // CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[CX]] : $*Int // CHECK-NEXT: assign [[Y]] to [[ACCESS]] // CHECK-NEXT: end_access [[ACCESS]] func testClassLetProperty(c: C) -> Int { return c.z } // CHECK-LABEL: sil hidden [ossa] @$s17access_marker_gen20testClassLetProperty1cSiAA1CC_tF : $@convention(thin) (@guaranteed C) -> Int { // CHECK: bb0(%0 : @guaranteed $C): // CHECK: [[ADR:%.*]] = ref_element_addr %{{.*}} : $C, #C.z // CHECK-NOT: begin_access // CHECK: %{{.*}} = load [trivial] [[ADR]] : $*Int // CHECK-NOT: end_access // CHECK-NOT: destroy_value %0 : $C // CHECK: return %{{.*}} : $Int // CHECK-LABEL: } // end sil function '$s17access_marker_gen20testClassLetProperty1cSiAA1CC_tF' class D { var x: Int = 0 } // modify // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17access_marker_gen1DC1xSivM // CHECK: [[T0:%.*]] = ref_element_addr %0 : $D, #D.x // CHECK-NEXT: [[T1:%.*]] = begin_access [modify] [dynamic] [[T0]] : $*Int // CHECK: yield [[T1]] : $*Int // CHECK: end_access [[T1]] : $*Int // CHECK: end_access [[T1]] : $*Int func testDispatchedClassInstanceProperty(d: D) { modify(&d.x) } // CHECK-LABEL: sil hidden [ossa] @$s17access_marker_gen35testDispatchedClassInstanceProperty1dyAA1DC_tF // CHECK: bb0([[D:%.*]] : @guaranteed $D // CHECK: [[METHOD:%.*]] = class_method [[D]] : $D, #D.x!modify.1 // CHECK: begin_apply [[METHOD]]([[D]]) // CHECK-NOT: begin_access // CHECK: end_apply
apache-2.0
172f15fe23cff47a818be64bd2e28c1e
38.490323
177
0.594674
3.006385
false
false
false
false
kingloveyy/SwiftBlog
SwiftBlog/SwiftBlog/Classes/BusinessModel/AccessToken.swift
1
2261
// // AccessToken.swift // SwiftBlog // // Created by King on 15/3/19. // Copyright (c) 2015年 king. All rights reserved. // import UIKit class AccessToken: NSObject,NSCoding { /// 用于调用access_token,接口获取授权后的access token。 var access_token: String? /// access_token的生命周期,单位是秒数。 var expires_in: NSNumber? { didSet { expiresDate = NSDate(timeIntervalSinceNow: expires_in!.doubleValue) // println("过期日期 \(expiresDate)") } } /// token过期日期 var expiresDate: NSDate? /// 是否过期 var isExpired: Bool { return expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending } /// access_token的生命周期(该参数即将废弃,开发者请使用expires_in)。 var remind_in: NSNumber? /// 当前授权用户的UID var uid : Int = 0 init(dict: NSDictionary) { super.init() self.setValuesForKeysWithDictionary(dict as [NSObject : AnyObject]) } /// 将数据保存到沙盒 func saveAccessToken() { NSKeyedArchiver.archiveRootObject(self, toFile: AccessToken.tokenPath()) } /// 从沙盒读取 token 数据 func loadAccessToken() -> AccessToken? { return NSKeyedUnarchiver.unarchiveObjectWithFile(AccessToken.tokenPath()) as? AccessToken } /// 返回保存在沙盒的路径 class func tokenPath() -> String { var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).last as! String path = path.stringByAppendingPathComponent("token.plist") println(path) return path } // MARK: - 归档&接档 func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(access_token) aCoder.encodeObject(access_token) aCoder.encodeObject(expiresDate) aCoder.encodeInteger(uid, forKey: "uid") } required init(coder aDecoder: NSCoder) { access_token = aDecoder.decodeObject() as? String expiresDate = aDecoder.decodeObject() as? NSDate uid = aDecoder.decodeIntegerForKey("uid") } }
mit
fa53083da17a4b1d5e2ac18441e2f5a7
27.708333
157
0.641509
4.493478
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureActivity/Sources/FeatureActivityUI/Details/Custodial/InterestActivityDetailsPresenter.swift
1
8269
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import Combine import DIKit import Localization import MoneyKit import PlatformKit import PlatformUIKit import RxRelay import RxSwift import ToolKit final class InterestActivityDetailsPresenter: DetailsScreenPresenterAPI { // MARK: - Types private typealias BadgeItem = BadgeAsset.Value.Interaction.BadgeItem private typealias BadgeType = BadgeItem.BadgeType private typealias LocalizedString = LocalizationConstants.Activity.Details private typealias LocalizedLineItem = LocalizationConstants.LineItem.Transactional private typealias AccessibilityId = Accessibility.Identifier.Activity.Details // MARK: - DetailsScreenPresenterAPI let cells: [DetailsScreen.CellType] let titleViewRelay: BehaviorRelay<Screen.Style.TitleView> = .init(value: .none) let navigationBarAppearance: DetailsScreen.NavigationBarAppearance = .defaultDark let navigationBarLeadingButtonAction: DetailsScreen.BarButtonAction = .default let navigationBarTrailingButtonAction: DetailsScreen.BarButtonAction = .default let reloadRelay: PublishRelay<Void> = .init() // MARK: Private Properties (LabelContentPresenting) private let cryptoAmountLabelPresenter: LabelContentPresenting // MARK: Private Properties (Badge Model) private let badgesModel = MultiBadgeViewModel() private let statusBadge: DefaultBadgeAssetPresenter = .init() // MARK: Private Properties (LineItemCellPresenting) private let orderIDPresenter: LineItemCellPresenting private let dateCreatedPresenter: LineItemCellPresenting private let toPresenter: LineItemCellPresenting private let fromPresenter: LineItemCellPresenting // MARK: - Init init( event: InterestActivityItemEvent, analyticsRecorder: AnalyticsEventRecorderAPI = resolve(), blockchainAccountRepository: BlockchainAccountRepositoryAPI = resolve() ) { let title: String switch event.type { case .withdraw: title = LocalizedString.Title.withdrawal let from = event.cryptoCurrency.code + " \(LocalizedString.rewardsAccount)" fromPresenter = TransactionalLineItem.from(from).defaultPresenter( accessibilityIdPrefix: AccessibilityId.lineItemPrefix ) toPresenter = DefaultLineItemCellPresenter( interactor: DefaultLineItemCellInteractor( title: DefaultLabelContentInteractor( knownValue: LocalizationConstants.LineItem.Transactional.to ), description: AccountNameLabelContentInteractor( address: event.accountRef, currencyType: .crypto(event.cryptoCurrency) ) ), accessibilityIdPrefix: "" ) case .interestEarned: title = LocalizedString.Title.rewardsEarned let destination = event.cryptoCurrency.code + " \(LocalizedString.rewardsAccount)" fromPresenter = TransactionalLineItem.from(LocalizedString.companyName).defaultPresenter( accessibilityIdPrefix: AccessibilityId.lineItemPrefix ) toPresenter = TransactionalLineItem.to(destination).defaultPresenter( accessibilityIdPrefix: AccessibilityId.lineItemPrefix ) case .transfer: title = LocalizedString.Title.added + " \(event.cryptoCurrency.displayCode)" let crypto = event.cryptoCurrency let name = crypto.name let destination = event.cryptoCurrency.code + " \(LocalizedString.rewardsAccount)" toPresenter = TransactionalLineItem.to(destination).defaultPresenter( accessibilityIdPrefix: AccessibilityId.lineItemPrefix ) if event.isInternalTransfer { fromPresenter = TransactionalLineItem .from(name + " \(crypto.defaultTradingWalletName)") .defaultPresenter( accessibilityIdPrefix: AccessibilityId.lineItemPrefix ) } else { fromPresenter = TransactionalLineItem .from(name + " \(crypto.defaultWalletName)") .defaultPresenter( accessibilityIdPrefix: AccessibilityId.lineItemPrefix ) } case .unknown: unimplemented() } titleViewRelay.accept(.text(value: title)) cryptoAmountLabelPresenter = DefaultLabelContentPresenter( knownValue: event.value.displayString, descriptors: .h1(accessibilityIdPrefix: "") ) let statusDescription: String let badgeType: BadgeType switch event.state { case .complete: statusDescription = LocalizedString.completed badgeType = .verified case .manualReview: statusDescription = LocalizedString.manualReview badgeType = .default(accessibilitySuffix: statusDescription) case .pending, .cleared, .processing: statusDescription = LocalizedString.pending badgeType = .default(accessibilitySuffix: statusDescription) case .failed, .rejected: statusDescription = LocalizedString.failed badgeType = .destructive case .refunded, .unknown: unimplemented() } badgesModel.badgesRelay.accept([statusBadge]) statusBadge.interactor.stateRelay.accept( .loaded( next: .init( type: badgeType, description: statusDescription ) ) ) orderIDPresenter = TransactionalLineItem.orderId(event.identifier).defaultCopyablePresenter( analyticsRecorder: analyticsRecorder, accessibilityIdPrefix: AccessibilityId.lineItemPrefix ) let date = DateFormatter.elegantDateFormatter.string(from: event.insertedAt) dateCreatedPresenter = TransactionalLineItem.date(date).defaultPresenter( accessibilityIdPrefix: AccessibilityId.lineItemPrefix ) cells = [ .label(cryptoAmountLabelPresenter), .badges(badgesModel), .separator, .lineItem(orderIDPresenter), .separator, .lineItem(dateCreatedPresenter), .separator, .lineItem(toPresenter), .separator, .lineItem(fromPresenter) ] } } final class AccountNameLabelContentInteractor: LabelContentInteracting { typealias InteractionState = LabelContent.State.Interaction private lazy var setup: Void = fetchNameOfAccountWithReceiveAddress(address) .asObservable() .map { .loaded(next: .init(text: $0)) } .bindAndCatch(to: stateRelay) .disposed(by: disposeBag) let stateRelay = BehaviorRelay<InteractionState>(value: .loading) var state: Observable<InteractionState> { _ = setup return stateRelay.asObservable() } // MARK: - Private Properties private let blockchainAccountRepository: BlockchainAccountRepositoryAPI private let address: String private let currencyType: CurrencyType private let disposeBag = DisposeBag() init( blockchainAccountRepository: BlockchainAccountRepositoryAPI = resolve(), address: String, currencyType: CurrencyType ) { self.blockchainAccountRepository = blockchainAccountRepository self.address = address self.currencyType = currencyType } private func fetchNameOfAccountWithReceiveAddress( _ address: String ) -> AnyPublisher<String, Never> { blockchainAccountRepository .fetchAccountWithAddresss( address, currencyType: currencyType ) .map(\.label) .replaceError(with: "\(currencyType.code) " + LocalizationConstants.wallet) .eraseToAnyPublisher() } }
lgpl-3.0
c7c92848839a61b1887ba611c3b08795
36.076233
101
0.650943
6.35023
false
false
false
false
daaavid/TIY-Assignments
41-Show-'n-Tell/Extensions.playground/Contents.swift
1
6540
//: Playground - noun: a place where people can learn to do rad flips import UIKit extension String { mutating func pigLatin() { var characters = self.characters if characters.count > 0 { let firstChar = String(characters.first!) characters.removeFirst() if self.checkCase("lowercase") { self = String(characters) + firstChar + "ay" } else { self = String(characters) + firstChar + "AY" } } } mutating func decodePigLatin() { var characters = self.characters if characters.count > 0 { characters.removeLast() characters.removeLast() let firstChar = String(characters.first!) characters.removeFirst() let secondChar = String(characters.last!) characters.removeLast() self = secondChar + firstChar + String(characters) } } /* mutating func pigLatin() { let components = self.componentsSeparatedByString(" ") self = "" for var component in components { var characters = component.characters if characters.count > 0 { let firstChar = String(characters.first!).lowercaseString characters.removeFirst() var newFirstChar = String(characters.first!) characters.removeFirst() if components.indexOf(component) == 0 { newFirstChar = newFirstChar.uppercaseString } component = newFirstChar + String(characters) + firstChar + "ay" } self = self + component + " " } } mutating func decodePigLatin() { let components = self.componentsSeparatedByString(" ") self = "" for var component in components { if component.characters.count > 0 { var characters = component.characters characters.removeLast() characters.removeLast() let secondChar = String(characters.first!).lowercaseString characters.removeFirst() var firstChar = String(characters.last!) characters.removeLast() if components.indexOf(component) == 0 { firstChar = firstChar.uppercaseString } component = firstChar + secondChar + String(characters) } self = self + component + " " } } */ mutating func alternatingCaps() { let characters = self.characters self = "" var count = 1 for character in characters { if count % 2 == 0 { self = self + String(character).uppercaseString } else { self = self + String(character).lowercaseString } count++ } } func checkCase(var regex: String) -> Bool { switch regex { case "uppercase": regex = "[A-Z]+" case "lowercase": regex = "[a-z]+" default: regex = "" } let test = NSPredicate(format: "SELF MATCHES %@", regex) return test.evaluateWithObject(self) } func isPhoneNumber() -> Bool { let regex = "^\\(\\d{3}\\) \\d{3}-\\d{4}$" let test = NSPredicate(format: "SELF MATCHES %@", regex) return test.evaluateWithObject(self) } func isEmail() -> Bool { let regex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" let test = NSPredicate(format: "SELF MATCHES %@", regex) return test.evaluateWithObject(self) } func validate(var regex: String) -> Bool { switch regex { case "uppercase": regex = "[A-Z]+" case "lowercase": regex = "[a-z]+" case "phone": regex = "^\\(\\d{3}\\) \\d{3}-\\d{4}$" case "email": regex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" default: regex = "" } let test = NSPredicate(format: "SELF MATCHES %@", regex) return test.evaluateWithObject(self) } } var reference = "There is always money in the banana stand" var banana = "banana" banana.checkCase("lowercase") /*: Fancy Comment */ extension UIImageView { func downloadImgFrom(imageURL: String, contentMode: UIViewContentMode) { if let url = NSURL(string: imageURL) { var task: NSURLSessionDataTask! task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in if data != nil { dispatch_async(dispatch_get_main_queue(), { () -> Void in let image = UIImage(data: data!) self.image = image self.contentMode = contentMode task.cancel() }) } }) task.resume() } else { print("url \(imageURL) was invalid") } } } extension UIView { func appearWithFade(duration: Double) { self.alpha = 0 UIView.animateWithDuration(duration) { () -> Void in self.alpha = 1 } } func hideWithFade(duration: Double) { self.alpha = 1 UIView.animateWithDuration(duration) { () -> Void in self.alpha = 0 } } func slideHorizontally(duration: Double, fromPointX: CGFloat) { let originalX = self.frame.origin.x self.frame.origin.x += fromPointX UIView.animateWithDuration(duration) { () -> Void in self.frame.origin.x = originalX } } func slideVertically(duration: Double, fromPointY: CGFloat) { let originalY = self.frame.origin.y self.frame.origin.y += fromPointY UIView.animateWithDuration(duration) { () -> Void in self.frame.origin.y = originalY } } }
cc0-1.0
c26da230c55e477d471b66212ff940b6
26.711864
81
0.488226
5.11337
false
false
false
false
EugeneVegner/sws-copyleaks-sdk-test
PlagiarismChecker/Classes/CopyleaksConst.swift
1
2704
/* * The MIT License(MIT) * * Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com) * * 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 /* HTTP method definitions. */ public enum CopyleaksHTTPMethod: String { case GET, POST, PUT, DELETE } /* HTTP Content Type. */ public struct CopyleaksHTTPContentType { public static let JSON = "application/json" public static let URLEncoded = "application/x-www-form-urlencoded" public static let Multipart = "multipart/form-data" } public struct CopyleaksConst { /* Default Accept language */ public static let defaultAcceptLanguage: String = "en-US" /* Base api url */ public static let serviceHost: String = "api.copyleaks.com" /* Api version */ public static let serviceVersion: String = "v1" /* Datetime format*/ public static let dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"; public static let creationDateTimeFormat = "dd/MM/yyyy HH:mm:ss"; /* Content-Type header */ public static let contentTypeHeader:String = "Content-Type" /* Accept-Language header */ public static let acceptLanguageHeader:String = "Accept-Language" /* User-Agent header */ public static let userAgentHeader:String = "User-Agent" /* User-Agent value */ public static let userAgentValue: String = "CopyleaksSDK/1.0" /* Cache-Control header & value */ public static let cacheControlHeader: String = "Cache-Control" public static let cacheControlValue: String = "no-cache" /* Copyleaks Error domain */ public static let errorDomain: String = "com.copyleaks" }
mit
4d69c4f2495215aa025d3c5eafe2ca7f
33.666667
81
0.706731
4.340289
false
false
false
false
PiXeL16/SendToMe
SendToMeFramework/Data/KeysDataStorage.swift
1
2810
// // KeysDataStorage.swift // SendToMe // // Created by Christopher Jimenez on 4/19/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // /// Simple data storage using NSUserDefault to store the email value set public struct KeysDataStorage { /// Domain to be shared let defaults = NSUserDefaults.init(suiteName: "group.com.greenpixels.sendtome") public init(){} /// Storage keys private enum StorageKeys{ static let mailgunApiKey = "MailgunApiKey" static let clientDomainKey = "ClientDomainKey" } /** Gets the mailgun api key previously saved - returns: mailgun api key */ public func getMailgunApiKey() -> String{ var mailgunApiKey = "" if let mailgunApi = defaults?.stringForKey(StorageKeys.mailgunApiKey) { mailgunApiKey = mailgunApi } return mailgunApiKey } /** Saves the Mailgun Api key - parameter mailgunApi: mailgun APi key */ public func saveMailgunApiKey(mailgunApi:String){ defaults?.setValue(mailgunApi, forKey: StorageKeys.mailgunApiKey) defaults?.synchronize() print("Mailgun API saved") } /// Has an Mailun Api key saved public var hasMailgunApiKeySaved: Bool{ return !getMailgunApiKey().isEmpty } /** Clear the value of the email in the storage */ public func clearMailgunKey() { defaults?.removeObjectForKey(StorageKeys.mailgunApiKey) print("mailgun API cleared") } /** Gets the client domain key - returns: client domain key previously saved */ public func getClientDomain() -> String{ var clientDomain = "" if let domain = defaults?.stringForKey(StorageKeys.clientDomainKey) { clientDomain = domain } return clientDomain } /** Saves the client domain key - parameter clientDomain: client domain key */ public func saveClientDomainKey(clientDomain:String){ defaults?.setValue(clientDomain, forKey: StorageKeys.clientDomainKey) defaults?.synchronize() print("Client Domain API saved") } /// Variable to know if we have a domain client saved or not public var hasClientDomainSaved: Bool{ return !getClientDomain().isEmpty } /** Clear the value of the email in the storage */ public func clearClientDomain() { defaults?.removeObjectForKey(StorageKeys.mailgunApiKey) print("client domain API cleared") } }
mit
64e126928f52d2a8639a7add9dd624e6
22.408333
83
0.58811
5.340304
false
false
false
false
apple/swift
test/Interpreter/SDK/objc_swift_getObjectType.swift
4
1433
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation protocol P: class { } class AbstractP: P { } class DelegatedP<D: P>: AbstractP { init(_ d: D) { } } class AnyP: DelegatedP<AbstractP> { init<D: P>(_ d: D) { super.init(DelegatedP<D>(d)) } } extension P { var anyP: AnyP { return AnyP(self) } } // https://github.com/apple/swift/issues/46942 // Test several paths through 'swift_getObjectType()'. // instance of a Swift class that conforms to P class O: NSObject, P { } var o = O() let obase: NSObject = o print(NSStringFromClass(object_getClass(o)!)) _ = (o as P).anyP _ = (obase as! P).anyP // CHECK: {{^}}main.O{{$}} // ... and KVO's artificial subclass thereof o.addObserver(NSObject(), forKeyPath: "xxx", options: [.new], context: nil) print(NSStringFromClass(object_getClass(o)!)) _ = (o as P).anyP _ = (obase as! P).anyP // CHECK-NEXT: NSKVONotifying_main.O // instance of an ObjC class that conforms to P extension NSLock: P { } var l = NSLock() let lbase: NSObject = l print(NSStringFromClass(object_getClass(l)!)) _ = (l as P).anyP _ = (lbase as! P).anyP // CHECK-NEXT: NSLock // ... and KVO's artificial subclass thereof l.addObserver(NSObject(), forKeyPath: "xxx", options: [.new], context: nil) print(NSStringFromClass(object_getClass(l)!)) _ = (l as P).anyP _ = (lbase as! P).anyP // CHECK-NEXT: NSKVONotifying_NSLock
apache-2.0
1e5b288e2949f6e5b304e1c15bcdbf8f
22.883333
75
0.663643
3.068522
false
false
false
false
maricapp/CalculadoraCranio
CalculadoraCranio/CalculadoraCranio/MedidasCranio.swift
1
8282
// // MedidasCranio.swift // CalculadoraCranio // // Created by Usuário Convidado on 24/08/16. // Copyright © 2016 LLMM. All rights reserved. // import UIKit import FirebaseDatabase class CalcSingleton { static var medidasSuperior = [Float]() static var medidasAnterior = [Float]() static var medidasLateral = [Float]() static var medidasPosterior = [Float]() static var tudoDoExcel = TudoDoExcel() static var resultados = Resultados() static let sharedInstance = CalcSingleton() private init() { } class func buscar(){ tudoDoExcel = TudoDoExcel() let url = NSURL(string: "https://craniowebapi.herokuapp.com/api/obtertudo") let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in tudoDoExcel = self.parseJson(data!) print(tudoDoExcel) } //tudo.obterGenero() task.resume() } class func attribuirMedidasSuperior(valorDigitado: Float, areaNome: String) { tudoDoExcel.obterGeneroDaArea(valorDigitado, areaNome: areaNome, resultados: resultados) print("Valor \(medidasSuperior) atribuido para medidasSuperior em calculadora singleton ") print("") } class func attribuirMedidasAnterior(handler: [Float]) { medidasAnterior = handler print("Valor \(medidasAnterior) atribuido para medidasAnterior em calculadora singleton ") print("") } class func attribuirMedidasLateral(handler: [Float]) { medidasLateral = handler print("Valor \(medidasLateral) atribuido para medidasLateral em calculadora singleton ") print("") } class func attribuirMedidasPosterior(handler: [Float]) { medidasPosterior = handler print("Valor \(medidasPosterior) atribuido para medidasPosterior em calculadora singleton ") print("") } class func obterMediaSuperior() { } class func obterGenero() -> String { var generoApi:String = "" print("Aqui!!!!!") let conditionRef = FIRDatabase.database().reference().child("rangeFem").child("begin") conditionRef.observeEventType(.Value){(snap: FIRDataSnapshot) in print(snap.value?.description) } print("FIIIIM!!!!!") var genero:String = "" let sumSuperior = medidasSuperior.reduce(0, combine: +) print("Soma do array sumSuperior: \(sumSuperior)") print("") let sumAnterior = medidasAnterior.reduce(0, combine: +) print("Soma do array sumAnterior: \(sumAnterior)") print("") let sumLateral = medidasLateral.reduce(0, combine: +) print("Soma do array sumAnterior: \(sumLateral)") print("") let sumPosterior = medidasPosterior.reduce(0, combine: +) print("Soma do array sumPosterior: \(sumPosterior)") print("") let somaTotal = sumSuperior + sumAnterior + sumLateral + sumPosterior if somaTotal < 50 { genero = "-1" } else if somaTotal > 100 { genero = "M" } else { genero = "F" } print("Genero: \(genero)") print("") print("Soma: \(somaTotal)") print("") let mediaNova = resultados.calcularMedia() return mediaNova } class func parseJson(data: NSData) -> TudoDoExcel { let tudoDoExcel = TudoDoExcel() do { let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) if let resultado = json["resultado"] as? [[String: AnyObject]] { for medida in resultado { let linhaExcel = LinhaExcel() if let areaNome = medida["AreaNome"] as? String { linhaExcel.areaNome = areaNome //print(areaNome) } if let cutPointNome = medida["CutPointNome"] as? String { linhaExcel.cutPointNome = cutPointNome //print(cutPointNome) } if let operador = medida["Operador"] as? String { linhaExcel.operador = operador //print(operador) } if let cutPointValor = medida["CutPointValor"] as? Float { linhaExcel.cutPointValor = cutPointValor //print(cutPointValor) } if let feminino = medida["Feminino"] as? Float { linhaExcel.feminino = feminino //print(feminino) } if let masculino = medida["Masculino"] as? Float { linhaExcel.masculino = masculino //print(masculino) } if let ordenador = medida["Ordenador"] as? Int { linhaExcel.ordenador = ordenador //print(ordenador) } tudoDoExcel.adicionaLinhaExcel(linhaExcel) print("linhaExcel") print(linhaExcel) } print("********************medidaReferencia") //print(tudoDoExcel.linhas[1864].areaNome) //print(tudoDoExcel.linhas[1864].cutPointValor) //print(tudoDoExcel.linhas[1866].areaNome) //print(tudoDoExcel.linhas[1866].cutPointValor) //print(medidaReferencia.linhas[1866].cutPointValor) //print(medidaReferencia.linhas[1866].operador) } } catch { print("error serializing JSON: \(error)") } print("teste") return tudoDoExcel } } /* cada objeto dessa classe faz referencia a um registro da tabela Area_CutPointNome do banco */ class TudoDoExcel { //var areaNome:String = "" var linhas = [LinhaExcel]() func adicionaLinhaExcel(linha: LinhaExcel){ linhas.append(linha) } func obterGeneroDaArea(valorDigitado: Float, areaNome: String, resultados: Resultados){ //let results = linhas.lazy.filter { c in c.areaNome == areaNome && c.cutPointValor < valorDigitado } // or instead of "c in", you can use $0: //.map { ($0.someProperty, $0.otherProperty) } var fem:Float = 0 var masc:Float = 0 for linha in linhas { if (linha.areaNome == areaNome && linha.cutPointValor == valorDigitado) { fem = linha.feminino masc = linha.masculino } } resultados.addFem(fem) resultados.addMasc(masc) print("**************** fem ***********") print(fem) print("**************** masc ***********") print(masc) } //func setAreaNome(nome: String){ // areaNome = nome //} } class LinhaExcel { var areaNome:String = "" var cutPointNome:String = "" var operador:String = "" var cutPointValor:Float = 0.0 var feminino:Float = 0.0 var masculino:Float = 0.0 var ordenador:Int = 0 } class Resultados { var superiorFem = [Float]() var superiorMasc = [Float]() var femFinal = Float() var mascFinal = Float() func addFem (valor: Float){ superiorFem.append(valor) } func addMasc (valor: Float){ superiorMasc.append(valor) } func calcularMedia()-> String{ femFinal = superiorFem.reduce(0, combine: +) mascFinal = superiorMasc.reduce(0, combine: +) var genero: String if (femFinal > mascFinal){ genero = "F" } else if (mascFinal > femFinal){ genero = "M" } else { genero = "X" } return genero } }
apache-2.0
01f591ee9c68a786c51b797900155cb5
29.895522
109
0.528261
4.896511
false
false
false
false
hooman/swift
test/IDE/print_ast_tc_decls_errors.swift
4
13447
// Verify errors in this file to ensure that parse and type checker errors // occur where we expect them. // RUN: %target-typecheck-verify-swift -show-diagnostics-after-fatal // RUN: %target-swift-ide-test -print-ast-typechecked -source-filename %s -prefer-type-repr=false > %t.printed.txt // RUN: %FileCheck %s -strict-whitespace < %t.printed.txt // RUN: %FileCheck -check-prefix=NO-TYPEREPR %s -strict-whitespace < %t.printed.txt // RUN: %target-swift-ide-test -print-ast-typechecked -source-filename %s -prefer-type-repr=true > %t.printed.txt // RUN: %FileCheck %s -strict-whitespace < %t.printed.txt // RUN: %FileCheck -check-prefix=TYPEREPR %s -strict-whitespace < %t.printed.txt //===--- //===--- Helper types. //===--- class FooClass {} class BarClass {} protocol FooProtocol {} protocol BarProtocol {} protocol BazProtocol { func baz() } protocol QuxProtocol { associatedtype Qux } class FooProtocolImpl : FooProtocol {} class FooBarProtocolImpl : FooProtocol, BarProtocol {} class BazProtocolImpl : BazProtocol { func baz() {} } //===--- //===--- Import printing. //===--- import not_existent_module_a // expected-error{{no such module 'not_existent_module_a'}} // CHECK: {{^}}import not_existent_module_a{{$}} import not_existent_module_a.submodule // expected-error{{no such module}} // CHECK-NEXT: {{^}}import not_existent_module_a.submodule{{$}} @_exported import not_existent_module_b // expected-error{{no such module 'not_existent_module_b'}} // CHECK-NEXT: {{^}}@_exported import not_existent_module_b{{$}} @_exported import not_existent_module_b.submodule // expected-error{{no such module}} // CHECK-NEXT: {{^}}@_exported import not_existent_module_b.submodule{{$}} import struct not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}} // CHECK-NEXT: {{^}}import struct not_existent_module_c.foo{{$}} import class not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}} // CHECK-NEXT: {{^}}import class not_existent_module_c.foo{{$}} import enum not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}} // CHECK-NEXT: {{^}}import enum not_existent_module_c.foo{{$}} import protocol not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}} // CHECK-NEXT: {{^}}import protocol not_existent_module_c.foo{{$}} import var not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}} // CHECK-NEXT: {{^}}import var not_existent_module_c.foo{{$}} import func not_existent_module_c.foo // expected-error{{no such module 'not_existent_module_c'}} // CHECK-NEXT: {{^}}import func not_existent_module_c.foo{{$}} //===--- //===--- Inheritance list in structs. //===--- struct StructWithInheritance1 : FooNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} // NO-TYPEREPR: {{^}}struct StructWithInheritance1 : <<error type>> {{{$}} // TYPEREPR: {{^}}struct StructWithInheritance1 : FooNonExistentProtocol {{{$}} struct StructWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} expected-error {{cannot find type 'BarNonExistentProtocol' in scope}} // NO-TYPEREPR: {{^}}struct StructWithInheritance2 : <<error type>>, <<error type>> {{{$}} // TYPEREPR: {{^}}struct StructWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {{{$}} //===--- //===--- Inheritance list in classes. //===--- class ClassWithInheritance1 : FooNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} // NO-TYREPR: {{^}}class ClassWithInheritance1 : <<error type>> {{{$}} // TYREPR: {{^}}class ClassWithInheritance1 : FooNonExistentProtocol {{{$}} class ClassWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} expected-error {{cannot find type 'BarNonExistentProtocol' in scope}} // NO-TYREPR: {{^}}class ClassWithInheritance2 : <<error type>>, <<error type>> {{{$}} // TYREPR: {{^}}class ClassWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {{{$}} class ClassWithInheritance3 : FooClass, FooNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} // NO-TYREPR: {{^}}class ClassWithInheritance3 : FooClass, <<error type>> {{{$}} // TYREPR: {{^}}class ClassWithInheritance3 : FooClass, FooNonExistentProtocol {{{$}} class ClassWithInheritance4 : FooProtocol, FooClass {} // expected-error {{superclass 'FooClass' must appear first in the inheritance clause}} {{31-31=FooClass, }} {{42-52=}} // CHECK: {{^}}class ClassWithInheritance4 : FooProtocol, FooClass {{{$}} class ClassWithInheritance5 : FooProtocol, BarProtocol, FooClass {} // expected-error {{superclass 'FooClass' must appear first in the inheritance clause}} {{31-31=FooClass, }} {{55-65=}} // CHECK: {{^}}class ClassWithInheritance5 : FooProtocol, BarProtocol, FooClass {{{$}} class ClassWithInheritance6 : FooClass, BarClass {} // expected-error {{multiple inheritance from classes 'FooClass' and 'BarClass'}} // NO-TYREPR: {{^}}class ClassWithInheritance6 : FooClass, <<error type>> {{{$}} // TYREPR: {{^}}class ClassWithInheritance6 : FooClass, BarClass {{{$}} class ClassWithInheritance7 : FooClass, BarClass, FooProtocol {} // expected-error {{multiple inheritance from classes 'FooClass' and 'BarClass'}} // NO-TYREPR: {{^}}class ClassWithInheritance7 : FooClass, <<error type>>, FooProtocol {{{$}} // TYREPR: {{^}}class ClassWithInheritance7 : FooClass, BarClass, FooProtocol {{{$}} class ClassWithInheritance8 : FooClass, BarClass, FooProtocol, BarProtocol {} // expected-error {{multiple inheritance from classes 'FooClass' and 'BarClass'}} // NO-TYREPR: {{^}}class ClassWithInheritance8 : FooClass, <<error type>>, FooProtocol, BarProtocol {{{$}} // TYREPR: {{^}}class ClassWithInheritance8 : FooClass, BarClass, FooProtocol, BarProtocol {{{$}} class ClassWithInheritance9 : FooClass, BarClass, FooProtocol, BarProtocol, FooNonExistentProtocol {} // expected-error {{multiple inheritance from classes 'FooClass' and 'BarClass'}} expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} // NO-TYREPR: {{^}}class ClassWithInheritance9 : FooClass, <<error type>>, FooProtocol, BarProtocol, <<error type>> {{{$}} // TYREPR: {{^}}class ClassWithInheritance9 : FooClass, BarClass, FooProtocol, BarProtocol, FooNonExistentProtocol {{{$}} //===--- //===--- Inheritance list in enums. //===--- enum EnumWithInheritance1 : FooNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} expected-error {{an enum with no cases}} // NO-TYREPR: {{^}}enum EnumWithInheritance1 : <<error type>> {{{$}} // TYREPR: {{^}}enum EnumWithInheritance1 : FooNonExistentProtocol {{{$}} enum EnumWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} expected-error {{cannot find type 'BarNonExistentProtocol' in scope}} expected-error {{an enum with no cases}} // NO-TYREPR: {{^}}enum EnumWithInheritance2 : <<error type>>, <<error type>> {{{$}} // TYREPR: {{^}}enum EnumWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {{{$}} enum EnumWithInheritance3 : FooClass { case X } // expected-error {{raw type 'FooClass' is not expressible by a string, integer, or floating-point literal}} // expected-error@-1{{'EnumWithInheritance3' declares raw type 'FooClass', but does not conform to RawRepresentable and conformance could not be synthesized}} // expected-error@-2{{RawRepresentable conformance cannot be synthesized because raw type 'FooClass' is not Equatable}} // NO-TYREPR: {{^}}enum EnumWithInheritance3 : <<error type>> {{{$}} // TYREPR: {{^}}enum EnumWithInheritance3 : FooClass {{{$}} enum EnumWithInheritance4 : FooClass, FooProtocol { case X } // expected-error {{raw type 'FooClass' is not expressible by a string, integer, or floating-point literal}} // expected-error@-1{{'EnumWithInheritance4' declares raw type 'FooClass', but does not conform to RawRepresentable and conformance could not be synthesized}} // expected-error@-2{{RawRepresentable conformance cannot be synthesized because raw type 'FooClass' is not Equatable}} // NO-TYREPR: {{^}}enum EnumWithInheritance4 : <<error type>>, FooProtocol {{{$}} // TYREPR: {{^}}enum EnumWithInheritance4 : FooClass, FooProtocol {{{$}} enum EnumWithInheritance5 : FooClass, BarClass { case X } // expected-error {{raw type 'FooClass' is not expressible by a string, integer, or floating-point literal}} expected-error {{multiple enum raw types 'FooClass' and 'BarClass'}} // expected-error@-1{{'EnumWithInheritance5' declares raw type 'FooClass', but does not conform to RawRepresentable and conformance could not be synthesized}} // expected-error@-2{{RawRepresentable conformance cannot be synthesized because raw type 'FooClass' is not Equatable}} // NO-TYREPR: {{^}}enum EnumWithInheritance5 : <<error type>>, <<error type>> {{{$}} // TYREPR: {{^}}enum EnumWithInheritance5 : FooClass, BarClass {{{$}} //===--- //===--- Inheritance list in protocols. //===--- protocol ProtocolWithInheritance1 : FooNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} // NO-TYREPR: {{^}}protocol ProtocolWithInheritance1 : <<error type>> {{{$}} // TYREPR: {{^}}protocol ProtocolWithInheritance1 : FooNonExistentProtocol {{{$}} protocol ProtocolWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {} // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} expected-error {{cannot find type 'BarNonExistentProtocol' in scope}} // NO-TYREPR: {{^}}protocol ProtocolWithInheritance2 : <<error type>>, <<error type>> {{{$}} // TYREPR: {{^}}protocol ProtocolWithInheritance2 : FooNonExistentProtocol, BarNonExistentProtocol {{{$}} protocol ProtocolWithInheritance3 : FooClass {} // NO-TYREPR: {{^}}protocol ProtocolWithInheritance3 : FooClass {{{$}} // TYREPR: {{^}}protocol ProtocolWithInheritance3 : FooClass {{{$}} protocol ProtocolWithInheritance4 : FooClass, FooProtocol {} // NO-TYREPR: {{^}}protocol ProtocolWithInheritance4 : FooClass, FooProtocol {{{$}} // TYREPR: {{^}}protocol ProtocolWithInheritance4 : FooClass, FooProtocol {{{$}} protocol ProtocolWithInheritance5 : FooClass, BarClass {} // expected-error{{multiple inheritance from classes 'FooClass' and 'BarClass'}} expected-error{{type 'Self' cannot be a subclass of both 'BarClass' and 'FooClass'}} // expected-note{{constraint conflicts with 'Self' : 'FooClass'}} // NO-TYREPR: {{^}}protocol ProtocolWithInheritance5 : <<error type>>, <<error type>> {{{$}} // TYREPR: {{^}}protocol ProtocolWithInheritance5 : FooClass, BarClass {{{$}} //===--- //===--- Typealias printing. //===--- // Normal typealiases. typealias Typealias1 = FooNonExistentProtocol // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} // NO-TYREPR: {{^}}typealias Typealias1 = <<error type>>{{$}} // TYREPR: {{^}}typealias Typealias1 = FooNonExistentProtocol{{$}} // sr-197 func foo(bar: Typealias1<Int>) {} // Should not generate error "cannot specialize non-generic type '<<error type>>'" // Associated types. protocol AssociatedType1 { // CHECK-LABEL: AssociatedType1 { associatedtype AssociatedTypeDecl1 : FooProtocol = FooClass // CHECK: {{^}} associatedtype AssociatedTypeDecl1 : FooProtocol = FooClass{{$}} associatedtype AssociatedTypeDecl2 : BazProtocol = FooClass // CHECK: {{^}} associatedtype AssociatedTypeDecl2 : BazProtocol = FooClass{{$}} associatedtype AssociatedTypeDecl3 : FooNonExistentProtocol // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} // NO-TYREPR: {{^}} associatedtype AssociatedTypeDecl3 : <<error type>>{{$}} // TYREPR: {{^}} associatedtype AssociatedTypeDecl3 : FooNonExistentProtocol{{$}} associatedtype AssociatedTypeDecl4 : FooNonExistentProtocol, BarNonExistentProtocol // expected-error {{cannot find type 'FooNonExistentProtocol' in scope}} expected-error {{cannot find type 'BarNonExistentProtocol' in scope}} // NO-TYREPR: {{^}} associatedtype AssociatedTypeDecl4 : <<error type>>, <<error type>>{{$}} // TYREPR: {{^}} associatedtype AssociatedTypeDecl4 : FooNonExistentProtocol, BarNonExistentProtocol{{$}} associatedtype AssociatedTypeDecl5 : FooClass // CHECK: {{^}} associatedtype AssociatedTypeDecl5{{$}} } //===--- //===--- Variable declaration printing. //===--- var topLevelVar1 = 42 // CHECK: {{^}}var topLevelVar1: Int{{$}} // CHECK-NOT: topLevelVar1 // CHECK: class C1 class C1 { // CHECK: init(data: <<error type>>) init(data:) // expected-error {{expected parameter type following ':'}} } protocol IllegalExtension {} class OuterContext { // CHECK: class OuterContext { extension IllegalExtension { // expected-error {{declaration is only valid at file scope}} // CHECK: extension IllegalExtension { func protocolFunc() {} // CHECK: func protocolFunc() } } static func topLevelStaticFunc() {} // expected-error {{static methods may only be declared on a type}} // NO-TYPEPR: {{^}}func topLevelStaticFunc() -> <<error type>>{{$}} // TYPEPR: {{^}}func topLevelStaticFunc() {{$}} static var topLevelStaticVar = 42 // expected-error {{static properties may only be declared on a type}} // CHECK: {{^}}var topLevelStaticVar: Int{{$}}
apache-2.0
266b4e6d215340bf03ada4c245c6b3e1
57.97807
289
0.720161
4.799072
false
false
false
false
jeffreybergier/Hipstapaper
Hipstapaper/Packages/V3Style/Sources/V3Style/PropertyWrappers/Sidebar.swift
1
1897
// // Created by Jeffrey Bergier on 2022/06/17. // // MIT License // // Copyright (c) 2021 Jeffrey Bergier // // 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 SwiftUI import Umbrella @propertyWrapper public struct Sidebar: DynamicProperty { public struct Value { public var toolbar: some ActionStyle = ActionStyleDefault /// Fake appearance style for use on Labels where there is no "real" disabled state public var disabled: some ActionStyle = ActionStyleFakeDisabled public var destructive: some ActionStyle = ActionStyleImp(buttonRole: .destructive) public var titleText: some ViewModifier = SidebarListTitleText() public var itemCountOval: some ViewModifier = SidebarOval() } public init() {} public var wrappedValue: Value { Value() } }
mit
3d330f836e3fe153a49f06f55c179ab8
39.361702
91
0.723247
4.64951
false
false
false
false
ECLabs/CareerUp
CareerUp/Job.swift
1
168
class Job: NSObject { var objectId = "" var updatedAt:NSDate? var title = "" var experianceLevel = "" var details = "" var customer = "" }
mit
2442c019edd2a0e60228b0fadbe42722
17.666667
28
0.547619
4
false
false
false
false
dshamany/CIToolbox
CIToolbox/ProfileView.swift
1
5292
// // ProfileView.swift // CIToolbox // // Created by Daniel Shamany on 7/5/17. // Copyright © 2017 Daniel Shamany. All rights reserved. // import UIKit import Firebase class ProfileView: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var profilePicture: UIImageView! @IBOutlet weak var firstName: UITextField! @IBOutlet weak var lastName: UITextField! @IBOutlet weak var phoneNumber: UITextField! @IBOutlet weak var emailAddress: UITextField! @IBOutlet weak var bioTextView: UITextView! func setInterface(){ let fullName = Global.currentUser.UserName var fullNameArray = fullName?.components(separatedBy: " ") firstName.text = fullNameArray?[0] lastName.text = fullNameArray?[1] phoneNumber.text = Global.currentUser.Phone! emailAddress.text = Global.currentUser.Email! bioTextView.text = Global.currentUser.Bio! if (Global.currentUser.ImageURL != " "){ //fetchUserPhoto() } } override func viewDidLoad() { super.viewDidLoad() setInterface() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func formatPhoneNumber(input: String) -> String{ var res: [String] = [""] //Read numbers only for i in input.characters{ if (i == "0" || i == "1" || i == "2" || i == "3" || i == "4" || i == "5" || i == "6" || i == "7" || i == "8" || i == "9"){ res.append(String(i)) } } if input == "" { return "" } else if res.count < 11 { alertFunction(title: "Oops!", msg: "Phone number too short") return input } else if res.count > 11 { alertFunction(title: "Oops!", msg: "Phone number too long") return input } else { return res[1] + res[2] + res[3] + "-" + res[4] + res[5] + res[6] + "-" + res[7] + res[8] + res[9] + res[10] } } //MARK: PicketView Code func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return Global.districts.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return Global.districts[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { alertFunction(title: "Selected!", msg: "\(Global.districts[row])") } @IBAction func editProfilePicture(_ sender: Any) { let image = UIImagePickerController() image.delegate = self image.sourceType = UIImagePickerControllerSourceType.photoLibrary image.allowsEditing = true self.present(image, animated: true){ //code for post-completion } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { profilePicture.image = image } else { alertFunction(title: "Oops!", msg: "Something was wrong with the image") } self.dismiss(animated: true, completion: nil) } @IBAction func tapAnywhere(_ sender: Any){ self.view.endEditing(true) } @IBAction func cancelAction(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func saveAction(_ sender: Any) { let ref = Database.database().reference() let user = Auth.auth().currentUser Global.currentUser.UserName = firstName.text! + " " + lastName.text! Global.currentUser.Phone = phoneNumber.text! Global.currentUser.Email = user?.email! Global.currentUser.Bio = bioTextView.text! if (phoneNumber.text != ""){ Global.currentUser.Phone = formatPhoneNumber(input: phoneNumber.text!) } ref.child("Users").child("\(user?.uid ?? "Unknown User")").setValue(Global.currentUser.Post) self.dismiss(animated: true, completion: nil) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { switch(textField){ case firstName: lastName.becomeFirstResponder() break case lastName: phoneNumber.becomeFirstResponder() break case phoneNumber: if (!((phoneNumber.text?.isEmpty)!)){ phoneNumber.text = formatPhoneNumber(input: phoneNumber.text!) } emailAddress.becomeFirstResponder() break case emailAddress: self.view.endEditing(true) default: break } return true } }
gpl-3.0
34711dfe40cf9b9562a13df261a2416a
32.06875
148
0.58231
4.872007
false
false
false
false
shuoli84/RxSwift
RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift
2
2654
// // RxCollectionViewReactiveArrayDataSource.swift // RxCocoa // // Created by Krunoslav Zaher on 6/29/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit import RxSwift // objc monkey business class _RxCollectionViewReactiveArrayDataSource: NSObject, UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func _collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 0 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return _collectionView(collectionView, numberOfItemsInSection: section) } func _collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return rxAbstractMethod() } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return _collectionView(collectionView, cellForItemAtIndexPath: indexPath) } } // Please take a look at `DelegateProxyType.swift` class RxCollectionViewReactiveArrayDataSource<ElementType> : _RxCollectionViewReactiveArrayDataSource , RxCollectionViewDataSourceType { typealias Element = [ElementType] typealias CellFactory = (UICollectionView, Int, ElementType) -> UICollectionViewCell var itemModels: [ElementType]? = nil func modelAtIndex(index: Int) -> ElementType? { return itemModels?[index] } var cellFactory: CellFactory init(cellFactory: CellFactory) { self.cellFactory = cellFactory } // data source override func _collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return itemModels?.count ?? 0 } override func _collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return cellFactory(collectionView, indexPath.item, itemModels![indexPath.item]) } // reactive func collectionView(collectionView: UICollectionView, observedEvent: Event<Element>) { switch observedEvent { case .Next(let boxedNext): self.itemModels = boxedNext.value case .Error(let error): bindingErrorToInterface(error) case .Completed: break } collectionView.reloadData() } }
mit
ec8b9ea66d9035119abd6884fc67e6e4
32.1875
140
0.6948
6.259434
false
false
false
false
SergeMaslyakov/audio-player
app/src/controllers/music/cells/MusicSongTableViewCell.swift
1
2663
// // MusicSongTableViewCell.swift // AudioPlayer // // Created by Serge Maslyakov on 07/07/2017. // Copyright © 2017 Maslyakov. All rights reserved. // import UIKit import MediaPlayer import TableKit final class MusicSongTableViewCell: UITableViewCell, ConfigurableCell, DecoratableCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var albumImage: UIImageView! @IBOutlet weak var controlImage: UIImageView! static var estimatedHeight: CGFloat? { return ThemeHeightHelper.Songs.cellHeight } static var defaultHeight: CGFloat? { return ThemeHeightHelper.Songs.cellHeight } override func awakeFromNib() { super.awakeFromNib() decorate() } /// MARK: ConfigurableCell func configure(with item: SongCellData) { nameLabel.text = item.song.title descriptionLabel.text = trackDescription(fromItem: item.song) var defaultImage = true var image: UIImage? = item.defaultCoverImage let imageSize = CGSize(width: round(albumImage.bounds.size.width), height: round(albumImage.bounds.size.height)) // For best performance. Image rendering in the background thread DispatchQueue.global(qos: .userInitiated).async { if let artwork = item.song.artwork { defaultImage = false image = artwork.image(at: imageSize) } DispatchQueue.main.async { // see apple bug "https://stackoverflow.com/questions/7667631/mpmediaitemartwork-returning-wrong-sized-artwork" self.controlImage.image = item.controlImage self.albumImage.contentMode = defaultImage ? .center : .scaleToFill self.albumImage.image = image } } } /// MARK: Formatters func trackDescription(fromItem item: MPMediaItem) -> String { var description: String = "" if let artist = item.albumArtist { description = artist + " - " } description += formattedDuration(fromItem: item) return description } func formattedDuration(fromItem item: MPMediaItem) -> String { if item.playbackDuration < 3600 { return TimeFormatter.msFrom(seconds: Int(item.playbackDuration)) } else { return TimeFormatter.hmsFrom(seconds: Int(item.playbackDuration)) } } /// MARK: DecoratableCell func decorate() { nameLabel.textColor = UIColor.MusicSongCell.titleText descriptionLabel.textColor = UIColor.MusicSongCell.descriptionText } }
apache-2.0
80b67f97c87f559863032655930eb092
29.25
127
0.653644
4.957169
false
false
false
false
asurinsaka/swift_examples_2.1
Teslameter/Teslameter/TeslaGraphView.swift
1
3164
// // TeslaGraphView.swift // Teslameter // // Created by larryhou on 9/18/14. // Copyright (c) 2014 larryhou. All rights reserved. // import Foundation import UIKit import CoreLocation class TeslaGraphView:UIView { enum TeslaAxis:Int { case X case Y case Z } private let GRAPH_DENSITY = 100 private let TICK_NUM = 4 private var buffer:[[CLHeadingComponentValue]] = [] private var index:Int = 0 func insertHeadingTesla(#x:CLHeadingComponentValue, y:CLHeadingComponentValue, z:CLHeadingComponentValue) { if buffer.count < GRAPH_DENSITY { buffer.append([0.0,0.0,0.0]) } buffer[index][TeslaAxis.X.rawValue] = x buffer[index][TeslaAxis.Y.rawValue] = y buffer[index][TeslaAxis.Z.rawValue] = z index = (index + 1) % GRAPH_DENSITY setNeedsDisplay() } private func drawGraph(#bounds:CGRect, inContext context:CGContextRef) { CGContextSaveGState(context) CGContextBeginPath(context) let delta = bounds.height / CGFloat( 2 * TICK_NUM) for i in 1..<(2 * TICK_NUM) { CGContextMoveToPoint(context, 0.0, delta * CGFloat(i)) CGContextAddLineToPoint(context, bounds.width, delta * CGFloat(i)) } CGContextSetLineWidth(context, 0.5) CGContextSetGrayStrokeColor(context, 0.75, 1.0) CGContextStrokePath(context) CGContextBeginPath(context) CGContextMoveToPoint(context, 0, bounds.height / 2) CGContextAddLineToPoint(context, bounds.width, bounds.height / 2) CGContextSetLineWidth(context, 0.5) CGContextSetGrayStrokeColor(context, 0.0, 1.0) CGContextStrokePath(context) CGContextRestoreGState(context) } private func drawTeslaBuffer(#axis:Int, fromIndex index:Int, inContext context:CGContextRef) { CGContextSaveGState(context) CGContextBeginPath(context) for i in 0..<buffer.count { var iter = (index + i) % buffer.count var comp:CGFloat = CGFloat(buffer[iter][axis] / 128 * 8) if comp > 0 { comp = bounds.height / 2 - fmin(comp, CGFloat(TICK_NUM)) * bounds.height / 2 / CGFloat(TICK_NUM) } else { comp = bounds.height / 2 + fmin(fabs(comp), CGFloat(TICK_NUM)) * bounds.height / 2 / CGFloat(TICK_NUM) } if i == 0 { CGContextMoveToPoint(context, 0, comp) } else { CGContextAddLineToPoint(context, CGFloat(i) * bounds.width / CGFloat(GRAPH_DENSITY) , comp) } } CGContextSetLineWidth(context, 2.0) CGContextSetLineJoin(context, kCGLineJoinRound) switch TeslaAxis(rawValue: axis)! { case .X:CGContextSetRGBStrokeColor(context, 1.0, 0.0, 1.0, 1.0) case .Y:CGContextSetRGBStrokeColor(context, 0.0, 1.0, 0.0, 1.0) case .Z:CGContextSetRGBStrokeColor(context, 0.0, 0.0, 1.0, 1.0) } CGContextStrokePath(context) CGContextRestoreGState(context) } override func drawRect(rect: CGRect) { var context = UIGraphicsGetCurrentContext() var bounds = CGRectMake(0, 0, self.bounds.width, self.bounds.height) drawGraph(bounds: bounds, inContext: context) CGContextSetAllowsAntialiasing(context, false) for axis in 0..<3 { drawTeslaBuffer(axis: axis, fromIndex: index, inContext: context) } CGContextSetAllowsAntialiasing(context, true) } }
mit
4d8144295f1cac65e52622d155178450
23.346154
106
0.701327
3.258496
false
false
false
false
ChaselAn/ACTagView
ACTagViewDemo/ACTagView/ACTagViewOneLineLayout.swift
1
2535
// // ACTagViewOneLineLayout.swift // ACTagViewDemo // // Created by ac on 2017/7/30. // Copyright © 2017年 ac. All rights reserved. // import UIKit class ACTagViewOneLineLayout: ACTagViewFlowLayout { private var offsetX: CGFloat = 0 override var collectionViewContentSize: CGSize { guard let collectionView = collectionView else { return CGSize.zero } collectionView.layoutIfNeeded() collectionView.superview?.layoutIfNeeded() return CGSize(width: max(collectionView.bounds.width, offsetX), height: collectionView.bounds.height) } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let array = super.layoutAttributesForElements(in: rect), let collectionView = collectionView else { return nil } collectionView.layoutIfNeeded() collectionView.superview?.layoutIfNeeded() var finalAttrs: [UICollectionViewLayoutAttributes] = [] var offsetX = tagViewMargin.horizontal let offsetY = tagViewMargin.vertical for attribute in array { let attrCopy = attribute.copy() as! UICollectionViewLayoutAttributes attrCopy.frame.origin.x = offsetX attrCopy.frame.origin.y = offsetY if !collectionView.isScrollEnabled && offsetX + attribute.frame.width + tagViewMargin.horizontal > collectionView.bounds.width { self.offsetX = offsetX return finalAttrs } offsetX += tagMargin.horizontal + attribute.frame.width finalAttrs += [attrCopy] } if offsetX > tagViewMargin.horizontal { offsetX = offsetX - tagMargin.horizontal + tagViewMargin.horizontal } self.offsetX = offsetX return finalAttrs } override func getEstimatedSize(in tagView: ACTagView) -> CGSize { guard let dataSource = tagView.tagDataSource else { return CGSize.zero } tagView.layoutIfNeeded() tagView.superview?.layoutIfNeeded() var offsetX = tagViewMargin.horizontal for i in 0 ..< dataSource.numberOfTags(in: tagView) { let attribute = dataSource.tagView(tagView, tagAttributeForIndexAt: i) let width = attribute.getWidth(height: tagHeight) offsetX += tagMargin.horizontal + width } if offsetX > tagViewMargin.horizontal { offsetX = offsetX - tagMargin.horizontal + tagViewMargin.horizontal } return CGSize(width: offsetX, height: tagHeight + 2 * tagViewMargin.vertical) } }
mit
b7cc965c56d1be3de373e94430c89948
28.103448
134
0.687204
5.084337
false
false
false
false
MetalPetal/MetalPetal
MetalPetalExamples/Shared/SketchBoardView.swift
1
17485
// // SketchBoardView.swift // MetalPetalDemo // // Created by YuAo on 2021/4/6. // import Foundation import SwiftUI import MetalPetal struct SketchBoardView: View { enum BrushColor: Hashable { struct Color: Hashable { var r: Float var g: Float var b: Float var a: Float } case `static`(Color) case `dynamic` case eraser } class Renderer: ObservableObject { @Published var image: CGImage? @Published var brushColor: BrushColor = .dynamic @Published var brushSize: CGFloat = 10 { didSet { self.updateBrushImage() } } private var canvasSize: CGSize private let renderContext = try! MTIContext(device: MTLCreateSystemDefaultDevice()!) private let imageRenderer = PixelBufferPoolBackedImageRenderer() private var backgroundImage: MTIImage private var previousImageBuffer: MTIImage? private var previousPreviousLocation: CGPoint? private var previousLocation: CGPoint? private var brushImage: MTIImage! private var compositingFilter = MultilayerCompositingFilter() private let bitmapScale: CGFloat = { #if os(macOS) return NSScreen.main?.backingScaleFactor ?? 1.0 #elseif os(iOS) return UIScreen.main.nativeScale #endif }() private let backgroundColor: MTIColor = .white init() { let initialCanvasSize = CGSize(width: 1024, height: 1024) canvasSize = initialCanvasSize backgroundImage = MTIImage(color: backgroundColor, sRGB: false, size: initialCanvasSize) updateBrushImage() output(image: backgroundImage) } func updateCanvasSize(_ size: CGSize) { canvasSize = size * bitmapScale if let imageBuffer = previousImageBuffer, (canvasSize.width > backgroundImage.size.width || canvasSize.height > backgroundImage.size.height) { backgroundImage = MTIImage(color: backgroundColor, sRGB: false, size: CGSize(width: max(backgroundImage.size.width, canvasSize.width), height: max(backgroundImage.size.height, canvasSize.height))) let expandCanvasFilter = MultilayerCompositingFilter() expandCanvasFilter.inputBackgroundImage = backgroundImage expandCanvasFilter.layers = [MultilayerCompositingFilter.Layer(content: imageBuffer).frame(CGRect(x: 0, y: 0, width: imageBuffer.size.width, height: imageBuffer.size.height), layoutUnit: .pixel)] let outputImage = expandCanvasFilter.outputImage!.withCachePolicy(.persistent) output(image: outputImage) } else if let imageBuffer = previousImageBuffer { output(image: imageBuffer) } else { reset() } renderContext.reclaimResources() } private func updateBrushImage() { let pixelSize = brushSize * bitmapScale guard let context = CGContext(data: nil, width: Int(pixelSize) + 2, height: Int(pixelSize) + 2, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) else { fatalError() } context.setFillColor(CGColor(gray: 0, alpha: 1)) context.fillEllipse(in: CGRect(x: 1, y: 1, width: pixelSize, height: pixelSize)) let brushImage = MTIImage(cgImage: context.makeImage()!, isOpaque: false).premultiplyingAlpha().withCachePolicy(.persistent) self.brushImage = brushImage } func reset() { backgroundImage = MTIImage(color: backgroundColor, sRGB: false, size: canvasSize) previousImageBuffer = nil output(image: backgroundImage) } func startStoke(at location: CGPoint) { previousLocation = nil previousPreviousLocation = nil draw(at: location * bitmapScale) } func moveStroke(to location: CGPoint) { draw(at: location * bitmapScale) } private func draw(at point: CGPoint) { let background: MTIImage = previousImageBuffer ?? backgroundImage var brushLayers = [MultilayerCompositingFilter.Layer]() let previousPreviousLocation = self.previousPreviousLocation ?? point let previousLocation = self.previousLocation ?? point self.previousPreviousLocation = self.previousLocation self.previousLocation = point let mid1 = (previousLocation + previousPreviousLocation) * 0.5 let mid2 = (point + previousLocation) * 0.5 func quadBezierPoint(t: CGFloat, start: CGPoint, c1: CGPoint, end: CGPoint) -> CGPoint { let x = quadBezier(t: t, start: start.x, c1: c1.x, end: end.x) let y = quadBezier(t: t, start: start.y, c1: c1.y, end: end.y) return CGPoint(x: x, y: y) } func quadBezier(t: CGFloat, start: CGFloat, c1: CGFloat, end: CGFloat) -> CGFloat { let t_ = (1.0 - t) let tt_ = t_ * t_ let tt = t * t return start * tt_ + 2.0 * c1 * t_ * t + end * tt } let pl = SIMD2<Float>(Float(previousLocation.x), Float(previousLocation.y)) let cl = SIMD2<Float>(Float(point.x), Float(point.y)) let d = distance(pl, cl) if d > 1 { for i in 1..<Int(d) { let p = quadBezierPoint(t: CGFloat(i)/CGFloat(d), start: mid1, c1: previousLocation, end: mid2) let tintColor: MTIColor switch self.brushColor { case .dynamic: tintColor = MTIColor(red: Float(p.x)/Float(backgroundImage.size.width), green: Float(p.y)/Float(backgroundImage.size.height), blue: 1, alpha: 1) case .static(let color): tintColor = MTIColor(red: color.r, green: color.g, blue: color.b, alpha: color.a) case .eraser: tintColor = backgroundColor } var brushLayer = MultilayerCompositingFilter.Layer(content: brushImage) brushLayer.position = p brushLayer.opacity = 1 brushLayer.blendMode = .normal brushLayer.tintColor = tintColor brushLayers.append(brushLayer) } } else { let tintColor: MTIColor switch self.brushColor { case .dynamic: tintColor = MTIColor(red: Float(point.x)/Float(backgroundImage.size.width), green: Float(point.y)/Float(backgroundImage.size.height), blue: 1, alpha: 1) case .static(let color): tintColor = MTIColor(red: color.r, green: color.g, blue: color.b, alpha: color.a) case .eraser: tintColor = backgroundColor } var brushLayer = MultilayerCompositingFilter.Layer(content: brushImage) brushLayer.position = point brushLayer.opacity = 1 brushLayer.blendMode = .normal brushLayer.tintColor = tintColor brushLayers.append(brushLayer) } compositingFilter.inputBackgroundImage = background compositingFilter.layers = brushLayers let output = compositingFilter.outputImage!.withCachePolicy(.persistent) self.output(image: output) } private func output(image: MTIImage) { do { // Render the output image try renderContext.startTask(toRender: image, completion: nil) // Save the rendered buffer so we can use it in the next frame. previousImageBuffer = renderContext.renderedBuffer(for: image) //Crop the output let croppedImage = image.cropped(to: CGRect(origin: .zero, size: canvasSize))! self.image = try self.imageRenderer.render(croppedImage, using: renderContext).cgImage } catch { print(error) } } } @StateObject private var renderer = Renderer() var body: some View { ZStack { if let image = renderer.image { Image(cgImage: image).resizable() } TouchTrackingView(touchBeganHandler: { [renderer] point in renderer.startStoke(at: point) }, touchMovedHandler: { [renderer] point in renderer.moveStroke(to: point) }, boundsChangedHandler: { [renderer] bounds in renderer.updateCanvasSize(bounds.size) }).frame(maxWidth: .infinity, maxHeight: .infinity) VStack { Spacer() VStack(alignment: .leading, spacing: 12) { HStack { BrushColorButton($renderer.brushColor, color: .dynamic) BrushColorButton($renderer.brushColor, color: .static(BrushColor.Color(r: 1, g: 203/255.0, b: 0, a: 1))) BrushColorButton($renderer.brushColor, color: .static(BrushColor.Color(r: 0, g: 203/255.0, b: 71/255.0, a: 1))) BrushColorButton($renderer.brushColor, color: .static(BrushColor.Color(r: 0, g: 203/255.0, b: 1, a: 1))) BrushColorButton($renderer.brushColor, color: .static(BrushColor.Color(r: 1, g: 0, b: 79/255.0, a: 1))) BrushColorButton($renderer.brushColor, color: .static(BrushColor.Color(r: 0, g: 0, b: 0, a: 1))) BrushColorButton($renderer.brushColor, color: .eraser) } HStack { Group { Circle().frame(width: renderer.brushSize, height: renderer.brushSize).foregroundColor(Color.secondary.opacity(0.5)) }.frame(width: BrushColorButton.preferredSize, height: BrushColorButton.preferredSize) Slider(value: $renderer.brushSize, in: 6...BrushColorButton.preferredSize) .accentColor(Color.secondary.opacity(0.5)) } } .scaledToFit() .padding() .blurBackgroundEffect(cornerRadius: 16) .padding() } } .toolbar(content: { Button("Reset", action: { [renderer] in renderer.reset() }) }) .inlineNavigationBarTitle("Sketch Board") } struct BrushColorButton: View { static let preferredSize: CGFloat = 36 static let dynamicBrushIcon: CGImage = RGUVB1GradientImage.makeCGImage(size: CGSize(width: BrushColorButton.preferredSize * 2, height: BrushColorButton.preferredSize * 2)) private let value: Binding<BrushColor> private let color: BrushColor private let isSelected: Bool @State var isHovering: Bool = false init(_ value: Binding<BrushColor>, color: BrushColor) { self.value = value self.color = color self.isSelected = value.wrappedValue == color } var body: some View { Group { switch color { case .static(let c): Circle().foregroundColor(Color(Color.RGBColorSpace.sRGB, red: Double(c.r), green: Double(c.g), blue: Double(c.b), opacity: Double(c.a))) case .dynamic: Image(cgImage: BrushColorButton.dynamicBrushIcon).resizable() case .eraser: Image(systemName: "square.tophalf.fill").resizable().padding(10).background(Color(.sRGB, white: 1, opacity: 1)) } } .frame(width: BrushColorButton.preferredSize, height: BrushColorButton.preferredSize) .clipShape(Circle()) .shadow(color: Color.black.opacity((isSelected || isHovering) ? 0.25 : 0), radius: 4, x: 0, y: 2) .overlay(Circle().stroke(Color.white, lineWidth: isSelected ? 2 : 0)) .onTapGesture { [value, color] in value.wrappedValue = color } .onHover(perform: { [$isHovering] hovering in withAnimation { $isHovering.wrappedValue = hovering } }) } } } fileprivate extension CGSize { static func * (lhs: CGSize, rhs: CGFloat) -> CGSize { return CGSize(width: lhs.width * rhs, height: lhs.height * rhs) } } fileprivate extension CGPoint { static func * (lhs: CGPoint, rhs: CGFloat) -> CGPoint { return CGPoint(x: lhs.x * rhs, y: lhs.y * rhs) } } fileprivate extension CGPoint { static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } } #if os(iOS) fileprivate typealias ViewRepresentable = UIViewRepresentable #elseif os(macOS) fileprivate typealias ViewRepresentable = NSViewRepresentable #endif struct TouchTrackingView: ViewRepresentable { #if os(iOS) class TouchTrackingNativeView: UIView { var touchBeginHandler: TouchHandler? var touchMovedHandler: TouchHandler? var boundsChangedHandler: BoundsChangeHandler? override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { touchBeginHandler?(touches.randomElement()!.location(in: self)) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { touchMovedHandler?(touches.randomElement()!.location(in: self)) } private var previousBounds: CGRect? override func layoutSubviews() { super.layoutSubviews() if previousBounds != bounds { previousBounds = bounds boundsChangedHandler?(bounds) } } } #elseif os(macOS) class TouchTrackingNativeView: NSView { var touchBeginHandler: TouchHandler? var touchMovedHandler: TouchHandler? var boundsChangedHandler: BoundsChangeHandler? private var isMouseUp: Bool = true override func mouseDown(with event: NSEvent) { var location = convert(event.locationInWindow, from: nil) location.y = bounds.height - location.y if isMouseUp { isMouseUp = false touchBeginHandler?(location) } } override func mouseDragged(with event: NSEvent) { var location = convert(event.locationInWindow, from: nil) location.y = bounds.height - location.y touchMovedHandler?(location) } override func mouseUp(with event: NSEvent) { isMouseUp = true } private var previousBounds: CGRect? override func layout() { super.layout() if previousBounds != bounds { previousBounds = bounds boundsChangedHandler?(bounds) } } } #endif typealias TouchHandler = (CGPoint) -> Void typealias BoundsChangeHandler = (CGRect) -> Void private let touchBeginHandler: TouchHandler private let touchMovedHandler: TouchHandler private let boundsChangedHandler: BoundsChangeHandler init(touchBeganHandler: @escaping TouchHandler, touchMovedHandler: @escaping TouchHandler, boundsChangedHandler: @escaping BoundsChangeHandler) { self.touchBeginHandler = touchBeganHandler self.touchMovedHandler = touchMovedHandler self.boundsChangedHandler = boundsChangedHandler } func makeUIView(context: Context) -> TouchTrackingNativeView { let view = TouchTrackingNativeView(frame: .zero) view.touchBeginHandler = self.touchBeginHandler view.touchMovedHandler = self.touchMovedHandler view.boundsChangedHandler = self.boundsChangedHandler return view } func updateUIView(_ uiView: TouchTrackingNativeView, context: Context) { } func makeNSView(context: Context) -> TouchTrackingNativeView { makeUIView(context: context) } func updateNSView(_ nsView: TouchTrackingNativeView, context: Context) { updateUIView(nsView, context: context) } } struct SketchBoardView_Previews: PreviewProvider { static var previews: some View { SketchBoardView() } }
mit
43da504f6899f4e9e4ca0e32d9589e02
39.852804
289
0.566772
5.261812
false
false
false
false
johnnyclem/intro-to-ios
Playgrounds/SwiftOperators.playground/section-26.swift
2
167
1 == 1 2 != 1 var firstObj = "test1" var secondObj = "test1" firstObj == secondObj // Same Value. So true //firstObj === secondObj // Different instances. So false
mit
fc1271ba7d8d268118e1de675fe31aea
17.555556
57
0.664671
3.27451
false
true
false
false
aipeople/PokeIV
Pods/PGoApi/PGoApi/Classes/Unknown6/subFuncI.swift
1
34302
// // subFuncA.swift // Pods // // Created by PokemonGoSucks on 2016-08-10 // // import Foundation public class subFuncI { public func subFuncI(input_: Array<UInt32>) -> Array<UInt32> { var v = Array<UInt32>(count: 469, repeatedValue: 0) var input = input_ v[0] = input[18] v[1] = (input[10] & ~v[0]) let part0 = ((input[97] ^ (input[10] & ~input[195]))) let part1 = (((input[2] & ~part0) ^ input[18])) let part2 = (((input[79] ^ v[0]) | input[56])) let part3 = ((input[81] ^ part2)) v[2] = (((((input[173] ^ input[86]) ^ input[10]) ^ input[45]) ^ (part3 & ~input[125])) ^ (part1 & ~input[56])) v[3] = ~input[56] v[4] = (v[2] & ~input[182]) let part4 = ((input[97] ^ (input[10] & ~input[195]))) let part5 = (((input[2] & ~part4) ^ input[18])) let part6 = (((input[79] ^ v[0]) | input[56])) let part7 = ((input[81] ^ part6)) v[5] = (((((input[173] ^ input[86]) ^ input[10]) ^ input[45]) ^ (part7 & ~input[125])) ^ (part5 & v[3])) v[6] = input[157] v[7] = input[193] v[8] = input[2] let part8 = (((v[2] & ~input[7]) ^ input[180])) v[9] = ((((v[2] & ~input[4]) ^ input[99]) ^ (input[37] & ~part8)) ^ input[22]) let part9 = ((v[4] ^ input[174])) v[10] = (((input[175] ^ input[70]) ^ (input[93] & v[5])) ^ (input[37] & ~part9)) input[175] = v[10] v[11] = v[9] v[12] = input[134] v[13] = v[11] input[22] = v[11] v[14] = v[12] v[15] = ~v[8] v[16] = (v[12] & input[10]) v[17] = (input[2] | v[6]) let part10 = (((v[5] & input[113]) ^ input[172])) v[18] = (((input[2] ^ input[142]) ^ (v[5] & ~input[19])) ^ (input[37] & ~part10)) let part11 = ((input[181] ^ input[10])) let part12 = (((part11 & ~v[8]) ^ input[194])) let part13 = ((v[16] ^ input[64])) let part14 = (((((v[16] ^ input[18]) ^ (part13 & ~v[8])) ^ (part12 & v[3])) | input[125])) let part15 = ((((~v[8] & v[6]) ^ v[7]) | input[56])) v[19] = ((((input[25] ^ v[12]) ^ v[17]) ^ part15) ^ part14) v[20] = (v[18] & input[24]) v[21] = (v[18] | input[24]) v[22] = ((v[18] & input[24]) & input[199]) v[23] = (v[18] ^ input[24]) v[24] = input[17] v[25] = (input[36] ^ input[167]) v[26] = input[26] let part16 = ((v[18] | input[24])) v[27] = (part16 & input[199]) v[28] = (~v[18] & input[199]) v[29] = (v[19] & ~v[24]) v[30] = input[9] v[31] = input[91] let part17 = (((v[5] & input[160]) ^ input[166])) v[32] = ((((v[5] & input[186]) ^ input[120]) ^ input[16]) ^ (input[37] & ~part17)) v[33] = (v[19] & v[31]) input[16] = v[32] v[34] = v[19] v[35] = (v[18] ^ input[131]) input[113] = v[18] let part18 = ((v[26] | v[19])) v[36] = (v[25] ^ part18) input[36] = v[36] v[37] = v[35] input[131] = v[35] v[38] = (v[22] ^ v[20]) input[202] = (v[22] ^ v[20]) v[39] = input[10] v[40] = input[64] v[41] = (v[28] ^ v[23]) input[138] = (v[28] ^ v[23]) v[42] = (v[40] & v[39]) v[43] = input[112] input[116] = v[27] v[44] = (v[34] & v[43]) v[45] = (v[33] ^ v[24]) v[46] = (v[34] & input[44]) v[47] = input[10] v[48] = (v[29] ^ v[31]) v[49] = (v[27] ^ v[20]) input[161] = (v[27] ^ v[20]) v[50] = input[1] v[51] = ((v[33] ^ v[30]) | v[50]) v[52] = (v[42] ^ v[17]) v[53] = (v[47] & ~v[14]) v[54] = ((v[34] & v[24]) ^ v[31]) v[55] = (v[34] & ~v[31]) v[56] = (v[46] ^ input[68]) v[57] = (v[53] ^ input[64]) let part19 = ((v[45] | v[50])) v[58] = (part19 ^ v[45]) v[59] = (v[54] & ~v[50]) v[60] = ((input[129] ^ v[44]) ^ v[51]) v[61] = (input[112] ^ v[44]) v[62] = input[1] let part20 = (((v[34] & v[24]) ^ input[72])) v[63] = (v[62] & ~part20) v[64] = (input[129] ^ v[62]) let part21 = ((v[29] ^ v[31])) v[65] = ((part21 & ~v[50]) ^ v[56]) let part22 = (((v[34] & ~v[30]) ^ v[24])) v[66] = (~v[50] & part22) v[67] = ((input[44] ^ input[52]) ^ (v[34] & input[68])) v[68] = (v[58] | input[33]) v[69] = ((v[55] ^ v[30]) ^ v[59]) v[70] = input[33] v[71] = ((v[51] ^ v[30]) | input[33]) let part23 = ((input[1] | (v[29] ^ v[30]))) v[72] = (((v[34] & ~input[112]) ^ v[30]) ^ part23) let part24 = ((v[66] ^ v[61])) v[73] = (part24 & ~v[70]) v[74] = (v[69] ^ v[68]) v[75] = ((input[1] & v[29]) ^ v[54]) let part25 = ((v[52] | input[56])) let part26 = (((part25 ^ input[104]) | input[125])) let part27 = (((v[57] & v[15]) | input[56])) v[76] = (part27 ^ part26) let part28 = ((input[1] | (v[29] ^ v[31]))) let part29 = ((part28 ^ v[30])) v[77] = ((v[75] ^ input[12]) ^ (part29 & ~v[70])) v[78] = ((input[0] ^ input[153]) ^ (input[88] & ~v[34])) v[79] = input[63] v[80] = ~v[79] let part30 = ((v[1] ^ input[18])) v[81] = (part30 & v[15]) let part31 = ((v[65] | input[33])) let part32 = ((((part31 ^ v[63]) ^ v[56]) | v[79])) v[82] = ((v[74] ^ input[195]) ^ part32) let part33 = ((v[67] | input[33])) let part34 = (((v[67] ^ part33) | v[79])) v[83] = ((((v[64] ^ input[40]) ^ (v[34] & ~input[68])) ^ v[73]) ^ part34) let part35 = ((v[55] | input[1])) let part36 = ((((v[60] & ~v[70]) ^ part35) ^ v[48])) input[98] ^= (v[74] ^ (v[79] & ~part36)) let part37 = ((v[72] ^ v[71])) v[84] = (v[77] ^ (part37 & ~v[79])) v[85] = (input[14] ^ input[148]) v[86] = input[42] v[87] = v[83] v[88] = input[108] input[40] = v[83] v[89] = (v[76] ^ v[86]) v[90] = (v[34] | v[88]) v[91] = input[47] v[92] = v[84] v[93] = (input[18] ^ input[66]) input[12] = v[84] v[94] = (v[81] ^ v[91]) v[95] = input[62] v[96] = input[5] v[97] = v[82] input[195] = v[82] let part38 = ((v[34] | v[96])) v[98] = (v[93] ^ part38) input[5] = v[98] input[14] = (v[85] ^ v[90]) v[99] = (~v[78] & v[95]) input[0] = v[78] input[88] = v[99] v[100] = (~v[78] & v[95]) input[167] = v[99] v[101] = (v[78] & v[95]) input[81] = (v[78] & v[95]) let part39 = ((v[89] ^ v[94])) v[102] = ~part39 v[103] = (v[85] ^ v[90]) v[104] = ((v[13] ^ v[85]) ^ v[90]) v[105] = (v[89] ^ v[94]) v[106] = ~input[58] v[107] = input[1] let part40 = (((v[89] ^ v[94]) | input[29])) let part41 = ((part40 ^ input[107])) let part42 = (((((v[102] & input[185]) ^ input[107]) ^ (input[1] & ~part41)) | input[63])) let part43 = (((input[140] & v[102]) ^ input[184])) v[108] = (((((v[107] & ~part43) ^ input[123]) ^ input[10]) ^ (v[102] & input[149])) ^ part42) v[109] = (v[108] | v[18]) v[110] = input[58] let part44 = (((v[102] & input[152]) ^ input[73])) let part45 = (((v[107] & ~part44) ^ input[151])) let part46 = (((v[102] & input[151]) ^ input[145])) let part47 = (((v[89] ^ v[94]) | input[132])) v[111] = ((((input[60] ^ input[170]) ^ part47) ^ (input[1] & ~part46)) ^ (part45 & v[80])) v[112] = (v[108] & ~v[18]) v[113] = (v[18] & ~v[108]) let part48 = ((v[18] | input[58])) v[114] = (part48 ^ v[18]) let part49 = (((v[89] ^ v[94]) | input[29])) let part50 = ((part49 ^ input[107])) let part51 = (((((v[102] & input[185]) ^ input[107]) ^ (input[1] & ~part50)) | input[63])) let part52 = (((input[140] & v[102]) ^ input[184])) v[115] = (((((v[107] & ~part52) ^ input[123]) ^ input[10]) ^ (v[102] & input[149])) ^ part51) v[116] = (v[108] ^ v[18]) v[117] = ((v[108] | v[18]) | v[110]) v[118] = ((v[18] & ~v[108]) | v[110]) v[119] = (v[117] ^ v[108]) v[120] = ((v[108] & ~v[18]) ^ v[110]) v[121] = ((v[108] & ~v[18]) | v[110]) v[122] = input[31] let part53 = ((v[110] | v[108])) let part54 = ((part53 ^ v[108])) v[123] = (((v[108] & ~v[18]) & v[106]) ^ (part54 & v[82])) let part55 = ((v[89] ^ v[94])) v[124] = (part55 & v[122]) v[125] = ((v[89] ^ v[94]) | v[122]) v[126] = (v[111] | v[13]) v[127] = ~input[80] v[128] = (v[125] & ~v[122]) v[129] = ((v[121] ^ v[108]) ^ v[18]) v[130] = input[38] let part56 = ((v[89] ^ v[94])) v[131] = ((~v[122] & v[127]) & part56) let part57 = ((v[111] | ~v[103])) v[132] = (part57 & v[130]) v[133] = ((v[111] | v[104]) | v[130]) v[134] = ~v[130] let part58 = ((v[111] | v[104])) v[135] = ((part58 ^ v[103]) | input[38]) let part59 = ((v[111] | v[13])) v[136] = (part59 & ~v[130]) v[137] = (v[98] & ~v[123]) v[138] = ((v[116] ^ input[58]) ^ (v[97] & ~v[119])) v[139] = (input[31] & ~v[124]) input[60] = v[111] let part60 = ((v[111] | v[104])) input[157] = (v[133] ^ part60) v[140] = input[118] input[151] = (v[132] ^ v[103]) v[141] = v[140] let part61 = ((((v[18] & v[106]) & v[97]) ^ v[18])) v[142] = ((v[129] ^ (v[120] & v[97])) ^ (v[98] & ~part61)) v[143] = input[89] let part62 = (((v[97] & v[106]) ^ v[114])) v[144] = (((v[98] & ~part62) ^ (v[97] & v[118])) ^ v[112]) v[145] = (v[138] ^ v[137]) v[146] = (v[102] & input[31]) v[147] = v[145] v[148] = (v[139] | input[80]) input[29] = v[115] v[149] = input[141] v[150] = (v[105] | input[152]) v[151] = input[105] input[19] = v[142] v[152] = (v[102] & v[151]) let part63 = ((v[105] | input[102])) v[153] = (v[149] ^ part63) input[118] = (v[136] ^ v[103]) input[89] = v[147] v[154] = input[1] input[91] = v[144] v[155] = v[152] v[156] = input[111] v[157] = (v[154] & ~v[153]) input[123] = v[146] v[158] = (v[128] ^ v[131]) v[159] = input[178] input[111] = (v[128] ^ v[131]) let part64 = ((v[131] ^ v[125])) v[160] = (v[159] & ~part64) v[161] = ~input[23] v[162] = ((v[102] & v[156]) ^ input[124]) let part65 = ((v[105] | input[75])) v[163] = (part65 ^ v[143]) v[164] = input[7] let part66 = ((v[111] | v[13])) input[73] = (v[135] ^ part66) let part67 = (((v[160] ^ ((v[161] & v[127]) & v[105])) ^ v[125])) v[165] = (part67 & v[164]) v[166] = input[178] v[167] = (v[148] ^ v[146]) input[134] = (v[148] ^ v[124]) input[104] = v[128] v[168] = (((input[28] ^ (v[166] & ~v[158])) ^ v[148]) ^ v[124]) v[169] = (v[105] | input[146]) v[170] = (v[125] & v[127]) v[171] = (v[125] | input[80]) v[172] = (v[139] ^ v[170]) v[173] = v[170] v[174] = input[80] input[72] = v[172] v[175] = (v[105] | v[174]) v[176] = (v[146] & v[127]) v[177] = ((v[124] & v[127]) ^ v[124]) let part68 = (((v[124] & v[127]) ^ v[146])) v[178] = (((v[146] & v[127]) ^ v[128]) ^ (part68 & v[161])) let part69 = ((v[105] | input[23])) let part70 = (((part69 ^ v[105]) ^ v[176])) v[179] = (input[178] & ~part70) input[44] = v[178] let part71 = ((v[171] ^ v[124])) v[180] = (v[172] ^ (part71 & v[161])) let part72 = ((((v[177] & v[161]) ^ v[158]) ^ v[179])) v[181] = (input[7] & ~part72) let part73 = ((v[172] | input[23])) v[182] = ((v[168] ^ part73) ^ v[165]) v[183] = (v[177] ^ input[71]) v[184] = (input[1] & ~v[163]) v[185] = (input[50] ^ v[150]) v[186] = v[182] input[28] = v[182] v[187] = (v[16] & v[15]) let part74 = (((v[124] ^ v[175]) | input[23])) let part75 = ((part74 ^ v[128])) v[188] = (part75 & input[178]) v[189] = ((v[162] ^ (v[185] & input[1])) | input[63]) v[190] = ~v[111] v[191] = (~v[111] & v[104]) v[192] = ((((input[8] ^ input[115]) ^ v[155]) ^ v[157]) ^ v[189]) v[193] = (v[191] ^ v[13]) let part76 = ((v[191] ^ v[103])) v[194] = (part76 & v[134]) v[195] = (((v[180] ^ input[54]) ^ v[188]) ^ v[181]) let part77 = ((input[94] ^ v[167])) v[196] = (input[178] & ~part77) let part78 = ((input[80] | v[124])) let part79 = ((part78 ^ v[124])) v[197] = ((v[183] & input[178]) ^ (input[23] & ~part79)) input[172] = ((input[38] & ~v[193]) ^ v[103]) v[198] = (v[13] & ~v[103]) v[199] = (input[7] & ~v[197]) let part80 = ((v[111] | v[13])) input[184] = (((v[13] & ~v[111]) ^ v[103]) ^ (input[38] & ~part80)) input[8] = v[192] let part81 = ((v[111] | v[13])) v[200] = (part81 ^ v[13]) v[201] = (v[171] ^ input[31]) v[202] = ((v[178] ^ input[32]) ^ v[196]) v[203] = (input[38] & ~v[200]) input[181] = (v[194] ^ v[200]) let part82 = ((v[111] | v[104])) input[140] = (v[203] ^ part82) let part83 = ((v[111] | v[104])) v[204] = (part83 ^ v[104]) v[205] = (v[202] ^ v[199]) v[206] = input[38] input[189] = ((v[206] ^ v[13]) ^ v[111]) let part84 = (((v[103] & ~v[13]) ^ v[111])) input[108] = ((v[13] & ~v[198]) ^ (v[206] & ~part84)) let part85 = (((~v[111] & v[198]) ^ v[13])) input[168] = (((~v[111] & v[198]) ^ v[103]) ^ (v[206] & ~part85)) input[54] = v[195] v[207] = input[122] let part86 = ((v[103] | v[111])) input[132] = (part86 ^ v[13]) v[208] = (v[186] & ~v[207]) v[209] = input[122] let part87 = ((~v[111] ^ v[13])) input[141] = (((part87 & v[103]) & v[206]) ^ v[204]) input[68] = v[208] v[210] = (v[36] | (v[209] ^ v[208])) input[194] = ((v[206] & ~v[204]) ^ v[111]) v[211] = (v[195] & ~v[100]) v[212] = (v[195] & v[100]) v[213] = (v[195] & ~v[101]) v[214] = input[62] input[105] = v[210] v[215] = (v[205] | v[214]) v[216] = input[31] input[153] = v[213] input[185] = v[211] v[217] = v[216] v[218] = (v[105] ^ v[216]) v[219] = input[80] input[64] = v[212] v[220] = (v[218] | v[219]) v[221] = v[205] v[222] = input[178] input[32] = v[205] let part88 = ((v[220] ^ v[217])) v[223] = (v[222] & ~part88) v[224] = input[74] v[225] = ~v[205] v[226] = input[200] v[227] = (((input[24] & v[205]) & v[78]) ^ v[215]) input[4] = v[218] v[228] = (v[227] & v[192]) v[229] = input[77] v[230] = (v[102] & input[61]) v[231] = input[84] let part89 = (((v[173] ^ v[218]) | input[23])) v[232] = ((v[167] ^ v[223]) ^ part89) input[176] = v[215] v[233] = ((v[141] ^ v[231]) ^ v[169]) v[234] = (v[221] | input[69]) v[235] = (v[221] | v[226]) input[117] = (v[218] ^ v[175]) v[236] = (v[201] & input[178]) v[237] = ((v[225] & v[229]) ^ input[24]) let part90 = ((v[187] ^ input[47])) v[238] = (part90 & v[3]) let part91 = ((v[230] ^ input[136])) v[239] = (v[233] ^ (part91 & input[1])) v[240] = (v[221] | v[224]) v[241] = ((input[39] ^ input[13]) ^ v[221]) v[242] = (v[18] & ~input[24]) input[74] = (v[225] & v[224]) v[243] = (v[232] & input[7]) let part92 = (((v[225] & v[224]) ^ v[101])) v[244] = (part92 & v[192]) let part93 = ((v[234] | v[78])) v[245] = ((v[225] & v[224]) ^ part93) let part94 = ((v[234] ^ v[224])) v[246] = (part94 & ~v[78]) v[247] = (v[215] ^ v[224]) v[248] = input[31] input[152] = v[245] v[249] = v[246] let part95 = ((v[221] | v[226])) let part96 = ((part95 ^ v[226])) let part97 = (((part96 & v[192]) ^ v[245])) v[250] = ((part97 & v[32]) ^ v[248]) v[251] = ((v[215] & v[78]) ^ v[237]) v[252] = v[250] v[253] = (v[237] | v[78]) v[254] = (v[215] ^ input[106]) v[255] = ((v[235] ^ input[62]) | v[78]) let part98 = ((v[251] ^ (v[192] & ~v[235]))) v[256] = (v[32] & ~part98) v[257] = input[62] input[94] = v[251] input[100] = v[254] v[258] = (v[225] & v[257]) input[200] = v[247] v[259] = ((v[225] & input[39]) ^ v[257]) v[260] = input[10] v[261] = (v[259] ^ v[253]) v[262] = (v[253] ^ v[229]) input[120] = v[262] v[263] = (v[260] ^ input[18]) input[77] = (v[228] ^ v[262]) v[264] = ((v[228] ^ v[262]) ^ v[256]) v[265] = (v[261] & v[192]) v[266] = (v[221] | input[24]) v[267] = (v[238] ^ v[81]) v[268] = (((v[105] & input[115]) ^ input[124]) ^ v[184]) v[269] = (v[263] | input[2]) v[270] = v[263] v[271] = input[39] v[272] = input[69] input[52] = ((v[266] ^ input[69]) ^ v[255]) v[273] = ((v[258] ^ v[271]) | v[78]) let part99 = ((v[221] | v[229])) v[274] = (part99 ^ v[272]) let part100 = ((v[221] | v[271])) v[275] = ((part100 & ~v[78]) ^ (input[106] & ~v[192])) v[276] = (~v[18] & input[24]) v[277] = input[199] v[278] = (v[23] & v[277]) v[279] = (v[242] & v[277]) v[280] = (v[268] | input[63]) v[281] = (v[247] ^ v[273]) v[282] = (((input[27] ^ input[24]) ^ v[258]) ^ v[249]) v[283] = v[221] let part101 = ((v[240] ^ v[272])) v[284] = ((part101 & ~v[78]) ^ v[254]) let part102 = ((v[20] | ~v[18])) v[285] = (input[199] & part102) let part103 = (((v[240] ^ v[229]) | v[78])) let part104 = ((((v[225] & input[106]) ^ input[82]) ^ part103)) v[286] = (v[192] & ~part104) let part105 = (((v[23] & v[277]) ^ v[276])) v[287] = ((v[221] & part105) ^ v[37]) v[288] = ((v[241] ^ (v[274] & ~v[78])) ^ (v[32] & ~v[275])) let part106 = (((v[20] ^ (v[242] & v[277])) | v[221])) v[289] = (part106 ^ v[18]) v[290] = input[41] let part107 = ((v[21] & ~v[18])) v[291] = ((~part107 & input[199]) ^ v[23]) let part108 = ((v[244] ^ input[52])) input[112] = ((v[282] ^ v[265]) ^ (v[32] & ~part108)) v[292] = (v[239] ^ v[280]) v[293] = (v[288] ^ (v[192] & ~v[284])) v[294] = (~v[21] & input[199]) v[295] = ((v[285] ^ (v[21] & ~v[18])) ^ (v[283] & v[20])) v[296] = (v[286] ^ v[281]) input[170] = v[296] v[297] = (v[291] ^ v[283]) v[298] = v[289] v[299] = v[283] v[300] = (v[283] & v[21]) v[301] = v[264] v[302] = v[293] v[303] = (v[252] ^ v[296]) input[106] = v[281] input[41] = (v[290] ^ v[301]) input[13] = v[302] input[84] = v[292] let part109 = ((v[287] | v[87])) v[304] = (part109 ^ v[297]) let part110 = ((v[298] | v[87])) v[305] = (v[295] ^ part110) v[306] = v[303] input[102] = v[303] v[307] = (v[10] | input[103]) v[308] = ((v[300] ^ v[294]) ^ v[23]) input[99] = v[308] v[309] = input[103] input[130] = v[297] input[146] = (v[292] | v[10]) v[310] = ~v[309] v[311] = ~v[10] v[312] = (input[117] ^ input[34]) v[313] = input[159] v[314] = (v[236] ^ v[312]) input[137] = v[304] let part111 = ((v[292] | v[10])) v[315] = (part111 & ~v[292]) v[316] = (input[109] ^ v[313]) v[317] = ((v[243] ^ v[236]) ^ v[312]) let part112 = (((~v[10] & v[292]) ^ v[307])) v[318] = (input[58] & ~part112) input[174] = v[305] v[319] = v[318] v[320] = (v[316] ^ input[43]) v[321] = (v[10] & ~v[309]) v[322] = (input[96] ^ v[317]) v[323] = input[125] input[69] = (v[10] & v[292]) let part113 = (((v[267] ^ v[270]) | v[323])) v[324] = ((v[320] ^ v[269]) ^ part113) let part114 = ((v[10] & v[292])) v[325] = (v[292] & ~part114) v[326] = ((v[292] | v[10]) | input[103]) v[327] = (v[325] ^ input[65]) v[328] = (v[22] ^ input[24]) v[329] = (v[292] ^ input[57]) v[330] = (input[103] | v[315]) v[331] = (((v[10] & v[292]) ^ input[7]) ^ v[330]) let part115 = (((v[10] & v[292]) ^ v[307])) let part116 = ((((part115 & input[58]) ^ v[315]) ^ v[307])) v[332] = (part116 & v[322]) input[43] = v[324] let part117 = (((v[292] ^ v[10]) ^ v[321])) v[333] = (part117 & input[58]) v[334] = ((v[321] & ~v[292]) ^ (v[10] & v[292])) v[335] = (v[325] ^ v[333]) v[336] = input[103] input[34] = v[312] v[337] = ((v[292] ^ v[10]) ^ v[336]) v[338] = ((v[292] ^ v[10]) | v[336]) v[339] = input[115] input[186] = v[317] v[340] = (v[337] ^ v[339]) v[341] = input[58] v[342] = (v[337] | input[58]) input[160] = v[314] v[343] = (v[307] ^ v[10]) v[344] = (v[307] & v[341]) input[96] = v[322] let part118 = ((v[292] | input[103])) v[345] = (part118 ^ v[292]) input[61] = v[334] v[346] = input[103] let part119 = ((v[345] ^ v[344])) v[347] = (v[322] & ~part119) let part120 = ((v[325] | v[346])) let part121 = ((v[327] ^ part120)) v[348] = (part121 & v[322]) let part122 = (((v[10] & v[292]) | v[346])) let part123 = ((v[325] ^ part122)) v[349] = (part123 & input[58]) let part124 = ((v[292] | v[10])) v[350] = (v[329] ^ (part124 & v[310])) let part125 = ((v[292] | v[10])) v[351] = (((v[10] & v[292]) & v[310]) ^ part125) v[352] = v[331] let part126 = ((v[342] ^ (v[10] & v[292]))) let part127 = ((v[292] | v[10])) let part128 = ((v[292] | v[10])) v[353] = ((((part127 & v[310]) ^ part128) ^ v[349]) ^ (part126 & v[322])) let part129 = ((v[335] ^ ((v[10] & v[292]) & v[310]))) let part130 = ((v[292] | v[10])) let part131 = ((part130 ^ v[338])) v[354] = (((input[58] & ~part131) ^ v[352]) ^ (v[322] & ~part129)) v[355] = input[58] v[356] = (v[355] & ~v[315]) let part132 = ((v[330] ^ v[315])) v[357] = ((part132 & v[355]) ^ v[334]) v[358] = input[58] let part133 = ((v[356] ^ (v[10] & v[292]))) v[359] = (v[322] & ~part133) v[360] = (v[345] ^ (v[343] & v[358])) v[361] = input[58] v[362] = ((v[358] & ~v[343]) ^ input[21]) v[363] = input[58] input[164] = v[351] v[364] = (v[330] ^ (v[292] & v[361])) let part134 = ((v[338] ^ v[292])) v[365] = (((v[338] ^ v[292]) ^ (v[361] & ~part134)) ^ v[332]) v[366] = ((v[324] & ~input[198]) ^ input[30]) let part135 = (((v[326] ^ v[10]) ^ v[319])) let part136 = (((v[357] ^ (part135 & v[322])) | v[97])) v[367] = (((v[350] ^ (v[326] & v[363])) ^ v[359]) ^ part136) v[368] = input[27] input[57] = v[367] let part137 = (((v[360] ^ v[348]) | v[97])) v[369] = (((v[362] ^ v[351]) ^ v[347]) ^ part137) let part138 = ((v[326] ^ v[292])) v[370] = ((v[340] ^ (part138 & v[363])) ^ (v[322] & ~v[364])) input[198] = (v[366] | v[368]) v[371] = (v[302] | v[369]) input[21] = v[369] v[372] = (v[370] ^ (v[365] & ~v[97])) input[115] = v[372] input[65] = (v[302] | v[369]) v[373] = (v[354] ^ (v[353] & ~v[97])) v[374] = (v[285] ^ v[20]) v[375] = input[119] input[7] = v[373] v[376] = (v[328] & v[225]) v[377] = input[139] v[378] = input[135] input[180] = v[371] v[379] = ((v[324] & v[377]) ^ v[378]) v[380] = (v[278] ^ v[18]) let part139 = (((v[324] & input[188]) | input[27])) v[381] = (((input[20] ^ input[92]) ^ (v[324] & ~input[158])) ^ part139) v[382] = (v[10] | v[381]) v[383] = (v[10] & v[381]) let part140 = ((v[10] ^ v[381])) v[384] = (part140 & v[36]) v[385] = ((((v[10] & v[381]) & v[36]) ^ v[10]) ^ v[381]) let part141 = ((v[10] | v[381])) v[386] = (part141 & v[36]) v[387] = ((v[384] ^ v[10]) ^ v[381]) let part142 = ((v[10] | v[381])) v[388] = (v[36] & ~part142) v[389] = ((v[384] ^ v[10]) | v[186]) v[390] = (v[186] | (v[10] ^ v[381])) v[391] = ((v[10] & ~v[381]) ^ v[386]) let part143 = ((v[10] | v[381])) v[392] = ((v[36] & ~part143) ^ v[10]) v[393] = ~input[27] let part144 = ((((v[299] & ~v[18]) ^ v[38]) | v[87])) let part145 = ((v[28] ^ v[18])) v[394] = (((v[299] & ~part145) ^ v[374]) ^ part144) v[395] = (input[58] | v[116]) v[396] = (v[186] | ((v[384] ^ v[10]) ^ v[381])) v[397] = (((input[56] ^ input[183]) ^ (v[324] & ~input[15])) ^ (v[379] & v[393])) let part146 = ((v[391] ^ v[390])) v[398] = (((v[386] ^ v[381]) ^ (~v[186] & v[385])) ^ (v[92] & ~part146)) v[399] = (v[113] & v[106]) let part147 = ((v[389] ^ v[384])) v[400] = ((v[392] ^ v[396]) ^ (part147 & v[92])) v[401] = ((v[113] & v[106]) ^ v[113]) v[402] = (v[400] ^ input[63]) let part148 = ((v[21] & ~v[18])) let part149 = (((v[376] ^ v[38]) | v[87])) v[403] = ((((part149 ^ input[1]) ^ v[380]) ^ (v[299] & ~part148)) ^ (v[397] & ~v[394])) v[404] = (input[58] ^ v[115]) v[405] = (v[382] ^ v[388]) v[406] = (v[402] ^ (v[292] & ~v[398])) let part150 = ((((v[36] & ~v[383]) ^ v[381]) ^ v[390])) v[407] = (((v[405] & ~v[186]) ^ v[383]) ^ (part150 & v[92])) let part151 = ((v[395] ^ v[18])) let part152 = ((((v[97] & ~part151) ^ v[113]) ^ (v[18] & v[106]))) v[408] = ((((v[401] & ~v[97]) ^ v[113]) ^ (v[18] & v[106])) ^ (part152 & v[98])) let part153 = ((v[406] & v[403])) v[409] = (v[403] & ~part153) let part154 = ((v[408] | v[397])) let part155 = ((v[395] ^ v[18])) let part156 = (((part155 & v[97]) ^ v[18])) let part157 = ((v[401] | v[97])) v[410] = ((((part157 ^ v[404]) ^ v[105]) ^ (part156 & v[98])) ^ part154) v[411] = (v[402] ^ (v[292] & ~v[398])) let part158 = ((v[384] ^ v[381])) let part159 = (((part158 & ~v[186]) ^ v[387])) let part160 = ((v[186] | v[381])) v[412] = ((((v[311] & v[381]) ^ v[386]) ^ part160) ^ (v[92] & ~part159)) v[413] = ((v[400] ^ input[53]) ^ (v[398] & ~v[292])) v[414] = (v[411] | v[403]) v[415] = (v[411] ^ v[403]) let part161 = ((v[406] & v[403])) v[416] = ((v[403] & ~part161) | v[372]) let part162 = ((v[411] | v[403])) v[417] = (part162 & ~v[372]) v[418] = ((v[407] & ~v[292]) ^ v[412]) let part163 = ((v[411] ^ v[403])) v[419] = (part163 & ~v[372]) let part164 = ((v[411] | v[403])) v[420] = (v[416] ^ part164) v[421] = (v[292] & ~v[407]) v[422] = (v[373] & ~v[413]) v[423] = (v[412] ^ input[35]) input[42] = v[410] v[424] = input[196] input[20] = v[381] input[1] = v[403] input[53] = v[413] input[119] = (v[413] ^ v[373]) input[56] = v[397] input[66] = v[422] input[63] = v[406] input[92] = (v[373] & ~v[422]) input[196] = (v[418] ^ v[424]) input[35] = (v[423] ^ v[421]) input[2] = (v[413] | v[373]) input[124] = (v[306] ^ v[410]) input[159] = (v[413] & v[373]) input[15] = (v[410] & v[306]) input[10] = (v[413] & ~v[373]) input[145] = (~v[410] & v[306]) input[139] = (~v[306] & v[410]) let part165 = ((v[410] & v[306])) input[183] = (v[410] & ~part165) let part166 = ((v[306] | v[410])) input[135] = (part166 & ~v[410]) input[93] = (((v[306] & v[372]) ^ v[414]) ^ v[417]) v[425] = (~v[372] & v[403]) input[125] = ((v[419] ^ v[406]) ^ (v[306] & ~v[417])) input[162] = (v[406] & v[403]) let part167 = ((v[403] | v[372])) let part168 = ((v[403] | v[372])) let part169 = ((v[406] & v[403])) let part170 = (((v[403] & ~part169) ^ part167)) input[79] = ((part170 & v[306]) ^ part168) v[426] = input[90] input[47] = v[425] let part171 = ((v[406] & v[403])) input[75] = (v[403] & ~part171) input[158] = (v[306] | v[410]) v[427] = input[201] let part172 = ((v[406] | v[372])) input[136] = ((v[415] ^ part172) ^ (v[306] & ~v[420])) v[428] = (((v[299] & ~v[23]) ^ v[279]) ^ v[21]) let part173 = (((~v[97] & v[114]) ^ input[58])) v[429] = (part173 & v[98]) let part174 = (((v[324] & ~v[426]) ^ input[78])) v[430] = (((v[375] ^ input[6]) ^ (v[324] & v[427])) ^ (part174 & v[393])) v[431] = (((v[299] & v[242]) ^ v[41]) | v[87]) let part175 = (((v[266] ^ v[242]) | v[87])) v[432] = (((v[299] & ~v[21]) ^ v[27]) ^ part175) v[433] = ((v[428] & ~v[87]) ^ ((v[276] & ~input[199]) & v[299])) let part176 = ((input[24] ^ v[27])) let part177 = (((v[299] & ~part176) ^ v[21])) v[434] = (part177 & ~v[87]) v[435] = (v[13] | v[103]) input[70] = (v[403] & ~v[406]) v[436] = ((v[308] ^ input[178]) ^ v[434]) let part178 = ((v[395] ^ v[116])) let part179 = (((v[18] ^ (v[18] & v[106])) ^ (part178 & v[97]))) v[437] = (((v[117] ^ v[109]) ^ (v[97] & ~v[109])) ^ (part179 & v[98])) v[438] = ((v[13] | v[103]) | v[111]) v[439] = input[70] input[126] = (~v[403] & v[406]) v[440] = (v[439] & ~v[372]) v[441] = input[122] input[201] = (v[430] ^ input[122]) v[442] = (v[104] ^ input[38]) let part180 = ((v[118] ^ v[115])) let part181 = (((v[97] & ~v[404]) ^ v[399])) v[443] = (((part181 & v[98]) ^ (v[109] & v[106])) ^ (v[97] & ~part180)) let part182 = ((v[117] ^ v[112])) let part183 = (((v[429] ^ (v[109] & v[106])) ^ (v[97] & ~part182))) v[444] = (part183 & ~v[397]) v[445] = (v[438] ^ v[435]) v[446] = ((v[414] & ~v[403]) | v[372]) v[447] = (input[126] ^ v[425]) v[448] = input[122] v[449] = ((v[186] & v[441]) ^ input[201]) input[192] = ((v[430] & ~v[186]) & ~v[36]) input[148] = (~v[430] & v[448]) v[450] = (v[442] ^ v[126]) let part184 = ((v[437] | v[397])) v[451] = (part184 ^ v[147]) let part185 = ((v[431] ^ v[49])) input[26] = (v[304] ^ (part185 & v[397])) input[178] = (v[436] ^ (v[397] & ~v[432])) v[452] = ((v[397] & ~v[433]) ^ v[305]) let part186 = ((v[443] | v[397])) v[453] = ((v[144] ^ v[324]) ^ part186) v[454] = ((v[142] ^ v[5]) ^ v[444]) let part187 = ((v[409] ^ v[419])) v[455] = (v[306] & ~part187) v[456] = (v[409] ^ v[440]) let part188 = ((v[414] | v[372])) v[457] = (input[126] ^ part188) v[458] = (input[126] & v[306]) v[459] = (input[126] & ~v[306]) v[460] = (v[449] ^ input[192]) v[461] = (v[186] & input[148]) v[462] = input[26] input[25] = (v[451] ^ v[34]) v[463] = input[178] v[464] = v[461] v[465] = v[462] input[193] = (v[454] & v[373]) v[466] = input[37] input[173] = v[454] input[149] = v[453] input[49] = (~v[306] & v[463]) input[107] = v[451] input[37] = (v[466] ^ v[465]) input[150] = v[452] let part189 = ((v[445] | v[430])) input[129] = (part189 ^ v[450]) input[155] = ((v[446] ^ (v[406] & v[403])) ^ v[455]) let part190 = (((v[406] & v[403]) ^ v[416])) input[182] = ((v[417] ^ v[415]) ^ (v[306] & ~part190)) let part191 = ((v[417] ^ v[403])) input[188] = ((((~v[372] & v[406]) & v[403]) ^ v[403]) ^ (part191 & v[306])) input[6] = v[430] let part192 = ((v[403] | v[372])) let part193 = ((part192 ^ v[406])) input[86] = ((v[406] ^ v[416]) ^ (part193 & ~v[306])) let part194 = ((v[403] | v[372])) let part195 = ((v[414] ^ part194)) input[39] = ((part195 & v[306]) ^ (v[406] & v[403])) v[467] = input[87] input[109] = (v[414] ^ v[403]) let part196 = ((v[440] ^ (v[406] & v[403]))) input[142] = ((v[446] ^ v[403]) ^ (v[306] & ~part196)) v[468] = ((v[186] & ~v[430]) ^ input[122]) input[45] = ((v[406] ^ v[416]) ^ v[306]) let part197 = ((v[414] ^ v[440])) input[97] = (v[456] ^ (v[306] & ~part197)) let part198 = ((v[414] | v[372])) let part199 = ((part198 ^ (v[406] & v[403]))) input[30] = (v[457] ^ (part199 & v[306])) input[18] = (v[458] ^ v[425]) input[31] = ((~v[306] & v[447]) ^ v[425]) input[71] = (~v[372] & v[459]) input[87] = (v[467] ^ v[452]) input[27] = (v[186] ^ v[430]) input[78] = (v[460] & v[190]) input[90] = (v[464] ^ v[430]) input[50] = v[468] return input } }
gpl-3.0
6b6f0b5c144f703179e8738e85c8a676
39.691578
118
0.398636
2.452245
false
false
false
false
bazelbuild/tulsi
src/TulsiGeneratorIntegrationTests/BazelFakeWorkspace.swift
1
4181
// Copyright 2018 The Tulsi Authors. All rights reserved. // // 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 import XCTest @testable import TulsiGenerator class BazelFakeWorkspace { let resourcesPathBase = "src/TulsiGeneratorIntegrationTests/Resources" let extraBuildFlags: [String] var runfilesURL: URL var runfilesWorkspaceURL: URL var fakeExecroot: URL var workspaceRootURL: URL var bazelURL: URL var canaryBazelURL: URL? var pathsToCleanOnTeardown = Set<URL>() // NOTE: messageLogger is unused here, but used within Google init(runfilesURL: URL, tempDirURL: URL, messageLogger: LocalizedMessageLogger) { self.runfilesURL = runfilesURL self.runfilesWorkspaceURL = runfilesURL.appendingPathComponent("__main__", isDirectory: true) self.fakeExecroot = tempDirURL.appendingPathComponent("fake_execroot", isDirectory: true) self.workspaceRootURL = fakeExecroot.appendingPathComponent("__main__", isDirectory: true) self.bazelURL = BazelLocator.bazelURL! self.extraBuildFlags = [] } private func addExportsFiles(buildFilePath: String, exportedFile: String) throws { try createDummyFile(path: "\(buildFilePath)/BUILD", content: "exports_files([\"\(exportedFile)\"])\n") } private func addFilegroup(buildFilePath: String, filegroup: String) throws { try createDummyFile(path: "\(buildFilePath)/BUILD", content: """ filegroup( name = "\(filegroup)", visibility = ["//visibility:public"], ) """ ) } private func createDummyFile(path: String, content: String) throws { let fileURL = workspaceRootURL.appendingPathComponent(path) let fileManager = FileManager.default let containingDirectory = fileURL.deletingLastPathComponent() if !fileManager.fileExists(atPath: containingDirectory.path) { try fileManager.createDirectory(at: containingDirectory, withIntermediateDirectories: true, attributes: nil) } if fileManager.fileExists(atPath: fileURL.path) { try fileManager.removeItem(at: fileURL) } try content.write(to: fileURL, atomically: false, encoding: String.Encoding.utf8) } private func installWorkspaceFile() { do { try FileManager.default.createDirectory(at: workspaceRootURL, withIntermediateDirectories: true, attributes: nil) do { let fileManager = FileManager.default if fileManager.fileExists(atPath: fakeExecroot.path) { try fileManager.removeItem(at: fakeExecroot) } try fileManager.copyItem(at: runfilesURL, to: fakeExecroot) pathsToCleanOnTeardown.insert(workspaceRootURL) } catch let e as NSError { XCTFail("Failed to copy workspace '\(runfilesURL)' to '\(workspaceRootURL)' for test. Error: \(e.localizedDescription)") return } } catch let e as NSError { XCTFail("Failed to create temp directory '\(workspaceRootURL.path)' for test. Error: \(e.localizedDescription)") } } func setup() -> BazelFakeWorkspace? { installWorkspaceFile() do { try createDummyFile(path: "tools/objc/objc_dummy.mm", content: "") try addExportsFiles(buildFilePath: "tools/objc", exportedFile: "objc_dummy.mm") } catch let e as NSError { XCTFail("Failed to set up fake workspace. Error: \(e.localizedDescription)") } return self } }
apache-2.0
c6e778aae5b0761d9d73eaf837401b3c
37.712963
128
0.663238
4.861628
false
false
false
false
russbishop/swift
stdlib/public/Platform/POSIXError.swift
1
6998
// FIXME: Only defining _POSIXError for Darwin at the moment. #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) /// Enumeration describing POSIX error codes. @objc public enum POSIXError : Int32 { // FIXME: These are the values for Darwin. We need to get the Linux // values as well. /// Operation not permitted. case EPERM = 1 /// No such file or directory. case ENOENT = 2 /// No such process. case ESRCH = 3 /// Interrupted system call. case EINTR = 4 /// Input/output error. case EIO = 5 /// Device not configured. case ENXIO = 6 /// Argument list too long. case E2BIG = 7 /// Exec format error. case ENOEXEC = 8 /// Bad file descriptor. case EBADF = 9 /// No child processes. case ECHILD = 10 /// Resource deadlock avoided. case EDEADLK = 11 /// 11 was EAGAIN. /// Cannot allocate memory. case ENOMEM = 12 /// Permission denied. case EACCES = 13 /// Bad address. case EFAULT = 14 /// Block device required. case ENOTBLK = 15 /// Device / Resource busy. case EBUSY = 16 /// File exists. case EEXIST = 17 /// Cross-device link. case EXDEV = 18 /// Operation not supported by device. case ENODEV = 19 /// Not a directory. case ENOTDIR = 20 /// Is a directory. case EISDIR = 21 /// Invalid argument. case EINVAL = 22 /// Too many open files in system. case ENFILE = 23 /// Too many open files. case EMFILE = 24 /// Inappropriate ioctl for device. case ENOTTY = 25 /// Text file busy. case ETXTBSY = 26 /// File too large. case EFBIG = 27 /// No space left on device. case ENOSPC = 28 /// Illegal seek. case ESPIPE = 29 /// Read-only file system. case EROFS = 30 /// Too many links. case EMLINK = 31 /// Broken pipe. case EPIPE = 32 /// math software. /// Numerical argument out of domain. case EDOM = 33 /// Result too large. case ERANGE = 34 /// non-blocking and interrupt i/o. /// Resource temporarily unavailable. case EAGAIN = 35 /// Operation would block. public static var EWOULDBLOCK: POSIXError { return EAGAIN } /// Operation now in progress. case EINPROGRESS = 36 /// Operation already in progress. case EALREADY = 37 /// ipc/network software -- argument errors. /// Socket operation on non-socket. case ENOTSOCK = 38 /// Destination address required. case EDESTADDRREQ = 39 /// Message too long. case EMSGSIZE = 40 /// Protocol wrong type for socket. case EPROTOTYPE = 41 /// Protocol not available. case ENOPROTOOPT = 42 /// Protocol not supported. case EPROTONOSUPPORT = 43 /// Socket type not supported. case ESOCKTNOSUPPORT = 44 /// Operation not supported. case ENOTSUP = 45 /// Protocol family not supported. case EPFNOSUPPORT = 46 /// Address family not supported by protocol family. case EAFNOSUPPORT = 47 /// Address already in use. case EADDRINUSE = 48 /// Can't assign requested address. case EADDRNOTAVAIL = 49 /// ipc/network software -- operational errors /// Network is down. case ENETDOWN = 50 /// Network is unreachable. case ENETUNREACH = 51 /// Network dropped connection on reset. case ENETRESET = 52 /// Software caused connection abort. case ECONNABORTED = 53 /// Connection reset by peer. case ECONNRESET = 54 /// No buffer space available. case ENOBUFS = 55 /// Socket is already connected. case EISCONN = 56 /// Socket is not connected. case ENOTCONN = 57 /// Can't send after socket shutdown. case ESHUTDOWN = 58 /// Too many references: can't splice. case ETOOMANYREFS = 59 /// Operation timed out. case ETIMEDOUT = 60 /// Connection refused. case ECONNREFUSED = 61 /// Too many levels of symbolic links. case ELOOP = 62 /// File name too long. case ENAMETOOLONG = 63 /// Host is down. case EHOSTDOWN = 64 /// No route to host. case EHOSTUNREACH = 65 /// Directory not empty. case ENOTEMPTY = 66 /// quotas & mush. /// Too many processes. case EPROCLIM = 67 /// Too many users. case EUSERS = 68 /// Disc quota exceeded. case EDQUOT = 69 /// Network File System. /// Stale NFS file handle. case ESTALE = 70 /// Too many levels of remote in path. case EREMOTE = 71 /// RPC struct is bad. case EBADRPC = 72 /// RPC version wrong. case ERPCMISMATCH = 73 /// RPC prog. not avail. case EPROGUNAVAIL = 74 /// Program version wrong. case EPROGMISMATCH = 75 /// Bad procedure for program. case EPROCUNAVAIL = 76 /// No locks available. case ENOLCK = 77 /// Function not implemented. case ENOSYS = 78 /// Inappropriate file type or format. case EFTYPE = 79 /// Authentication error. case EAUTH = 80 /// Need authenticator. case ENEEDAUTH = 81 /// Intelligent device errors. /// Device power is off. case EPWROFF = 82 /// Device error, e.g. paper out. case EDEVERR = 83 /// Value too large to be stored in data type. case EOVERFLOW = 84 /// Program loading errors. /// Bad executable. case EBADEXEC = 85 /// Bad CPU type in executable. case EBADARCH = 86 /// Shared library version mismatch. case ESHLIBVERS = 87 /// Malformed Macho file. case EBADMACHO = 88 /// Operation canceled. case ECANCELED = 89 /// Identifier removed. case EIDRM = 90 /// No message of desired type. case ENOMSG = 91 /// Illegal byte sequence. case EILSEQ = 92 /// Attribute not found. case ENOATTR = 93 /// Bad message. case EBADMSG = 94 /// Reserved. case EMULTIHOP = 95 /// No message available on STREAM. case ENODATA = 96 /// Reserved. case ENOLINK = 97 /// No STREAM resources. case ENOSR = 98 /// Not a STREAM. case ENOSTR = 99 /// Protocol error. case EPROTO = 100 /// STREAM ioctl timeout. case ETIME = 101 /// No such policy registered. case ENOPOLICY = 103 /// State not recoverable. case ENOTRECOVERABLE = 104 /// Previous owner died. case EOWNERDEAD = 105 /// Interface output queue is full. case EQFULL = 106 /// Must be equal largest errno. public static var ELAST: POSIXError { return EQFULL } // FIXME: EOPNOTSUPP has different values depending on __DARWIN_UNIX03 and // KERNEL. } #endif // os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
apache-2.0
e1775f488e8f402a76cb9e48df1653c1
26.551181
76
0.581309
4.412358
false
false
false
false
Eonil/EditorLegacy
Modules/Editor/Sources/TypeExtensions/AppKitExtensions.swift
1
2986
// // AppKitExtensions.swift // RustCodeEditor // // Created by Hoon H. on 11/11/14. // Copyright (c) 2014 Eonil. All rights reserved. // import Foundation import AppKit extension NSSplitViewController { public func addChildViewControllerAsASplitViewItem(childViewController: NSViewController) { self.addChildViewController(childViewController) self.addSplitViewItem(NSSplitViewItem(viewController: childViewController)) } } extension NSViewController { // var childViewControllers:[NSViewController] { // get { // // } // } func indexOfChildViewController(vc:NSViewController) -> Int? { for i in 0..<self.childViewControllers.count { let vc1 = self.childViewControllers[i] as NSViewController if vc1 === vc { return i } } return nil } func removeChildViewController<T:NSViewController>(vc:T) { precondition(vc.parentViewController === self, "The view-controller is not a child of this view-controller.") if let idx1 = self.indexOfChildViewController(vc) { self.removeChildViewControllerAtIndex(idx1) } else { fatalError("The view-controller is not a child of this view-controller.") } } } extension NSView { var layoutConstraints:[NSLayoutConstraint] { get { return self.constraints as [NSLayoutConstraint] } set(v) { let cs1 = self.constraints self.removeConstraints(cs1) assert(self.constraints.count == 0) self.addConstraints(v as [AnyObject]) } } } extension NSTextView { // var selectedRanges:[NSRange] { // get { // return self.selectedRanges.map({$0.rangeValue}) // } // set(v) { // self.selectedRanges = v.map({NSValue(range: $0)}) // } // } } extension NSTableColumn { convenience init(identifier:String, title:String) { self.init(identifier: identifier) self.title = title } convenience init(identifier:String, title:String, width:CGFloat) { self.init(identifier: identifier) self.title = title self.width = width } } extension NSLayoutManager { } extension NSMenu { func addSeparatorItem() { let m = NSMenuItem.separatorItem() self.addItem(m) } } extension NSMenuItem { var reaction:(()->())? { get { let c1 = ObjC.getStrongAssociationOf(self, key: Keys.MENU_REACTION) as TargetActionFunctionBox? return c1?.function } set(v) { let c1 = v == nil ? nil as TargetActionFunctionBox? : TargetActionFunctionBox(v!) self.target = c1 self.action = c1 == nil ? "" : c1!.action ObjC.setStrongAssociationOf(self, key: Keys.MENU_REACTION, value: c1) } } private struct Keys { static let MENU_REACTION = UnsafeMutablePointer<Void>.alloc(1) } convenience init(title:String, reaction:()->()) { self.init() self.title = title self.reaction = reaction } } extension NSColor { class func withUInt8Components(red r:UInt8, green g:UInt8, blue b:UInt8, alpha a:UInt8) -> NSColor { return NSColor(SRGBRed: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a) / 255.0) } }
mit
98645ab9e8fc5e4ded090d088f5a197e
20.955882
125
0.700938
3.210753
false
false
false
false
alessiobrozzi/firefox-ios
Shared/Extensions/UIImageExtensions.swift
8
2440
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import WebImage private let imageLock = NSLock() extension UIImage { /// Despite docs that say otherwise, UIImage(data: NSData) isn't thread-safe (see bug 1223132). /// As a workaround, synchronize access to this initializer. /// This fix requires that you *always* use this over UIImage(data: NSData)! public static func imageFromDataThreadSafe(_ data: Data) -> UIImage? { imageLock.lock() let image = UIImage(data: data) imageLock.unlock() return image } /// Generates a UIImage from GIF data by calling out to SDWebImage. The latter in turn uses UIImage(data: NSData) /// in certain cases so we have to synchronize calls (see bug 1223132). public static func imageFromGIFDataThreadSafe(_ data: Data) -> UIImage? { imageLock.lock() let image = UIImage.sd_animatedGIF(with: data) imageLock.unlock() return image } public static func dataIsGIF(_ data: Data) -> Bool { guard data.count > 3 else { return false } // Look for "GIF" header to identify GIF images var header = [UInt8](repeating: 0, count: 3) data.copyBytes(to: &header, count: 3 * MemoryLayout<UInt8>.size) return header == [0x47, 0x49, 0x46] } public static func createWithColor(_ size: CGSize, color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) let context = UIGraphicsGetCurrentContext() let rect = CGRect(origin: CGPoint.zero, size: size) color.setFill() context!.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } public func createScaled(_ size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage! } public static func templateImageNamed(_ name: String) -> UIImage? { return UIImage(named: name)?.withRenderingMode(.alwaysTemplate) } }
mpl-2.0
25fba4f64aac4f80afa6463a6f259016
37.125
117
0.661885
4.603774
false
false
false
false
cybertunnel/SplashBuddy
SplashBuddy/SoftwareArray.swift
1
1812
// // SoftwareArray.swift // SplashBuddy // // Created by Francois Levaux on 02.03.17. // Copyright © 2017 François Levaux-Tiffreau. All rights reserved. // import Cocoa class SoftwareArray: NSObject { static let sharedInstance = SoftwareArray() dynamic var array = [Software]() { didSet { self.checkSoftwareStatus() } } func failedSoftwareArray(_ _array: [Software] = SoftwareArray.sharedInstance.array) -> [Software] { return _array.filter({ $0.status == .failed }) } func canContinue(_ _array: [Software] = SoftwareArray.sharedInstance.array) -> Bool { guard Preferences.sharedInstance.doneParsingPlist == true else { return false } let criticalSoftwareArray = _array.filter({ $0.canContinue == false }) return criticalSoftwareArray.filter({ $0.status == .success }).count == criticalSoftwareArray.count } func allInstalled(_ _array: [Software] = SoftwareArray.sharedInstance.array) -> Bool { let displayedSoftwareArray = _array.filter({ $0.displayToUser == true }) return displayedSoftwareArray.filter({ $0.status == .success }).count == displayedSoftwareArray.count } func checkSoftwareStatus() { if self.failedSoftwareArray().count > 0 { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "errorWhileInstalling"), object: nil) } if self.canContinue() { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "canContinue"), object: nil) } if self.allInstalled() { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "doneInstalling"), object: nil) } } }
apache-2.0
eb23f5c7f2923416deab1dd64d9e1b3a
30.754386
117
0.629282
4.664948
false
false
false
false
benlangmuir/swift
test/Sema/diag_type_conversion.swift
6
3067
// RUN: %target-typecheck-verify-swift %clang-importer-sdk // REQUIRES: objc_interop import Foundation func foo1(_ a: [Int]) {} func foo2(_ a : UnsafePointer<Int>) {} func foo4(_ a : UnsafeMutablePointer<Int>) {} func foo3 () { let j = 3 foo2(j) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UnsafePointer<Int>'}} {{none}} foo4(j) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UnsafeMutablePointer<Int>'}} {{none}} var i = 3 foo2(i) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UnsafePointer<Int>'}} {{8-8=&}} foo4(i) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UnsafeMutablePointer<Int>'}} {{8-8=&}} foo2(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UnsafePointer<Int>'}} {{none}} foo4(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UnsafeMutablePointer<Int>'}} {{none}} } class A {} class B : A {} func foo5(b : B) {} func foo6(a : A) { foo5(b : a) // expected-error {{cannot convert value of type 'A' to expected argument type 'B'}} {{13-13= as! B}} } func foo7(b : [B]) {} func foo8(a : [A]) { // TODO(diagnostics): Since `A` and `B` are related it would make sense to suggest forced downcast. foo7(b : a) // expected-error {{cannot convert value of type '[A]' to expected argument type '[B]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('A' and 'B') are expected to be equal}} } protocol P1 {} struct S1 : P1 {} func foo9(s : S1) {} func foo10(p : P1) { foo9(s : p) // expected-error {{cannot convert value of type 'any P1' to expected argument type 'S1'}} {{13-13= as! S1}} } func foo11(a : [AnyHashable]) {} func foo12(b : [NSObject]) { foo11(a : b) } func foo13(a : [AnyHashable : Any]) {} func foo14(b : [NSObject : AnyObject]) { foo13(a : b) } // Add a minimal test for inout-to-pointer conversion involving a // generic function with a protocol constraint of Equatable. infix operator =*= : ComparisonPrecedence func =*= <T : Equatable>(lhs: T, rhs: T) -> Bool { return lhs == rhs } func =*= <T : Equatable>(lhs: T?, rhs: T?) -> Bool { return lhs == rhs } class C {} var o = C() var p: UnsafeMutablePointer<C>? = nil _ = p =*= &o func rdar25963182(_ bytes: [UInt8] = nil) {} // expected-error@-1 {{nil default argument value cannot be converted to type}} // SR-13262 struct SR13262_S {} func SR13262(_ x: Int) {} func SR13262_Int(_ x: Int) -> Int { 0 } func SR13262_SF(_ x: Int) -> SR13262_S { SR13262_S() } func testSR13262(_ arr: [Int]) { for x in arr where SR13262(x) {} // expected-error {{cannot convert value of type '()' to expected condition type 'Bool'}} for x in arr where SR13262_Int(x) {} // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} {{22-22=(}} {{36-36= != 0)}} for x in arr where SR13262_SF(x) {} // expected-error {{cannot convert value of type 'SR13262_S' to expected condition type 'Bool'}} }
apache-2.0
21aec678e4d73d1ef59f5fa80db7b1db
34.252874
154
0.651451
3.245503
false
false
false
false
mshhmzh/firefox-ios
Client/Frontend/Settings/SearchEnginePicker.swift
4
2209
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit class SearchEnginePicker: UITableViewController { weak var delegate: SearchEnginePickerDelegate? var engines: [OpenSearchEngine]! var selectedSearchEngineName: String? override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("Default Search Engine", comment: "Title for default search engine picker.") navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .Plain, target: self, action: #selector(SearchEnginePicker.cancel)) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return engines.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let engine = engines[indexPath.item] let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) cell.textLabel?.text = engine.shortName cell.imageView?.image = engine.image.createScaled(CGSize(width: OpenSearchEngine.PreferredIconSize, height: OpenSearchEngine.PreferredIconSize)) if engine.shortName == selectedSearchEngineName { cell.accessoryType = UITableViewCellAccessoryType.Checkmark } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let engine = engines[indexPath.item] delegate?.searchEnginePicker(self, didSelectSearchEngine: engine) tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.Checkmark } override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.None } func cancel() { delegate?.searchEnginePicker(self, didSelectSearchEngine: nil) } }
mpl-2.0
ef336e59ba2fd5fac49b08a2a0992bf9
46
205
0.741512
5.606599
false
false
false
false
novi/i2c-swift-example
Sources/I2CDeviceModule/Device.swift
1
1644
// // Device.swift // I2CDeviceModule // // Created by Yusuke Ito on 12/17/16. // Copyright © 2016 Yusuke Ito. All rights reserved. // import Foundation import I2C public final class DeviceWrap: I2CDevice { private let device: I2CDevice public init<D: I2CDevice>(_ d: D) { self.device = d } public func write(toAddress: UInt8, data: [UInt8]) throws { try device.write(toAddress: toAddress, data: data) } public func write(toAddress: UInt8, data: [UInt8], readBytes: UInt32) throws -> [UInt8] { return try device.write(toAddress: toAddress, data: data, readBytes: readBytes) } } fileprivate func getCommandArgs() -> [String: String] { var args = CommandLine.arguments args.removeFirst() // cmd[0] is program name var result: [String: String] = [:] for arg in args { let parts = arg.components(separatedBy: "=") if parts.count == 2 { result[parts[0].lowercased()] = parts[1] } } return result } #if os(Linux) public func getCurrentI2CDevice() throws -> DeviceWrap { if let port = getCommandArgs()["i2cnum"], let portNum = UInt(port) { return DeviceWrap(try I2CBusDevice(portNumber: UInt8(portNum) )) } for i in 0..<10 { if FileManager.default.fileExists(atPath: "/dev/i2c-\(i)") { print("/dev/i2c-\(i) found") return DeviceWrap(try I2CBusDevice(portNumber: UInt8(i) )) } } fatalError("no i2c device file") } #else public func getCurrentI2CDevice() throws -> DeviceWrap { return try DeviceWrap(I2CTinyUSB()) } #endif
mit
432aff64b6317b634f248f1cf1d1c1b2
24.671875
93
0.61899
3.651111
false
false
false
false
Hexaville/HexavilleAuth
Sources/HexavilleAuth/Providers/OAuth2/GithubAuthorizationProvider.swift
1
2174
// // GithubAuthorizationProvider.swift // HexavilleAuth // // Created by Yuki Takei on 2017/05/31. // // import Foundation import HexavilleFramework public enum GithubAuthorizationProviderError: Error { case bodyShouldBeAJSON } public struct GithubAuthorizationProvider: OAuth2AuthorizationProvidable { public let path: String public let oauth: OAuth2 public let callback: RespodWithCredential public init(path: String, consumerKey: String, consumerSecret: String, callbackURL: CallbackURL, blockForCallbackURLQueryParams: ((Request) -> [URLQueryItem])? = nil, scope: String, callback: @escaping RespodWithCredential) { self.path = path self.oauth = OAuth2( consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeURL: "http://github.com/login/oauth/authorize", accessTokenURL: "https://github.com/login/oauth/access_token", callbackURL: callbackURL, blockForCallbackURLQueryParams: blockForCallbackURLQueryParams, scope: scope ) self.callback = callback } public func authorize(for request: Request) throws -> (Credential, LoginUser) { let credential = try self.getAccessToken(for: request) let url = URL(string: "https://api.github.com/user?access_token=\(credential.accessToken)")! let (response, body) = try HTTPClient().send(url: url) guard (200..<300).contains(response.statusCode) else { throw HexavilleAuthError.responseError(response, body) } guard let json = try JSONSerialization.jsonObject(with: body, options: []) as? [String: Any] else { throw GithubAuthorizationProviderError.bodyShouldBeAJSON } let user = LoginUser( id: String(json["id"] as? Int ?? 0), name: json["login"] as? String ?? "", screenName: json["name"] as? String, email: json["email"] as? String, picture: json["avatar_url"] as? String, raw: json ) return (credential, user) } }
mit
ff4c579b52d9a89e6a0b56ea22313b57
32.96875
229
0.630635
4.726087
false
false
false
false
alvarorgtr/swift_data_structures
DataStructures/LabelledGraph.swift
1
4240
// // Graph.swift // DataStructures // // Created by Álvaro Rodríguez García on 23/3/17. // Copyright © 2017 DeltaApps. All rights reserved. // import Foundation fileprivate typealias TreeMap<Key: Comparable, Value> = AVLTreeMap<Key, Value> /** Implementation of a undirected, unweighted graph via adjacency lists. For the label management we are using the Sedgewick et al. implementation. Possible anomalies: parallel edges, self-loops */ public struct LabelledGraph<Label: Hashable> { public typealias Vertex = Label public typealias Edge = GraphEdge<Int> internal var edges: [List<Edge>] internal var vertices: [Vertex] internal var keys: [Vertex: Int] public private(set) var edgeCount: Int = 0 public var vertexCount: Int { return vertices.count } // MARK: Initializers init() { edges = [] vertices = [] keys = [:] } init <E: Sequence>(edges: E) where E.Iterator.Element == (Vertex, Vertex) { self.init() for edge in edges { addEdge(from: edge.0, to: edge.1) } } init<V: Sequence, E: Sequence>(vertices: V, edges: E) where V.Iterator.Element == Vertex, E.Iterator.Element == (Vertex, Vertex) { self.vertices = [Vertex](vertices) self.edges = Array(repeating: List<Edge>(), count: self.vertices.count) keys = [:] for (index, vertex) in self.vertices.enumerated() { keys[vertex] = index } for edgeTuple in edges { if let from = keys[edgeTuple.0], let to = keys[edgeTuple.1] { let edge1 = Edge(from: from, to: to) let edge2 = Edge(from: to, to: from) self.edges[edge1.from].appendLast(edge1) self.edges[edge2.from].appendLast(edge2) edgeCount += 1 } else { fatalError("Unknown vertex in edge") } } } // MARK: Accessors public func degree(of vertex: Vertex) -> Int { precondition(keys[vertex] != nil, "The vertex must be in the graph") return edges[keys[vertex]!].count } public func adjacentVertices(to vertex: Vertex) -> AnySequence<Vertex> { precondition(keys[vertex] != nil, "The vertex must be in the graph") return AnySequence<Vertex>(self.edges[keys[vertex]!].map({ (edge) -> Vertex in return self.vertices[edge.to] })) } public func areAdjacent(_ v: Vertex, _ w: Vertex) -> Bool { guard let vIndex = keys[v], let wIndex = keys[w] else { return false } let adjacency = edges[vIndex] for edge in adjacency { if edge.to == wIndex { return true } } return false } // MARK: Mutators /** Adds a vertex to the graph if it isn't already there. - parameter vertex: the vertex to be added. - returns: the index of the vertex. - complexity: Amortized O(1) */ @discardableResult public mutating func add(vertex: Vertex) -> Int { if let index = keys[vertex] { return index } else { vertices.append(vertex) edges.append(List<Edge>()) keys[vertex] = vertexCount - 1 return vertexCount - 1 } } /** Adds the edge from-to to the graph and the corresponding vertices if needed. Since the graph is not directed the to-from edge is also added. - parameter from: the first vertex - parameter to: the second vertex - warning: this function doesn't check for parallel vertices. */ public mutating func addEdge(from: Vertex, to: Vertex) { // Won't add if already there let fromInt = add(vertex: from) let toInt = add(vertex: to) let edge1 = Edge(from: fromInt, to: toInt) let edge2 = Edge(from: toInt, to: fromInt) edges[fromInt].appendLast(edge1) edges[toInt].appendLast(edge2) edgeCount += 1 } /** Adds the edge from-to to the graph and the corresponding vertices if needed. Since the graph is not directed the to-from edge is also added. - parameter edge: the edge. - warning: this function doesn't check for parallel vertices. */ public mutating func add(edge: GraphEdge<Vertex>) { addEdge(from: edge.from, to: edge.to) } } extension LabelledGraph: GraphCollection { public typealias Element = Label public typealias Index = Int public typealias Iterator = AnyIterator<Vertex> public func vertex(for index: Int) -> Element { return vertices[index] } public func index(for vertex: Vertex) -> Int { precondition(keys[vertex] != nil, "The vertex doesn't exist") return keys[vertex]! } }
gpl-3.0
849a5cfe665173fb69272d0c4d1eb7c3
25.310559
145
0.6839
3.311962
false
false
false
false
CosmicMind/MaterialKit
Sources/iOS/ImageCard.swift
1
3416
/* * Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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 HOLDER 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 UIKit open class ImageCard: Card { /** A Display value to indicate whether or not to display the imageView to the full view bounds. */ open var displayStyle = DisplayStyle.partial { didSet { layoutSubviews() } } /// A preset wrapper around imageViewEdgeInsets. open var imageViewEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { imageViewEdgeInsets = EdgeInsetsPresetToValue(preset: imageViewEdgeInsetsPreset) } } /// A reference to imageViewEdgeInsets. @IBInspectable open var imageViewEdgeInsets = EdgeInsets.zero { didSet { layoutSubviews() } } /// A reference to the imageView. @IBInspectable open var imageView: UIImageView? { didSet { oldValue?.removeFromSuperview() if let v = imageView { container.addSubview(v) } layoutSubviews() } } /// An ImageCardToolbarAlignment value. open var toolbarAlignment = ToolbarAlignment.bottom { didSet { layoutSubviews() } } /// Reloads the view. open override func reload() { var h: CGFloat = 0 if let v = imageView { h = prepare(view: v, with: imageViewEdgeInsets, from: h) container.sendSubview(toBack: v) } if let v = toolbar { prepare(view: v, with: toolbarEdgeInsets, from: h) v.frame.origin.y = .top == toolbarAlignment ? toolbarEdgeInsets.top : h - v.bounds.height - toolbarEdgeInsets.bottom container.bringSubview(toFront: v) } if let v = contentView { h = prepare(view: v, with: contentViewEdgeInsets, from: h) } if let v = bottomBar { h = prepare(view: v, with: bottomBarEdgeInsets, from: h) } container.frame.size.height = h bounds.size.height = h } }
bsd-3-clause
2e9d2c4a7a188734625790555a842d60
30.925234
122
0.696429
4.560748
false
false
false
false
nickygerritsen/Timepiece
Sources/Duration.swift
2
1515
// // Duration.swift // Timepiece // // Created by Naoto Kaneko on 2014/08/17. // Copyright (c) 2014年 Naoto Kaneko. All rights reserved. // import Foundation prefix func - (duration: Duration) -> (Duration) { return Duration(value: -duration.value, unit: duration.unit) } public class Duration { public let value: Int public let unit: NSCalendarUnit private let calendar = NSCalendar.currentCalendar() /** Initialize a date before a duration. */ public var ago: NSDate { return ago(from: NSDate()) } public func ago(from date: NSDate) -> NSDate { return calendar.dateByAddingDuration(-self, toDate: date, options: .SearchBackwards)! } /** Initialize a date after a duration. */ public var later: NSDate { return later(from: NSDate()) } public func later(from date: NSDate) -> NSDate { return calendar.dateByAddingDuration(self, toDate: date, options: .SearchBackwards)! } /** This conversion is deprecated in 0.4.1 and will be obsoleted in 0.5.0. This operation is performed under incorrect assumption that 1 month is always equal to 30 days. */ @availability(*, deprecated=0.4.1) public lazy var interval: NSTimeInterval = { [unowned self] in return self.unit.interval * NSTimeInterval(self.value) }() public init(value: Int, unit: NSCalendarUnit) { self.value = value self.unit = unit } }
mit
40314fa2a547c4eff571aadb655d29c2
26.017857
103
0.632518
4.322857
false
false
false
false
trentrand/WWDC-2015-Scholarship
Trent Rand/AppDelegate.swift
1
3483
// // AppDelegate.swift // Trent Rand // // Created by Trent Rand on 4/15/15. // Copyright (c) 2015 Trent Rand. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var slideMenuVC: HKSlideMenu3DController! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Set status bar to light UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false) slideMenuVC = HKSlideMenu3DController() slideMenuVC.view.frame = UIScreen.mainScreen().bounds let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let menuVC: AnyObject! = mainStoryboard.instantiateViewControllerWithIdentifier("menuVC") let navMain: AnyObject! = mainStoryboard.instantiateViewControllerWithIdentifier("navVC") self.slideMenuVC.menuViewController = menuVC as! MenuViewController self.slideMenuVC.mainViewController = navMain as! UINavigationController self.slideMenuVC.backgroundImage = UIImage(named: "background.jpg") self.slideMenuVC.backgroundImageContentMode = UIViewContentMode.ScaleToFill self.slideMenuVC.enablePan = true; self.window?.rootViewController = self.slideMenuVC self.window?.makeKeyAndVisible() return true } class func mainDelegate() -> AppDelegate { return UIApplication.sharedApplication().delegate as! AppDelegate } 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:. } }
mit
6590dcc6e45cdaf2ae3a5e610529a965
44.828947
285
0.726098
5.757025
false
false
false
false