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
Corey2121/the-oakland-post
The Oakland Post/SignUpViewController.swift
3
6334
// // SignUpViewController.swift // The Oakland Post // // A simple signup form. // // Created by Andrew Clissold on 8/24/14. // Copyright (c) 2014 Andrew Clissold. All rights reserved. // import UIKit class SignUpViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var confirmPasswordTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var signUpButton: UIButton! @IBOutlet weak var signUpActivityIndicator: UIActivityIndicatorView! var keyboardWasPresent = false override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .Done, target: self, action: "dismiss") usernameTextField.delegate = self passwordTextField.delegate = self confirmPasswordTextField.delegate = self emailTextField.delegate = self } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if UIDevice.currentDevice().userInterfaceIdiom != .Pad { registerForKeyboardNotifications() } } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver( self, name: UIKeyboardDidShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver( self, name: UIKeyboardWillHideNotification, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) findAndResignFirstResponder() } func registerForKeyboardNotifications() { NSNotificationCenter.defaultCenter().addObserver( self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver( self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } var insets = UIEdgeInsetsZero func keyboardDidShow(notification: NSNotification) { if navigationController == nil { // Occurs when a screen edge pan gesture is initiated but canceled, // so insets will already have been set. scrollView.contentInset = insets scrollView.scrollIndicatorInsets = insets return } let info = notification.userInfo! let keyboardHeight = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue().size.height let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height let navBarHeight = navigationController!.navigationBar.frame.size.height let top = statusBarHeight + navBarHeight let bottom = keyboardHeight insets = UIEdgeInsets(top: top, left: 0, bottom: bottom, right: 0) UIView.animateWithDuration(0.3) { self.scrollView.contentInset = self.insets self.scrollView.scrollIndicatorInsets = self.insets } } func keyboardWillHide(notification: NSNotification) { if navigationController == nil { return } // avoid crash let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height let navBarHeight = navigationController!.navigationBar.frame.size.height let top = statusBarHeight + navBarHeight let insets = UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0) scrollView.contentInset = insets scrollView.scrollIndicatorInsets = insets } var count = 0 override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if ++count == 2 || (count == 4 && keyboardWasPresent) { let viewHeight = view.frame.size.height let viewWidth = view.frame.size.width var navBarHeight = navigationController!.navigationBar.frame.size.height if UIDevice.currentDevice().userInterfaceIdiom != .Pad { let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height navBarHeight += statusBarHeight } scrollView.contentSize = CGSize(width: viewWidth, height: viewHeight-navBarHeight) } } func textFieldShouldReturn(textField: UITextField) -> Bool { if let nextResponder = textField.superview?.viewWithTag(textField.tag + 1) { nextResponder.becomeFirstResponder() } else if textField === emailTextField { hideKeyboardAndSignUp() } return false } @IBAction func hideKeyboardAndSignUp() { findAndResignFirstResponder() signUpButton.enabled = false signUpActivityIndicator.startAnimating() var user = PFUser() user.username = usernameTextField.text user.password = passwordTextField.text user.email = emailTextField.text let confirmPassword = confirmPasswordTextField.text if valid(user, confirmPassword) { user.signUpInBackgroundWithBlock { (succeeded, error) in if succeeded { homeViewController.reloadData() homeViewController.navigationItem.rightBarButtonItem = homeViewController.favoritesBarButtonItem self.dismiss() } else { showAlertForErrorCode(error!.code) self.signUpActivityIndicator.stopAnimating() self.signUpButton.enabled = true } } } else { self.signUpActivityIndicator.stopAnimating() self.signUpButton.enabled = true } } func findAndResignFirstResponder() { for textField in [usernameTextField, passwordTextField, confirmPasswordTextField, emailTextField] { if textField.isFirstResponder() { textField.resignFirstResponder() return } } } func dismiss() { findAndResignFirstResponder() dismissViewControllerAnimated(true, completion: nil) } }
bsd-3-clause
267b9dec8e6d825c21d3dc4ae0ebbe85
35.612717
107
0.65851
6.032381
false
false
false
false
pencildrummer/TwilioLookup
TwilioLookup/Sources/TwilioCarrier.swift
1
1755
// // TwilioCarrier.swift // Pods // // Created by Fabio Borella on 22/06/16. // // import Foundation /** Available types of carrier */ public enum TwilioCarrierType: String { /// The phone number is a landline number generally not capable of receiving SMS messages. case Landline = "landline" /// The phone number is a mobile number generally capable of receiving SMS messages. case Mobile = "mobile" /// An internet based phone number that may or may not be capable of receiving SMS messages. For example, Google Voice. case Voip = "voip" } /** Available types of carrier caller */ public enum TwilioCarrierCallerType: String { /// The carrier caller is not available case Unavailable = "unavailable" /// The carrier caller is a business number case Business = "business" /// The carrier caller is a consumer number case Consumer = "consumer" } /** The carrier of a certain phone number - seealso: TwilioLookupResponse */ open class TwilioCarrier { /** The mobile country code of the carrier (for mobile numbers only). */ open var mobileCountryCode: String! /** The mobile network code of the carrier (for mobile numbers only). */ open var mobileNetworkCode: String! /** The name of the carrier. Please bear in mind that carriers rebrand themselves constantly and that the names used for carriers will likely change over time. */ open var name: String! /** The phone number type. See `TwilioCarrierType` for more information. */ open var type: TwilioCarrierType! /** The error code, if any, associated with your request. */ open var errorCode: TwilioErrorCode? }
mit
3c18010c80da2c584da070c0c98f6e86
25.19403
161
0.671795
4.488491
false
false
false
false
kongtomorrow/ProjectEuler-Swift
ProjectEuler/main.swift
1
1259
// // main.swift // ProjectEuler // // Created by Ken Ferry on 8/7/14. // Copyright (c) 2014 Understudy. All rights reserved. // import Foundation import dispatch @objc class Problems { func methodsStartingWithPrefix(prefix:String)->[String] { var count:UInt32 = 0 let methods = class_copyMethodList(Problems.self, &count) var methodNames = [String]() for i in 0..<Int(count) { let methName = method_getName(methods[i]).description methodNames.append(methName) } free(methods) return methodNames.filter({($0 as NSString).hasPrefix(prefix)}).sorted({ (a, b) -> Bool in return (a as NSString).localizedStandardCompare(b) == NSComparisonResult.OrderedAscending }) } func benchmarkProblem(methName:String) { benchmark(methName) { ()->Int in return FThePolice.sendProblemMessage(Selector(methName), toObject: self) } } } let probs = Problems() probs.methodsStartingWithPrefix("p").map({probs.benchmarkProblem($0)}) probs.methodsStartingWithPrefix("run").map({probs.benchmarkProblem($0)}) //probs.benchmarkProblem(probs.methodsStartingWithPrefix("p").last!) // just the last problem
mit
61ad7bc6b7a88be601668918049d2a18
29.707317
101
0.647339
4.100977
false
false
false
false
strike65/SwiftyStats
SwiftyStats/CommonSource/DataFrame/SSDataFrame.swift
1
30013
// // SSDataFrame.swift // SwiftyStats /* Copyright (2017-2019) strike65 GNU GPL 3+ 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, version 3 of the License. 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 Foundation #if os(macOS) || os(iOS) import os.log #endif /// Defines a structure holding multiple SSExamine objects: /// Each column contains an SSExamine object. /// /// Each COL represents a single SSExamine object. The structure of the dataframe is like a two-dimensional table: /// /// With N = sampleSize: /// /// < COL[0] COL[1] ... COL[columns - 1] > /// tags tags[0] tags[1] ... tags[columns - 1] /// cnames cnames[0 cnames[1] ... cnames[columns - 1] /// ROW0 data[0][0] data[0][1] ... data[0][columns - 1] /// ROW1 data[1][0] data[1][1] ... data[1][columns - 1] /// ... .......... .......... ... .................... /// ROWN data[N][0] data[N][1] ... data[N][columns - 1] /// public class SSDataFrame<SSElement, FPT: SSFloatingPoint>: NSObject, NSCopying, Codable, NSMutableCopying, SSDataFrameContainer where SSElement: Comparable, SSElement: Hashable, SSElement: Codable, FPT: Codable { // public typealias Examine = SSExamine<SSElement, Double> // coding keys private enum CodingKeys: String, CodingKey { case data = "ExamineArray" case tags case cnames case nrows case ncolumns } /// Required func to conform to Codable protocol public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(self.data, forKey: .data) try container.encodeIfPresent(self.tags, forKey: .tags) try container.encodeIfPresent(self.cNames, forKey: .cnames) try container.encodeIfPresent(self.rows, forKey: .nrows) try container.encodeIfPresent(self.cols, forKey: .ncolumns) } /// Required func to conform to Codable protocol public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if let d = try container.decodeIfPresent(Array<SSExamine<SSElement, FPT>>.self, forKey: .data) { self.data = d } if let t = try container.decodeIfPresent(Array<String>.self, forKey: .tags) { self.tags = t } if let n = try container.decodeIfPresent(Array<String>.self, forKey: .cnames) { self.cNames = n } if let r = try container.decodeIfPresent(Int.self, forKey: .nrows) { self.rows = r } if let c = try container.decodeIfPresent(Int.self, forKey: .ncolumns) { self.cols = c } } #if os(macOS) || os(iOS) // @available(macOS 10.12, iOS 10, *) /// Saves the dataframe to filePath using JSONEncoder /// - Parameter path: The full qualified filename. /// - Parameter overwrite: If true, file will be overwritten. /// - Throws: SSSwiftyStatsError.posixError (file can't be removed), SSSwiftyStatsError.directoryDoesNotExist, SSSwiftyStatsError.fileNotReadable public func archiveTo(filePath path: String!, overwrite: Bool!) throws -> Bool { let fm: FileManager = FileManager.default let fullFilename: String = NSString(string: path).expandingTildeInPath let dir: String = NSString(string: fullFilename).deletingLastPathComponent var isDir = ObjCBool(false) if !fm.fileExists(atPath: dir, isDirectory: &isDir) { if !isDir.boolValue || path.count == 0 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("No writeable path found", log: .log_fs ,type: .error) } #endif throw SSSwiftyStatsError(type: .directoryDoesNotExist, file: #file, line: #line, function: #function) } #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("File doesn't exist", log: .log_fs ,type: .error) } #endif throw SSSwiftyStatsError(type: .fileNotFound, file: #file, line: #line, function: #function) } if fm.fileExists(atPath: fullFilename) { if overwrite { if fm.isWritableFile(atPath: fullFilename) { do { try fm.removeItem(atPath: fullFilename) } catch { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Unable to remove file prior to saving new file: %@", log: .log_fs ,type: .error, error.localizedDescription) } #endif throw SSSwiftyStatsError(type: .fileNotWriteable, file: #file, line: #line, function: #function) } } else { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Unable to remove file prior to saving new file", log: .log_fs ,type: .error) } #endif throw SSSwiftyStatsError(type: .fileNotWriteable, file: #file, line: #line, function: #function) } } else { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("File exists: %@", log: .log_fs ,type: .error, fullFilename) } #endif throw SSSwiftyStatsError(type: .fileExists, file: #file, line: #line, function: #function) } } let jsonEncode = JSONEncoder() let d = try jsonEncode.encode(self) do { try d.write(to: URL.init(fileURLWithPath: fullFilename), options: Data.WritingOptions.atomic) return true } catch { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Unable to write data", log: .log_fs, type: .error) } #endif return false } } // @available(macOS 10.10, iOS 10, *) /// Initializes a new dataframe from an archive saved by archiveTo(filePath path:overwrite:). /// - Parameter path: The full qualified filename. /// - Throws: SSSwiftyStatError.fileNotReadable public class func unarchiveFrom(filePath path: String!) throws -> SSDataFrame<SSElement, FPT>? { let fm: FileManager = FileManager.default let fullFilename: String = NSString(string: path).expandingTildeInPath if !fm.isReadableFile(atPath: fullFilename) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("File not readable", log: .log_fs ,type: .error) } #endif throw SSSwiftyStatsError(type: .fileNotFound, file: #file, line: #line, function: #function) } do { let data: Data = try Data.init(contentsOf: URL.init(fileURLWithPath: fullFilename)) let jsonDecoder = JSONDecoder() let result = try jsonDecoder.decode(SSDataFrame<SSElement, FPT>.self, from: data) return result } catch { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Failure", log: .log_fs ,type: .error) } #endif return nil } } #endif private var data:Array<SSExamine<SSElement, FPT>> = Array<SSExamine<SSElement, FPT>>() private var tags: Array<String> = Array<String>() private var cNames: Array<String> = Array<String>() private var rows: Int = 0 private var cols: Int = 0 /// Array containing all SSExamine objects public var examines: Array<SSExamine<SSElement, FPT>> { get { return data } } /// Number of rows per column (= sample size) public var sampleSize: Int { get { return rows } } /// Returns true if the receiver is equal to `object`. public override func isEqual(_ object: Any?) -> Bool { var result: Bool = true if let df: SSDataFrame<SSElement, FPT> = object as? SSDataFrame<SSElement, FPT> { if self.columns == df.columns && self.rows == df.rows { for k in 0..<self.columns { result = result && self[k].isEqual(df[k]) } return result } else { return false } } else { return false } } /// Number of samples (Same as `columns`) public var countOfSamples: Int { get { return cols } } /// Number of samples (Same as `countOfSamples`) public var columns: Int { get { return cols } } /// Returns true, if the receiver is empty (i.e. there are no data) public var isEmpty: Bool { get { return rows == 0 && cols == 0 } } /// Initializes a new instance and returns that instance in a fully initialized state /// - Parameter examineArray: An Array of SSEXamine objects /// - Throws: SSSwiftyStatsError init(examineArray: Array<SSExamine<SSElement, FPT>>!) throws { let tempSampleSize = examineArray.first!.sampleSize data = Array<SSExamine<SSElement, FPT>>.init() tags = Array<String>() cNames = Array<String>() var i: Int = 0 for a in examineArray { if a.sampleSize != tempSampleSize { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Sample sizes are expected to be equal", log: .log_stat, type: .error) } #endif data.removeAll() tags.removeAll() cNames.removeAll() rows = 0 cols = 0 throw SSSwiftyStatsError.init(type: .invalidArgument, file: #file, line: #line, function: #function) } i += 1 data.append(a) if let t = a.tag { tags.append(t) } else { tags.append("NA") } if let n = a.name { if let _ = cNames.firstIndex(of: n) { var k: Int = 1 var tempSampleString = n + "_" + String(format: "%02d", arguments: [k as CVarArg]) while (cNames.firstIndex(of: tempSampleString) != nil) { k += 1 tempSampleString = n + "_" + String(format: "%02d", arguments: [k as CVarArg]) } cNames.append(tempSampleString) } else { cNames.append(n) } } else { cNames.append(String(format: "%03d", arguments: [i as CVarArg])) } } rows = tempSampleSize cols = i super.init() } /// Required initializer override public init() { cNames = Array<String>() tags = Array<String>() data = Array<SSExamine<SSElement, FPT>>() rows = 0 cols = 0 super.init() } /// Appends a column /// - Parameter examine: The SSExamine object /// - Parameter name: Name of column /// - Throws: SSSwiftyStatsError examine.sampleSize != self.rows public func append(_ examine: SSExamine<SSElement, FPT>, name: String?) throws { if examine.sampleSize != self.rows { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Sample sizes are expected to be equal", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .invalidArgument, file: #file, line: #line, function: #function) } self.data.append(examine) if let t = examine.tag { self.tags.append(t) } else { self.tags.append("NA") } if let n = examine.name { self.cNames.append(n) } else { cNames.append(String(format: "%03d", arguments: [(self.cols + 1) as CVarArg] )) } cols += 1 } /// Removes all columns public func removeAll() { data.removeAll() cNames.removeAll() tags.removeAll() cols = 0 rows = 0 } /// Removes a column /// - Parameter name: Name of column /// - Returns: the removed column oe nil public func remove(name: String!) -> SSExamine<SSElement, FPT>? { if cols > 0 { if let i = cNames.firstIndex(of: name) { cNames.remove(at: i) tags.remove(at: i) cols -= 1 rows -= 1 return data.remove(at: i) } else { return nil } } else { return nil } } private func isValidColumnIndex(_ index: Int) -> Bool { return (index >= 0 && index < self.columns) ? true : false } private func isValidRowIndex(_ index: Int) -> Bool { return (index >= 0 && index < self.rows) ? true : false } private func indexOf(columnName: String!) -> Int? { if let i = cNames.firstIndex(of: columnName) { return i } else { return nil } } /// Returns the row at a given index public func row(at index: Int) -> Array<SSElement> { if isValidRowIndex(index) { var res = Array<SSElement>() for c in self.data { if let e = c[index] { res.append(e) } else { fatalError("Index out of range") } } return res } else { fatalError("Row-Index out of row.") } } /// Accesses the column at a given index public subscript(_ idx: Int) -> SSExamine<SSElement, FPT> { if isValidColumnIndex(idx) { return data[idx] } else { fatalError("Index out of range") } } /// Accesses the column named `name` public subscript(_ name: String) -> SSExamine<SSElement, FPT> { if let i = cNames.firstIndex(of: name) { return data[i] } else { fatalError("Index out of range") } } /// Returns a new instance that’s a copy of the receiver. /// /// The returned object is implicitly retained by the sender, who is responsible for releasing it. The copy returned is immutable if the consideration “immutable vs. mutable” applies to the receiving object; otherwise the exact nature of the copy is determined by the class. /// - Parameters: /// - zone: This parameter is ignored. Memory zones are no longer used by Objective-C. public func copy(with zone: NSZone? = nil) -> Any { do { let res = try SSDataFrame<SSElement, FPT>.init(examineArray: self.data) res.tags = self.tags res.cNames = self.cNames return res } catch { fatalError("Copy failed") } } /// Returns a new instance that’s a mutable copy of the receiver. /// /// The returned object is implicitly retained by the sender, who is responsible for releasing it. The copy returned is immutable if the consideration “immutable vs. mutable” applies to the receiving object; otherwise the exact nature of the copy is determined by the class. In fact, that functions does the same as `copy(with:)` /// - Parameters: /// - zone: This parameter is ignored. Memory zones are no longer used by Objective-C. public func mutableCopy(with zone: NSZone? = nil) -> Any { return self.copy(with: zone) } /// Returns the object returned by `mutableCopy(with:)` where the `zone` is nil. /// /// This is a convenience method for classes that adopt the NSMutableCopying protocol. An exception is raised if there is no implementation for `mutableCopy(with:)`. public override func mutableCopy() -> Any { return self.copy(with: nil) } /// Returns the object returned by `copy(with:) where the `zone` is nil. /// /// This is a convenience method for classes that adopt the NSCopying protocol. An exception is raised if there is no implementation for copy(with:). NSObject does not itself support the NSCopying protocol. Subclasses must support the protocol and implement the copy(with:) method. A subclass version of the copy(with:) method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject. public override func copy() -> Any { return copy(with: nil) } /// Exports the dataframe as csv /// - Parameter path: The full path /// - Parameter atomically: Write atomically /// - Parameter firstRowAsColumnName: If true, the row name is equal to the exported SSExamine object. If this object hasn't a name, an auto incremented integer is used. /// - Parameter useQuotes: If true all fields will be enclosed by quotation marks /// - Parameter overwrite: If true an existing file will be overwritten /// - Parameter stringEncoding: Encoding /// - Returns: True if the file was successfully written. /// - Throws: SSSwiftyStatsError public func exportCSV(path: String!, separator sep: String = ",", useQuotes: Bool = false, firstRowAsColumnName cn: Bool = true, overwrite: Bool = false, stringEncoding enc: String.Encoding = String.Encoding.utf8, atomically: Bool = true) throws -> Bool { if !self.isEmpty { var string = String() if cn { for c in 0..<cols { if useQuotes { string = string + "\"" + cNames[c] + "\"" + sep } else { string = string + cNames[c] + sep } } string = String.init(string.dropLast()) string += "\n" } for r in 0..<self.rows { for c in 0..<self.cols { if useQuotes { string = string + "\"" + "\(String(describing: self.data[c][r]!))" + "\"" + sep } else { string = string + "\(String(describing: self.data[c][r]!))" + sep } } string = String.init(string.dropLast()) string += "\n" } string = String.init(string.dropLast()) let fileManager = FileManager.default let fullName = NSString(string: path).expandingTildeInPath if fileManager.fileExists(atPath: fullName) { if !overwrite { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("File already exists", log: .log_fs, type: .error) } #endif throw SSSwiftyStatsError(type: .fileExists, file: #file, line: #line, function: #function) } else { do { try fileManager.removeItem(atPath: fullName) } catch { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Can't remove file", log: .log_fs, type: .error) } #endif throw SSSwiftyStatsError(type: .fileNotWriteable, file: #file, line: #line, function: #function) } } } var result: Bool do { try string.write(toFile: fullName, atomically: atomically, encoding: enc) result = true } catch { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("File could not be written", log: .log_fs, type: .error) } #endif result = false } return result } else { return false } } /// Initializes a new DataFrame instance. /// - Parameter fromString: A string of objects (mostly numbers) separated by `separator` /// - Parameter separator: The separator (delimiter) used. Default = "," /// - Parameter firstRowContainsNames: Indicates, that the first line contains Column Identifiers. /// - Parameter parser: A function to convert a string to the expected generic type /// - Throws: SSSwiftyStatsError if the file doesn't exist or can't be accessed /// /// The following example creates a DataFrame object with 4 columns: /// /// let dataString = "Group 1,Group 2,Group 3,Group 4\n6.9,8.3,8.0,5.8\n5.4,6.8,10.5,3.8\n5.8,7.8,8.1,6.1\n4.6,9.2,6.9,5.6\n4.0,6.5,9.3,6.2" /// var df: SSDataFrame<Double, Double> /// do { /// df = try SSDataFrame.dataFrame(fromString: TukeyKramerData_01String, parser: scanDouble) /// } /// catch { /// ... /// } public class func dataFrame(fromString: String!, separator sep: String! = ",", firstRowContainsNames cn: Bool = true, parser: (String) -> SSElement?) throws -> SSDataFrame<SSElement, FPT> { do { var importedString = fromString if let lastScalar = importedString?.unicodeScalars.last { if CharacterSet.newlines.contains(lastScalar) { importedString = String(importedString!.dropLast()) } } let lines: Array<String> = importedString!.components(separatedBy: CharacterSet.newlines) var cnames: Array<String> = Array<String>() var cols: Array<String> var curString: String var columns: Array<Array<SSElement>> = Array<Array<SSElement>>() var k: Int = 0 var startRow: Int if cn { startRow = 1 } else { startRow = 0 } for r in startRow..<lines.count { cols = lines[r].components(separatedBy: sep) if columns.count == 0 && cols.count > 0 { for _ in 1...cols.count { columns.append(Array<SSElement>()) } } for c in 0..<cols.count { curString = cols[c].replacingOccurrences(of: "\"", with: "") if let d = parser(curString) { columns[c].append(d) } else { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Error during processing data file", log: .log_fs, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } } } if cn { let names = lines[0].components(separatedBy: sep) for name in names { curString = name.replacingOccurrences(of: "\"", with: "") cnames.append(curString) } } var examineArray: Array<SSExamine<SSElement, FPT>> = Array<SSExamine<SSElement, FPT>>() for k in 0..<columns.count { examineArray.append(SSExamine<SSElement, FPT>.init(withArray: columns[k], name: nil, characterSet: nil)) } if cn { k = 0 for e in examineArray { e.name = cnames[k] k += 1 } } return try SSDataFrame<SSElement, FPT>.init(examineArray: examineArray) } catch { return SSDataFrame<SSElement, FPT>() } } /// Loads the content of a file using the specified encoding. /// - Parameter path: The path to the file (e.g. ~/data/data.dat) /// - Parameter separator: The separator used in the file /// - Parameter firstRowContainsNames: Indicates, that the first line contains Column Identifiers. /// - Parameter stringEncoding: The encoding to use. /// - Parameter parser: A function to convert a string to the expected generic type /// - Throws: SSSwiftyStatsError if the file doesn't exist or can't be accessed public class func dataFrame(fromFile path: String!, separator sep: String! = ",", firstRowContainsNames cn: Bool = true, stringEncoding: String.Encoding! = String.Encoding.utf8, _ parser: (String) -> SSElement?) throws -> SSDataFrame<SSElement, FPT> { let fileManager = FileManager.default let fullFilename: String = NSString(string: path).expandingTildeInPath if !fileManager.fileExists(atPath: fullFilename) || !fileManager.isReadableFile(atPath: fullFilename) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("File not found", log: .log_fs, type: .error) } #endif throw SSSwiftyStatsError(type: .fileNotFound, file: #file, line: #line, function: #function) } do { var importedString = try String.init(contentsOfFile: fullFilename, encoding: stringEncoding) if let lastScalar = importedString.unicodeScalars.last { if CharacterSet.newlines.contains(lastScalar) { importedString = String(importedString.dropLast()) } } let lines: Array<String> = importedString.components(separatedBy: CharacterSet.newlines) var cnames: Array<String> = Array<String>() var cols: Array<String> var curString: String var columns: Array<Array<SSElement>> = Array<Array<SSElement>>() var k: Int = 0 var startRow: Int if cn { startRow = 1 } else { startRow = 0 } for r in startRow..<lines.count { cols = lines[r].components(separatedBy: sep) if columns.count == 0 && cols.count > 0 { for _ in 1...cols.count { columns.append(Array<SSElement>()) } } for c in 0..<cols.count { curString = cols[c].replacingOccurrences(of: "\"", with: "") if let d = parser(curString) { columns[c].append(d) } else { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Error during processing data file", log: .log_fs, type: .error) } #endif throw SSSwiftyStatsError.init(type: .functionNotDefinedInDomainProvided, file: #file, line: #line, function: #function) } } } if cn { let names = lines[0].components(separatedBy: sep) for name in names { curString = name.replacingOccurrences(of: "\"", with: "") cnames.append(curString) } } var examineArray: Array<SSExamine<SSElement, FPT>> = Array<SSExamine<SSElement, FPT>>() for k in 0..<columns.count { examineArray.append(SSExamine<SSElement, FPT>.init(withArray: columns[k], name: nil, characterSet: nil)) } if cn { k = 0 for e in examineArray { e.name = cnames[k] k += 1 } } return try SSDataFrame<SSElement, FPT>.init(examineArray: examineArray) } catch { throw error } } }
gpl-3.0
8c1470e5f082ab6a55e9f4d9773d8823
38.736424
458
0.519049
4.684728
false
false
false
false
piscoTech/Workout
Workout Core/Model/Workout/Additional Data/RunningHeartZones.swift
1
5123
// // RunningHeartZones.swift // Workout // // Created by Marco Boschi on 28/08/2018. // Copyright © 2018 Marco Boschi. All rights reserved. // import UIKit import HealthKit import MBLibrary public class RunningHeartZones: AdditionalDataProcessor, AdditionalDataProvider, PreferencesDelegate { private weak var preferences: Preferences? public static let defaultZones = [60, 70, 80, 94] /// The maximum valid time between two samples. static let maxInterval: TimeInterval = 60 private var maxHeartRate: Double? private var zones: [Int]? private var rawHeartData: [HKQuantitySample]? private var zonesData: [TimeInterval]? init(with preferences: Preferences) { self.preferences = preferences preferences.add(delegate: self) runningHeartZonesConfigChanged() } public func runningHeartZonesConfigChanged() { if let hr = preferences?.maxHeartRate { self.maxHeartRate = Double(hr) } else { self.maxHeartRate = nil } self.zones = preferences?.runningHeartZones self.updateZones() } // MARK: - Process Data func wantData(for typeIdentifier: HKQuantityTypeIdentifier) -> Bool { return typeIdentifier == .heartRate } func process(data: [HKQuantitySample], for _: WorkoutDataQuery) { self.rawHeartData = data updateZones() } private func zone(for s: HKQuantitySample, in zones: [Double]) -> Int? { guard let maxHR = maxHeartRate else { return nil } let p = s.quantity.doubleValue(for: WorkoutUnit.heartRate.default) / maxHR return zones.lastIndex { p >= $0 } } private func updateZones() { guard let maxHR = maxHeartRate, let data = rawHeartData else { zonesData = nil return } let zones = (self.zones ?? RunningHeartZones.defaultZones).map({ Double($0) / 100 }) zonesData = [TimeInterval](repeating: 0, count: zones.count) var previous: HKQuantitySample? for s in data { defer { previous = s } guard let prev = previous else { continue } let time = s.startDate.timeIntervalSince(prev.startDate) guard time <= RunningHeartZones.maxInterval else { continue } let pZone = zone(for: prev, in: zones) let cZone = zone(for: s, in: zones) if let c = cZone, pZone == c { zonesData?[c] += time } else if let p = pZone, let c = cZone, abs(p - c) == 1 { let pH = prev.quantity.doubleValue(for: WorkoutUnit.heartRate.default) / maxHR let cH = s.quantity.doubleValue(for: WorkoutUnit.heartRate.default) / maxHR /// Threshold between zones let th = zones[max(p, c)] guard th >= min(pH, cH), th <= max(pH, cH) else { continue } /// Incline of a line joining the two data points let m = (cH - pH) / time /// The time after the previous data point when the zone change let change = (th - pH) / m zonesData?[p] += change zonesData?[c] += time - change } } } // MARK: - Display Data private static let header = NSLocalizedString("HEART_ZONES_TITLE", comment: "Heart zones") private static let footer = NSLocalizedString("HEART_ZONES_FOOTER", comment: "Can be less than total") private static let zoneTitle = NSLocalizedString("HEART_ZONES_ZONE_%lld", comment: "Zone x") private static let zoneConfig = NSLocalizedString("HEART_ZONES_NEED_CONFIG", comment: "Zone config") public let sectionHeader: String? = RunningHeartZones.header public var sectionFooter: String? { return zonesData == nil ? nil : RunningHeartZones.footer } public var numberOfRows: Int { return zonesData?.count ?? 1 } public func heightForRowAt(_ indexPath: IndexPath, in tableView: UITableView) -> CGFloat? { if zonesData == nil { return UITableView.automaticDimension } else { return nil } } public func cellForRowAt(_ indexPath: IndexPath, for tableView: UITableView) -> UITableViewCell { guard let data = zonesData?[indexPath.row] else { let cell = tableView.dequeueReusableCell(withIdentifier: "msg", for: indexPath) cell.textLabel?.text = RunningHeartZones.zoneConfig return cell } let cell = tableView.dequeueReusableCell(withIdentifier: "basic", for: indexPath) cell.textLabel?.text = String(format: RunningHeartZones.zoneTitle, indexPath.row + 1) cell.detailTextLabel?.text = data > 0 ? data.formattedDuration : missingValueStr return cell } public func export(for preferences: Preferences, withPrefix prefix: String, _ callback: @escaping ([URL]?) -> Void) { guard prefix.range(of: "/") == nil else { fatalError("Prefix must not contain '/'") } DispatchQueue.background.async { guard let zonesData = self.zonesData else { callback([]) return } let hzFile = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("\(prefix)heartZones.csv") guard let file = OutputStream(url: hzFile, append: false) else { callback(nil) return } let sep = CSVSeparator do { file.open() defer{ file.close() } try file.write("Zone\(sep)Time\n") for (i, t) in zonesData.enumerated() { try file.write("\(i + 1)\(sep)\(t.rawDuration().toCSV())\n") } callback([hzFile]) } catch { callback(nil) } } } }
mit
45c2b4257c8412bf266a6dc3f8f27492
26.244681
118
0.689574
3.529979
false
false
false
false
codepgq/AnimateDemo
Animate/Animate/controller/综合实例/火苗/FireTwoController.swift
1
4355
// // FireTwoController.swift // Animate // // Created by Mac on 17/2/9. // Copyright © 2017年 Mac. All rights reserved. // import UIKit class FireTwoController: UIViewController { @IBOutlet weak var fireImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() fireEmitter.emitterCells = [fire] view.layer.addSublayer(fireEmitter) } //创建一个粒子 lazy var fire : CAEmitterCell = { let cell = CAEmitterCell() //粒子的创建速率 默认 0 cell.birthRate = 200 //粒子存活时间 单位s cell.lifetime = 0.3 //粒子的生存时间容差 0.3 += (0.0 ~ 0.5) cell.lifetimeRange = 0.5 //粒子颜色 // cell.color = UIColor(red: 200 / 255.0, green: 87 / 255.0, blue: 14 / 255.0, alpha: 0.1).cgColor cell.color = UIColor.white.cgColor //粒子内容 cell.contents = UIImage(named: "DazFire")?.cgImage cell.contentsRect = CGRect(x: 0, y: 0, width: 0.8, height: 2) //粒子名称 cell.name = "fire" //粒子的速度 默认 0 cell.velocity = 20 //粒子速度容差 cell.velocityRange = 10 //粒子在xy平面的发射角度 cell.emissionLongitude = CGFloat(M_PI + M_PI_2) //粒子发射角度容差 cell.emissionRange = CGFloat(M_PI_2) //粒子缩放速度 cell.scaleSpeed = 0.3 //粒子缩放大小 默认1 cell.scale = 1 //粒子缩放容差 cell.scaleRange = 0.2 //粒子旋转度 默认是 0 cell.spin = 0.2 //粒子旋转度容差 cell.spinRange = 0.4 /* 以及其他属性介绍 redRange 红色容差 greenRange 绿色容差 blueRange 蓝色容差 alphaRange 透明度容差 redSpeed 红色速度 greenSpeed 绿色速度 blueSpeed 蓝色速度 alphaSpeed 透明度速度 contentsRect 渲染范围 */ return cell }() //创建一个发射器对象 lazy var fireEmitter : CAEmitterLayer = { let emitter = CAEmitterLayer() //设置中心点 // emitter.emitterPosition = CGPoint(x: self.fireImageView.frame.width * 0.6, y: self.fireImageView.frame.height * 0.4) emitter.emitterPosition = CGPoint(x: self.fireImageView.center.x + 10, y: self.fireImageView.center.y - 10) //设置尺寸 // emitter.emitterSize = CGSize(width: 20, height: 20) //设置发射模式 /* public let kCAEmitterLayerPoints: String 从一个点发出 public let kCAEmitterLayerOutline: String 从边缘发出 public let kCAEmitterLayerSurface: String 从表面发出 public let kCAEmitterLayerVolume: String 从发射器中发出 */ emitter.emitterMode = kCAEmitterLayerOutline //设置发射器形状 /* public let kCAEmitterLayerPoint: String 点 public let kCAEmitterLayerLine: String 线 public let kCAEmitterLayerRectangle: String 矩形 public let kCAEmitterLayerCuboid: String 立方体 public let kCAEmitterLayerCircle: String 圆形 public let kCAEmitterLayerSphere: String 球 */ emitter.emitterShape = kCAEmitterLayerSphere //设置发射器渲染模式 /* CA_EXTERN NSString * const kCAEmitterLayerUnordered 无序 CA_EXTERN NSString * const kCAEmitterLayerOldestFirst 生命久的粒子会被渲染在最上层 CA_EXTERN NSString * const kCAEmitterLayerOldestLast 后产生的粒子会被渲染在最上层 CA_EXTERN NSString * const kCAEmitterLayerBackToFront 粒子的渲染按照Z轴的前后顺序进行 CA_EXTERN NSString * const kCAEmitterLayerAdditive 混合模式 */ emitter.renderMode = kCAEmitterLayerUnordered return emitter }() }
apache-2.0
bcb22a8e25f75643b65acb12af99f7d6
27.541353
126
0.548472
4.25084
false
false
false
false
lramirezsuarez/HelloWorld-iOS
HelloWorld/HelloWorld/udemyPlayground.playground/Contents.swift
1
2567
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" print("Mi nombre :V") // Arrays var arrayUdemy = [3.87, 7.1, 8.9]; arrayUdemy.remove(at: 1) arrayUdemy.append(arrayUdemy[0] * arrayUdemy[1]) var array2 = [String]() //Dictionaries var dictionaryUdemy = ["id": "1", "name":"robert"]; print(dictionaryUdemy["id"]!) print(dictionaryUdemy["name"]!) print(dictionaryUdemy.count) dictionaryUdemy["last-name"] = "Robertson" print(dictionaryUdemy) dictionaryUdemy.removeValue(forKey: "id") var dictionary2 = [String: String]() dictionary2["firstKey"] = "FirstValue" print(dictionary2) let menu = ["pizza" : 10.99, "ice-cream" : 4.99, "salad" : 7.99] print("The cost of my meal is \(menu["pizza"]! + menu["salad"]!)") //Challenge if statements username/password var username = "Lucho" var password = "12345" if username == "Lucho" && password == "123456" { print("Welcome to the app \(username)") } else if username == "Lucho" && password != "123456" { print("\(username) your password is incorrect, please try again") } else if username != "Lucho" && password == "123456" { print("\(username) your username is incorrect, please try again") } else { print("Wrond Username and Password") } //Generate a random number. let randFinger = arc4random_uniform(6) // While loop. var mult = 1 while (mult<=20) { print(7*mult) mult += 1 } var arrWhile = [7, 23, 45, 70, 98, 0] var k = 0 while (k < arrWhile.count) { arrWhile[k] += 1 k += 1 } print(arrWhile) //For loop let arrayFor = ["Eliza", "Julian", "Luis Alberto", "Luz Elena"] for name in arrayFor { print("Hi there \(name)!") } var arrHalve : [Double] = [8, 7, 19, 28] for (index, data) in arrHalve.enumerated() { arrHalve[index] = data / 2 } print(arrHalve) //Classes and Objects class Ghost { var isAlive = true var strenght = 0 func kill() { isAlive = false } func isStrong() -> Bool { if (strenght > 10) { return true } else { return false } } } var pinky = Ghost() pinky.isAlive pinky.isStrong() pinky.strenght = 20 pinky.isStrong() print(pinky.isAlive) print(pinky.strenght) print(pinky.isStrong()) pinky.kill() print(pinky.isAlive) //Optionals var number : Int? print(number) let userEnteredText = "5" let userEnteredInteger = Int(userEnteredText) if let variableAsigned = userEnteredInteger { print(variableAsigned * 7) } else { print("The user entered text is not a number") }
mit
aa77e291aec1e54d459b7b2026ed5b38
16
69
0.640436
2.95397
false
false
false
false
mercadopago/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/Issuer.swift
1
729
// // Issuer.swift // MercadoPagoSDK // // Created by Matias Gualino on 31/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation public class Issuer : NSObject { public var _id : NSNumber? public var name : String? public class func fromJSON(json : NSDictionary) -> Issuer { let issuer : Issuer = Issuer() if json["id"] != nil && !(json["id"]! is NSNull) { if let issuerIdStr = json["id"]! as? NSString { issuer._id = NSNumber(longLong: issuerIdStr.longLongValue) } else { issuer._id = NSNumber(longLong: (json["id"] as? NSNumber)!.longLongValue) } } issuer.name = JSON(json["name"]!).asString return issuer } }
mit
eada678083b29405bf56b66a216fd458
26.037037
77
0.615912
3.663317
false
false
false
false
LouisLWang/curly-garbanzo
weibo-swift/Classes/Module/Home/Controller/LWHomeViewController.swift
1
3226
// // LWHomeViewController.swift // weibo-swift // // Created by Louis on 10/27/15. // Copyright © 2015 louis. All rights reserved. // import UIKit class LWHomeViewController: LWBaseViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
24337a359ba967602385706d5476a8d7
32.947368
157
0.686202
5.550775
false
false
false
false
benlangmuir/swift
test/IDE/complete_where_clause.swift
7
15352
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP1 | %FileCheck %s -check-prefix=A1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP2 | %FileCheck %s -check-prefix=A1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP3 | %FileCheck %s -check-prefix=A1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP4 | %FileCheck %s -check-prefix=TYPE1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP5 | %FileCheck %s -check-prefix=TYPE1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP6 | %FileCheck %s -check-prefix=EMPTY // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_ASSOC_NODUP_1 | %FileCheck %s -check-prefix=GEN_T_ASSOC_E // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_ASSOC_NODUP_2 | %FileCheck %s -check-prefix=GEN_T_ASSOC_E // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_1 | %FileCheck %s -check-prefix=GEN_T // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_2_ASSOC | %FileCheck %s -check-prefix=GEN_T_ASSOC_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_3 | %FileCheck %s -check-prefix=GEN_T // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_4 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_5 | %FileCheck %s -check-prefix=GEN_T_S1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_6 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_1 | %FileCheck %s -check-prefix=GEN_T_S1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_1 | %FileCheck %s -check-prefix=GEN_T_S1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ALIAS_1 | %FileCheck %s -check-prefix=GEN_T_S1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ALIAS_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_1 | %FileCheck %s -check-prefix=GEN_T_NOMINAL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_3 | %FileCheck %s -check-prefix=ANYTYPE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_4 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CLASS_1 | %FileCheck %s -check-prefix=GEN_T_NOMINAL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CLASS_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_1 | %FileCheck %s -check-prefix=GEN_T_NOMINAL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSOC_1 | %FileCheck %s -check-prefix=P2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSOC_2 | %FileCheck %s -check-prefix=U_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL | %FileCheck %s -check-prefix=PROTOCOL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT | %FileCheck %s -check-prefix=PROTOCOL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_SELF | %FileCheck %s -check-prefix=PROTOCOL_SELF // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NOMINAL_TYPEALIAS | %FileCheck %s -check-prefix=NOMINAL_TYPEALIAS // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NOMINAL_TYPEALIAS_EXT | %FileCheck %s -check-prefix=NOMINAL_TYPEALIAS_EXT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NOMINAL_TYPEALIAS_NESTED1 | %FileCheck %s -check-prefix=NOMINAL_TYPEALIAS_NESTED1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NOMINAL_TYPEALIAS_NESTED2 | %FileCheck %s -check-prefix=NOMINAL_TYPEALIAS_NESTED2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NOMINAL_TYPEALIAS_NESTED1_EXT | %FileCheck %s -check-prefix=NOMINAL_TYPEALIAS_NESTED1_EXT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=NOMINAL_TYPEALIAS_NESTED2_EXT | %FileCheck %s -check-prefix=NOMINAL_TYPEALIAS_NESTED2_EXT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXT_ASSOC_MEMBER_1 | %FileCheck %s -check-prefix=EXT_ASSOC_MEMBER // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXT_ASSOC_MEMBER_2 | %FileCheck %s -check-prefix=EXT_ASSOC_MEMBER // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXT_SECONDTYPE | %FileCheck %s -check-prefix=EXT_SECONDTYPE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=WHERE_CLAUSE_WITH_EQUAL | %FileCheck %s -check-prefix=WHERE_CLAUSE_WITH_EQUAL class A1<T1, T2, T3> {} class A2<T4, T5> {} protocol P1 {} extension A1 where #^GP1^#{} extension A1 where T1 : P1, #^GP2^# {} extension A1 where T1 : P1, #^GP3^# extension A1 where T1 : #^GP4^# extension A1 where T1 : P1, T2 : #^GP5^# extension A1 where T1.#^GP6^# {} // A1: Begin completions // A1-DAG: Decl[GenericTypeParam]/Local: T1[#T1#]; name=T1 // A1-DAG: Decl[GenericTypeParam]/Local: T2[#T2#]; name=T2 // A1-DAG: Decl[GenericTypeParam]/Local: T3[#T3#]; name=T3 // A1-DAG: Decl[Class]/Local: A1[#A1#]; name=A1 // A1-NOT: T4 // A1-NOT: T5 // A1-NOT: Self // TYPE1: Begin completions // TYPE1-DAG: Decl[Protocol]/CurrModule: P1[#P1#]; name=P1 // TYPE1-DAG: Decl[Class]/CurrModule: A1[#A1#]; name=A1 // TYPE1-DAG: Decl[Class]/CurrModule: A2[#A2#]; name=A2 // TYPE1-NOT: T1 // TYPE1-NOT: T2 // TYPE1-NOT: T3 // TYPE1-NOT: T4 // TYPE1-NOT: T5 // TYPE1-NOT: Self // EMPTY: Begin completions, 1 items // EMPTY-DAG: Keyword/None: Type[#T1.Type#]; name=Type // EMPTY: End completions protocol A {associatedtype E} protocol B {associatedtype E} protocol C {associatedtype E} protocol D: C {associatedtype E} func ab<T: A & B>(_ arg: T) where T.#^FUNC_ASSOC_NODUP_1^# func ab<T: D>(_ arg: T) where T.#^FUNC_ASSOC_NODUP_2^# // GEN_T_ASSOC_E: Begin completions, 2 items // GEN_T_ASSOC_E-NEXT: Decl[AssociatedType]/{{Super|CurrNominal}}: E; name=E // GEN_T_ASSOC_E-NEXT: Keyword/None: Type[#T.Type#]; // GEN_T_ASSOC_E: End completions protocol Assoc { associatedtype Q } func f1<T>(_: T) where #^FUNC_1^# {} // GEN_T: Decl[GenericTypeParam]/Local: T[#T#]; name=T func f2<T>(_: T) where T.#^FUNC_2^# {} // GEN_T_DOT: Begin completions // GEN_T_DOT-DAG: Keyword/None: Type[#T.Type#]; // GEN_T_DOT-NOT: Keyword/CurrNominal: self[#T#]; // GEN_T_DOT: End completions func f2b<T: Assoc>(_: T) where T.#^FUNC_2_ASSOC^# {} // GEN_T_ASSOC_DOT: Begin completions // GEN_T_ASSOC_DOT-DAG: Decl[AssociatedType]/{{Super|CurrNominal}}: Q; // GEN_T_ASSOC_DOT-DAG: Keyword/None: Type[#T.Type#]; // GEN_T_ASSOC_DOT-NOT: Keyword/CurrNominal: self[#T#]; // GEN_T_ASSOC_DOT: End completions func f3<T>(_: T) where T == #^FUNC_3^# {} func f3<T>(_: T) where T == T.#^FUNC_4^# {} struct S1 { func f1<T>(_: T) where #^FUNC_5^# {} func f2<T>(_: T) where T.#^FUNC_6^# {} subscript<T>(x: T) -> T where #^SUBSCRIPT_1^# { return x } subscript<T>(x: T) -> T where T.#^SUBSCRIPT_2^# { return x } init<T>(_: T) where #^INIT_1^# {} init<T>(_: T) where T.#^INIT_2^# {} typealias TA1<T> = A1<T, T, T> where #^ALIAS_1^# typealias TA2<T> = A1<T, T, T> where T.#^ALIAS_2^# } // GEN_T_S1: Begin completions, 3 items // GEN_T_S1-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // GEN_T_S1-DAG: Decl[Struct]/Local: S1[#S1#]; // GEN_T_S1-DAG: Keyword[Self]/CurrNominal: Self[#S1#]; // GEN_T_S1: End completions struct S2<T> where #^STRUCT_1^# {} struct S3<T> where T.#^STRUCT_2^# {} struct S4<T> where T == #^STRUCT_3^# {} struct S5<T> where T == T.#^STRUCT_4^# {} class C1<T> where #^CLASS_1^# {} class C2<T> where T.#^CLASS_2^# {} enum E1<T> where #^ENUM_1^# {} enum E2<T> where T.#^ENUM_2^# {} // GEN_T_NOMINAL: Begin completions, 1 items // GEN_T_NOMINAL: Decl[GenericTypeParam]/Local: T[#T#]; name=T // GEN_T_NOMINAL: End completions // ANYTYPE: Begin completions // ANYTYPE-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // ANYTYPE-DAG: Decl[Class]/CurrModule: A1[#A1#]; // ANYTYPE-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem: Int[#Int#]; // ANYTYPE: End completions protocol P2 { associatedtype T where #^ASSOC_1^# associatedtype U: Assoc where U.#^ASSOC_2^# } // P2: Begin completions, 4 items // P2-DAG: Decl[GenericTypeParam]/Local: Self[#Self#]; // P2-DAG: Decl[AssociatedType]/{{Super|CurrNominal}}: T; // P2-DAG: Decl[AssociatedType]/{{Super|CurrNominal}}: U; // P2-DAG: Decl[Protocol]/Local: P2[#P2#] // P2: End completions // U_DOT: Begin completions, 2 items // U_DOT-DAG: Keyword/None: Type[#Self.U.Type#]; // U_DOT-DAG: Decl[AssociatedType]/CurrNominal: Q; // U_DOT: End completions protocol P3 where #^PROTOCOL^# { associatedtype T: Assoc typealias U = T.Q typealias IntAlias = Int } // PROTOCOL: Begin completions, 4 items // PROTOCOL-DAG: Decl[GenericTypeParam]/Local: Self[#Self#]; // PROTOCOL-DAG: Decl[AssociatedType]/CurrNominal: T; // PROTOCOL-DAG: Decl[TypeAlias]/CurrNominal: U[#Self.T.Q#]; // PROTOCOL-DAG: Decl[Protocol]/Local: P3[#P3#]; // PROTOCOL: End completions extension P3 where #^PROTOCOL_EXT^# { // Same as PROTOCOL } protocol P4 where Self.#^PROTOCOL_SELF^# { associatedtype T: Assoc typealias U = T.Q typealias IntAlias = Int } // PROTOCOL_SELF: Begin completions // PROTOCOL_SELF-DAG: Decl[AssociatedType]/CurrNominal: T; // PROTOCOL_SELF-DAG: Decl[TypeAlias]/CurrNominal: U[#Self.T.Q#]; // PROTOCOL_SELF-DAG: Decl[TypeAlias]/CurrNominal: IntAlias[#Int#]; // PROTOCOL_SELF-DAG: Keyword/None: Type[#Self.Type#]; // PROTOCOL_SELF: End completions struct TA1<T: Assoc> where #^NOMINAL_TYPEALIAS^# { typealias U = T.Q } // NOMINAL_TYPEALIAS: Begin completions, 1 items // NOMINAL_TYPEALIAS-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // NOMINAL_TYPEALIAS: End completions extension TA1 where #^NOMINAL_TYPEALIAS_EXT^# { } // NOMINAL_TYPEALIAS_EXT: Begin completions, 4 items // NOMINAL_TYPEALIAS_EXT-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // NOMINAL_TYPEALIAS_EXT-DAG: Decl[TypeAlias]/CurrNominal: U[#T.Q#]; // NOMINAL_TYPEALIAS_EXT-DAG: Decl[Struct]/Local: TA1[#TA1#]; // NOMINAL_TYPEALIAS_EXT-DAG: Keyword[Self]/CurrNominal: Self[#TA1<T>#]; // NOMINAL_TYPEALIAS_EXT: End completions struct TA2<T: Assoc> { struct Inner1<U> where #^NOMINAL_TYPEALIAS_NESTED1^# { typealias X1 = T typealias X2 = T.Q } // NOMINAL_TYPEALIAS_NESTED1: Begin completions, 2 items // NOMINAL_TYPEALIAS_NESTED1-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // NOMINAL_TYPEALIAS_NESTED1-DAG: Decl[GenericTypeParam]/Local: U[#U#]; // NOMINAL_TYPEALIAS_NESTED1: End completions struct Inner2 where #^NOMINAL_TYPEALIAS_NESTED2^# { typealias X1 = T typealias X2 = T.Q } // NOMINAL_TYPEALIAS_NESTED2: Begin completions, 1 items // NOMINAL_TYPEALIAS_NESTED2-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // NOMINAL_TYPEALIAS_NESTED2: End completions } extension TA2.Inner1 where #^NOMINAL_TYPEALIAS_NESTED1_EXT^# {} // NOMINAL_TYPEALIAS_NESTED1_EXT: Begin completions, 6 items // NOMINAL_TYPEALIAS_NESTED1_EXT-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // NOMINAL_TYPEALIAS_NESTED1_EXT-DAG: Decl[GenericTypeParam]/Local: U[#U#]; // NOMINAL_TYPEALIAS_NESTED1_EXT-DAG: Decl[TypeAlias]/CurrNominal: X1[#T#]; // NOMINAL_TYPEALIAS_NESTED1_EXT-DAG: Decl[TypeAlias]/CurrNominal: X2[#T.Q#]; // FIXME : We shouldn't be suggesting Inner1 because it's not fully-qualified // NOMINAL_TYPEALIAS_NESTED1_EXT-DAG: Decl[Struct]/Local: Inner1[#TA2.Inner1#]; // NOMINAL_TYPEALIAS_NESTED1_EXT-DAG: Keyword[Self]/CurrNominal: Self[#TA2<T>.Inner1<U>#]; // NOMINAL_TYPEALIAS_NESTED1_EXT: End completions extension TA2.Inner2 where #^NOMINAL_TYPEALIAS_NESTED2_EXT^# {} // NOMINAL_TYPEALIAS_NESTED2_EXT: Begin completions, 5 items // NOMINAL_TYPEALIAS_NESTED2_EXT-DAG: Decl[GenericTypeParam]/Local: T[#T#]; // NOMINAL_TYPEALIAS_NESTED2_EXT-DAG: Decl[TypeAlias]/CurrNominal: X1[#T#]; // NOMINAL_TYPEALIAS_NESTED2_EXT-DAG: Decl[TypeAlias]/CurrNominal: X2[#T.Q#]; // FIXME : We shouldn't be suggesting Inner2 because it's not fully-qualified // NOMINAL_TYPEALIAS_NESTED2_EXT-DAG: Decl[Struct]/Local: Inner2[#TA2.Inner2#]; // NOMINAL_TYPEALIAS_NESTED2_EXT-DAG: Keyword[Self]/CurrNominal: Self[#TA2<T>.Inner2#]; // NOMINAL_TYPEALIAS_NESTED2_EXT: End completions protocol WithAssoc { associatedtype T: Assoc } extension WithAssoc where T.#^EXT_ASSOC_MEMBER_1^# // EXT_ASSOC_MEMBER: Begin completions, 2 items // EXT_ASSOC_MEMBER-DAG: Decl[AssociatedType]/CurrNominal: Q; // EXT_ASSOC_MEMBER-DAG: Keyword/None: Type[#Self.T.Type#]; // EXT_ASSOC_MEMBER: End completions extension WithAssoc where Int == T.#^EXT_ASSOC_MEMBER_2^# // Same as EXT_ASSOC_MEMBER extension WithAssoc where Int == #^EXT_SECONDTYPE^# // EXT_SECONDTYPE: Begin completions // EXT_SECONDTYPE-DAG: Decl[AssociatedType]/CurrNominal: T; // EXT_SECONDTYPE: End completions func foo<K: WithAssoc>(_ key: K.Type) where K.#^WHERE_CLAUSE_WITH_EQUAL^# == S1 {} // WHERE_CLAUSE_WITH_EQUAL: Begin completions, 2 items // WHERE_CLAUSE_WITH_EQUAL-DAG: Decl[AssociatedType]/CurrNominal: T; // WHERE_CLAUSE_WITH_EQUAL-DAG: Keyword/None: Type[#K.Type#]; // WHERE_CLAUSE_WITH_EQUAL: End completions
apache-2.0
daa8f2232e669d2223f3c3961beff956
55.029197
180
0.691636
3.041807
false
true
false
false
tardieu/swift
test/IDE/complete_members_optional.swift
27
1949
// RUN: sed -n -e '1,/NO_ERRORS_UP_TO_HERE$/ p' %s > %t_no_errors.swift // RUN: %target-swift-frontend -typecheck -verify -disable-objc-attr-requires-foundation-module %t_no_errors.swift // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OPTIONAL_MEMBERS_1 | %FileCheck %s -check-prefix=OPTIONAL_MEMBERS_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=OPTIONAL_MEMBERS_2 | %FileCheck %s -check-prefix=OPTIONAL_MEMBERS_2 @objc protocol HasOptionalMembers1 { @objc optional func optionalInstanceFunc() -> Int @objc optional static func optionalClassFunc() -> Int @objc optional var optionalInstanceProperty: Int { get } @objc optional static var optionalClassProperty: Int { get } } func sanityCheck1(_ a: HasOptionalMembers1) { func isOptionalInt(_ a: inout Int?) {} var result1 = a.optionalInstanceFunc?() isOptionalInt(&result1) var result2 = a.optionalInstanceProperty isOptionalInt(&result2) } // NO_ERRORS_UP_TO_HERE func optionalMembers1(_ a: HasOptionalMembers1) { a.#^OPTIONAL_MEMBERS_1^# } // OPTIONAL_MEMBERS_1: Begin completions, 2 items // OPTIONAL_MEMBERS_1-DAG: Decl[InstanceMethod]/CurrNominal: optionalInstanceFunc!()[#Int#]{{; name=.+$}} // OPTIONAL_MEMBERS_1-DAG: Decl[InstanceVar]/CurrNominal: optionalInstanceProperty[#Int?#]{{; name=.+$}} // OPTIONAL_MEMBERS_1: End completions func optionalMembers2<T : HasOptionalMembers1>(_ a: T) { T.#^OPTIONAL_MEMBERS_2^# } // OPTIONAL_MEMBERS_2: Begin completions, 3 items // OPTIONAL_MEMBERS_2-DAG: Decl[InstanceMethod]/Super: optionalInstanceFunc!({#self: HasOptionalMembers1#})[#() -> Int#]{{; name=.+$}} // OPTIONAL_MEMBERS_2-DAG: Decl[StaticMethod]/Super: optionalClassFunc!()[#Int#]{{; name=.+$}} // OPTIONAL_MEMBERS_2-DAG: Decl[StaticVar]/Super: optionalClassProperty[#Int?#]{{; name=.+$}} // OPTIONAL_MEMBERS_2: End completions
apache-2.0
89ae04fb6ffb3befa7b433e13e0a6073
44.325581
158
0.71216
3.569597
false
false
false
false
dataich/TypetalkSwift
TypetalkSwift/Requests/GetFriends.swift
1
973
// // GetFriends.swift // TypetalkSwift // // Created by Taichiro Yoshida on 2017/10/15. // Copyright © 2017 Nulab Inc. All rights reserved. // import Alamofire // sourcery: AutoInit public struct GetFriends: Request { public let q :String public let offset : Int? public let count : Int? public typealias Response = GetFriendsResponse public var path: String { return "/search/friends" } public var version: Int { return 2 } public var parameters: Parameters? { var parameters: Parameters = [:] parameters["q"] = self.q parameters["offset"] = self.offset parameters["count"] = self.count return parameters } // sourcery:inline:auto:GetFriends.AutoInit public init(q: String, offset: Int?, count: Int?) { self.q = q self.offset = offset self.count = count } // sourcery:end } public struct GetFriendsResponse: Codable { public let accounts: [AccountWithStatus] public let count: Int }
mit
29aa1e0aeda4d3ad5af3f8aa937b922e
20.130435
53
0.673868
3.826772
false
false
false
false
luongtsu/MHCalendar
MHCalendar/MHCalendar0.swift
1
10610
// // MHCalendar.swift // MHCalendarDemo // // Created by Luong Minh Hiep on 9/11/17. // Copyright © 2017 Luong Minh Hiep. All rights reserved. // /* import UIKit private let collectionCellReuseIdentifier = "MHCollectionViewCell" protocol MHCalendarResponsible: class { func didSelectDate(date: Date) func didSelectDates(dates: [Date]) func didSelectAnotherMonth(isNextMonth: Bool) } open class MHCalendar0: UIView { weak var mhCalendarObserver : MHCalendarResponsible? // Appearance var tintColor: UIColor var dayDisabledTintColor: UIColor var weekdayTintColor: UIColor var weekendTintColor: UIColor var todayTintColor: UIColor var dateSelectionColor: UIColor var monthTitleColor: UIColor var backgroundImage: UIImage? var backgroundColor: UIColor? // Other config var selectedDates = [Date]() var startDate: Date? var hightlightsToday: Bool = true var hideDaysFromOtherMonth: Bool = false var multiSelectEnabled: Bool = true var displayingMonthIndex: Int = 0// count from starting date fileprivate(set) open var startYear: Int fileprivate(set) open var endYear: Int override open func viewDidLoad() { super.viewDidLoad() // setup collectionview self.collectionView?.delegate = self self.collectionView?.backgroundColor = UIColor.clear self.collectionView?.showsHorizontalScrollIndicator = false self.collectionView?.showsVerticalScrollIndicator = false // Register cell classes self.collectionView!.register(UINib(nibName: "MHCollectionViewCell", bundle: Bundle(for: MHCalendar.self )), forCellWithReuseIdentifier: collectionCellReuseIdentifier) self.collectionView!.register(UINib(nibName: "MHCalendarHeaderView", bundle: Bundle(for: MHCalendar.self )), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "MHCalendarHeaderView") if backgroundImage != nil { self.collectionView!.backgroundView = UIImageView(image: backgroundImage) } else if backgroundColor != nil { self.collectionView?.backgroundColor = backgroundColor } else { self.collectionView?.backgroundColor = UIColor.white } } public init(startYear: Int = Date().year(), endYear: Int = Date().year(), multiSelection: Bool = true, selectedDates: [Date] = []) { self.startYear = startYear self.endYear = endYear self.multiSelectEnabled = multiSelection self.selectedDates = selectedDates //Text color initializations self.tintColor = UIColor.rgb(192, 55, 44) self.dayDisabledTintColor = UIColor.rgb(200, 200, 200) self.weekdayTintColor = UIColor.rgb(46, 204, 113) self.weekendTintColor = UIColor.rgb(192, 57, 43) self.dateSelectionColor = UIColor.rgb(52, 152, 219) self.monthTitleColor = UIColor.rgb(211, 84, 0) self.todayTintColor = UIColor.rgb(248, 160, 46) //Layout creation let layout = UICollectionViewFlowLayout() layout.sectionHeadersPinToVisibleBounds = true layout.minimumInteritemSpacing = 1 layout.minimumLineSpacing = 1 layout.headerReferenceSize = CGSize(width: UIScreen.main.bounds.width, height: MHCalendarHeaderView.defaultHeight) super.init(collectionViewLayout: layout) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewFlowLayout override open func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let startDate = Date(year: startYear, month: 1, day: 1) let firstDayOfMonth = startDate.dateByAddingMonths(displayingMonthIndex) let addingPrefixDaysWithMonthDyas = ( firstDayOfMonth.numberOfDaysInMonth() + firstDayOfMonth.weekday() - Calendar.current.firstWeekday ) let addingSuffixDays = addingPrefixDaysWithMonthDyas%7 var totalNumber = addingPrefixDaysWithMonthDyas if addingSuffixDays != 0 { totalNumber = totalNumber + (7 - addingSuffixDays) } return totalNumber } override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionCellReuseIdentifier, for: indexPath) as! MHCollectionViewCell let calendarStartDate = Date(year:startYear, month: 1, day: 1) let firstDayOfThisMonth = calendarStartDate.dateByAddingMonths(displayingMonthIndex) let prefixDays = ( firstDayOfThisMonth.weekday() - Calendar.current.firstWeekday) if indexPath.row >= prefixDays { cell.isCellSelectable = true let currentDate = firstDayOfThisMonth.dateByAddingDays(indexPath.row-prefixDays) let nextMonthFirstDay = firstDayOfThisMonth.dateByAddingDays(firstDayOfThisMonth.numberOfDaysInMonth()-1) cell.currentDate = currentDate cell.titleLabel.text = "\(currentDate.day())" if selectedDates.filter({ $0.isDateSameDay(currentDate)}).count > 0 && (firstDayOfThisMonth.month() == currentDate.month()) { cell.selectedForLabelColor(dateSelectionColor) } else { cell.deSelectedForLabelColor(weekdayTintColor) if cell.currentDate.isSaturday() || cell.currentDate.isSunday() { cell.titleLabel.textColor = weekendTintColor } if (currentDate > nextMonthFirstDay) { cell.isCellSelectable = false if hideDaysFromOtherMonth { cell.titleLabel.textColor = UIColor.clear } else { cell.titleLabel.textColor = self.dayDisabledTintColor } } if currentDate.isToday() && hightlightsToday { cell.setTodayCellColor(todayTintColor) } if startDate != nil { if Calendar.current.startOfDay(for: cell.currentDate as Date) < Calendar.current.startOfDay(for: startDate!) { cell.isCellSelectable = false cell.titleLabel.textColor = self.dayDisabledTintColor } } } } else { cell.deSelectedForLabelColor(weekdayTintColor) cell.isCellSelectable = false let previousDay = firstDayOfThisMonth.dateByAddingDays(-( prefixDays - indexPath.row)) cell.currentDate = previousDay cell.titleLabel.text = "\(previousDay.day())" if hideDaysFromOtherMonth { cell.titleLabel.textColor = UIColor.clear } else { cell.titleLabel.textColor = self.dayDisabledTintColor } } cell.backgroundColor = UIColor.clear return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { let rect = UIScreen.main.bounds let screenWidth = rect.size.width - 7 return CGSize(width: screenWidth/7, height: screenWidth/7); } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(5, 0, 5, 0); //top,left,bottom,right } override open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "MHCalendarHeaderView", for: indexPath) as! MHCalendarHeaderView let startDate = Date(year: startYear, month: 1, day: 1) let firstDayOfMonth = startDate.dateByAddingMonths(indexPath.section) header.currentMonthLabel.text = firstDayOfMonth.monthNameFull() header.currentMonthLabel.textColor = monthTitleColor header.updateWeekdaysLabelColor(weekdayTintColor) header.updateWeekendLabelColor(weekendTintColor) header.backgroundColor = UIColor.clear return header; } return UICollectionReusableView() } override open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! MHCollectionViewCell if !multiSelectEnabled && cell.isCellSelectable! { mhCalendarObserver?.didSelectDate(date: cell.currentDate) cell.selectedForLabelColor(dateSelectionColor) selectedDates.append(cell.currentDate) return } if cell.isCellSelectable! { if selectedDates.filter({ $0.isDateSameDay(cell.currentDate) }).count == 0 { selectedDates.append(cell.currentDate) cell.selectedForLabelColor(dateSelectionColor) if cell.currentDate.isToday() { cell.setTodayCellColor(dateSelectionColor) } } else { selectedDates = selectedDates.filter(){ return !($0.isDateSameDay(cell.currentDate)) } if cell.currentDate.isSaturday() || cell.currentDate.isSunday() { cell.deSelectedForLabelColor(weekendTintColor) } else { cell.deSelectedForLabelColor(weekdayTintColor) } if cell.currentDate.isToday() && hightlightsToday{ cell.setTodayCellColor(todayTintColor) } } } } }*/
mit
2a240062c8a458b5c2ff728ed522a030
41.951417
227
0.644076
5.563188
false
false
false
false
KevinGong2013/Printer
Sources/Printer/Ticket/Block.swift
1
1885
// // Block.swift // Ticket // // Created by gix on 2019/6/30. // Copyright © 2019 gix. All rights reserved. // import Foundation public protocol Printable { func data(using encoding: String.Encoding) -> Data } public protocol BlockDataProvider: Printable { } public protocol Attribute { var attribute: [UInt8] { get } } public struct Block: Printable { public static var defaultFeedPoints: UInt8 = 70 private let feedPoints: UInt8 private let dataProvider: BlockDataProvider public init(_ dataProvider: BlockDataProvider, feedPoints: UInt8 = Block.defaultFeedPoints) { self.feedPoints = feedPoints self.dataProvider = dataProvider } public func data(using encoding: String.Encoding) -> Data { return dataProvider.data(using: encoding) + Data.print(feedPoints) } } public extension Block { // blank line static var blank = Block(Blank()) static func blank(_ line: UInt8) -> Block { return Block(Blank(), feedPoints: Block.defaultFeedPoints * line) } // qr static func qr(_ content: String) -> Block { return Block(QRCode(content)) } // title static func title(_ content: String) -> Block { return Block(Text.title(content)) } // plain text static func plainText(_ content: String) -> Block { return Block(Text.init(content)) } static func text(_ text: Text) -> Block { return Block(text) } // key value static func kv(k: String, v: String) -> Block { return Block(Text.kv(k: k, v: v)) } // dividing static var dividing = Block(Dividing.default) // image static func image(_ im: Image, attributes: TicketImage.PredefinedAttribute...) -> Block { return Block(TicketImage(im, attributes: attributes)) } }
apache-2.0
fd7383919f140534e005e8ec078dea19
23.153846
97
0.624735
4.15894
false
false
false
false
charlymr/IRLDocumentScanner
demo/demo/ViewController.swift
1
1688
// // ViewController.swift // demo // // Created by Denis Martin on 28/06/2015. // Copyright (c) 2015 iRLMobile. All rights reserved. // import UIKit import IRLDocumentScanner; class ViewController : UIViewController, IRLScannerViewControllerDelegate { @IBOutlet weak var scanButton: UIButton! @IBOutlet weak var imageView: UIImageView! // MARK: User Actions @IBAction func scan(_ sender: AnyObject) { let scanner = IRLScannerViewController.standardCameraView(with: self) scanner.showControls = true scanner.showAutoFocusWhiteRectangle = true present(scanner, animated: true, completion: nil) } // MARK: IRLScannerViewControllerDelegate func pageSnapped(_ page_image: UIImage, from controller: IRLScannerViewController) { controller.dismiss(animated: true) { () -> Void in self.imageView.image = page_image } } func cameraViewWillUpdateTitleLabel(_ cameraView: IRLScannerViewController) -> String? { var text = "" switch cameraView.cameraViewType { case .normal: text = text + "NORMAL" case .blackAndWhite: text = text + "B/W-FILTER" case .ultraContrast: text = text + "CONTRAST" } switch cameraView.detectorType { case .accuracy: text = text + " | Accuracy" case .performance: text = text + " | Performance" } return text } func didCancel(_ cameraView: IRLScannerViewController) { cameraView.dismiss(animated: true){ ()-> Void in NSLog("Cancel pressed"); } } }
mit
53db17ada1c0f3c70af6310366a236be
28.614035
92
0.614336
4.637363
false
false
false
false
jjochen/photostickers
UITests/Tests/PhotoStickersUITests.swift
1
4359
// // PhotoStickersUITests.swift // PhotoStickersUITests // // Created by Jochen Pfeiffer on 28/12/2016. // Copyright © 2016 Jochen Pfeiffer. All rights reserved. // import XCTest class PhotoStickersUITests: XCTestCase { func testMessagesExtension() { guard let messageApp = XCUIApplication.eps_iMessagesApp() else { fatalError() } messageApp.terminate() messageApp.launchArguments += ["-RunningUITests", "true"] setupSnapshot(messageApp) messageApp.launch() tapButton(withLocalizations: ["Fortfahren", "Continue"], inApp: messageApp) tapButton(withLocalizations: ["Abbrechen", "Cancel"], inApp: messageApp) messageApp.tables["ConversationList"].cells.firstMatch.tap() sleep(1) messageApp.textFields["messageBodyField"].tap() sleep(1) let start = messageApp.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) let finish = messageApp.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.6)) start.press(forDuration: 0.05, thenDragTo: finish) sleep(1) messageApp.textFields["messageBodyField"].tap() let messageText = "🎉🎉🎉 Party?" messageApp.typeText(messageText) sleep(1) messageApp.buttons["sendButton"].tap() sleep(1) let appCells = messageApp.collectionViews["appSelectionBrowserIdentifier"].cells let photoStickersCell = appCells.matching(NSPredicate(format: "label CONTAINS[c] 'Photo Stickers'")).firstMatch photoStickersCell.tap() sleep(5) let partySticker = messageApp.collectionViews["StickerBrowserCollectionView"].cells.element(boundBy: 5) let messageCell = messageApp.collectionViews["TranscriptCollectionView"].cells.matching(NSPredicate(format: "label CONTAINS[c] %@", messageText)).firstMatch let cellWidth = messageCell.frame.size.width let rightDX = CGFloat(130) let relativeDX = 1 - rightDX / cellWidth let sourceCoordinate: XCUICoordinate = partySticker.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.1)) let destCoordinate: XCUICoordinate = messageCell.coordinate(withNormalizedOffset: CGVector(dx: relativeDX, dy: 0.0)) sourceCoordinate.press(forDuration: 0.5, thenDragTo: destCoordinate) sleep(1) snapshot("1_Messages", timeWaitingForIdle: 40) messageApp.otherElements["collapseButtonIdentifier"].tap() sleep(1) snapshot("2_Sticker_Collection", timeWaitingForIdle: 40) messageApp.buttons["StickerBrowserEditBarButtonItem"].tap() messageApp.collectionViews["StickerBrowserCollectionView"].cells.element(boundBy: 0).tap() sleep(1) messageApp.buttons["RectangleButton"].tap() snapshot("3_Edit_Sticker") } } // MARK: Helper private extension PhotoStickersUITests { func isIPad() -> Bool { let window = XCUIApplication().windows.element(boundBy: 0) return window.horizontalSizeClass == .regular && window.verticalSizeClass == .regular } func tapButton(withLocalizations localizations: [String], inApp app: XCUIApplication) { localizations.forEach { title in let button = app.buttons[title] if button.exists { button.tap() } } } } extension XCUIElement { func forceTap() { if isHittable { tap() } else { let coordinate: XCUICoordinate = self.coordinate(withNormalizedOffset: CGVector(dx: 0.0, dy: 0.0)) coordinate.tap() } } // The following is a workaround for inputting text in the // simulator when the keyboard is hidden func setText(_ text: String, application: XCUIApplication) { UIPasteboard.general.string = text doubleTap() application.menuItems["Paste"].tap() } func dragAndDropUsingCenterPos(forDuration duration: TimeInterval, thenDragTo destElement: XCUIElement) { let sourceCoordinate: XCUICoordinate = coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) let destCorodinate: XCUICoordinate = destElement.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) sourceCoordinate.press(forDuration: duration, thenDragTo: destCorodinate) } }
mit
98bb49aadba7c464d3ede80e293f30c8
34.072581
164
0.671189
4.539666
false
true
false
false
C39GX6/ArchiveExport
ArchiveExport/ViewController.swift
1
8161
// // ViewController.swift // ArchiveExport // // Created by 刘诗彬 on 14/10/29. // Copyright (c) 2014年 Stephen. All rights reserved. // import Cocoa class ViewController: NSViewController,NSOpenSavePanelDelegate,NSWindowDelegate{ @IBOutlet weak var archiveButton: NSPopUpButton! @IBOutlet weak var provisioningButton: NSPopUpButton! @IBOutlet weak var indicator: NSProgressIndicator! @IBOutlet weak var iconView: NSImageView! @IBOutlet weak var statLabel: NSTextField! @IBOutlet weak var exportButton: NSButton! @IBOutlet weak var infoLabel: NSTextField! var exportTask : NSTask! var exportPath : String! var archives : [AEArchive]! var provisionings : [AEProvisioning]! var exporting = false @IBAction func export(sender: AnyObject) { if exportTask != nil && exportTask.running { return } let archive = selectedArchive() let provisioning = selectedProvisining() if archive == nil || provisioning == nil{ return } let savePanel = NSSavePanel(); savePanel.allowedFileTypes = ["ipa"] savePanel.allowsOtherFileTypes = false savePanel.directoryURL = NSURL(fileURLWithPath: NSHomeDirectory()+"/Desktop") savePanel.nameFieldStringValue = archive!.name savePanel.delegate = self savePanel.beginSheetModalForWindow(self.view.window!, completionHandler:{(NSModalResponse) -> () in }) } func exportTo(path:String){ if exportTask != nil && exportTask.running { return } statLabel.stringValue = "" let archive = selectedArchive() let provisioning = selectedProvisining() if archive != nil && provisioning != nil{ exportPath = path exportTask = NSTask(); exportTask.launchPath = "/usr/bin/xcrun" exportTask.arguments = ["--sdk","iphoneos","PackageApplication",archive!.appPath!,"--embed",provisioning!.identifier!,"-o",exportPath] setIsExporting(true) exportTask.terminationHandler = {[weak self](_:NSTask) in dispatch_async(dispatch_get_main_queue(), {self?.checkResult()})} exportTask.launch() } } func checkResult(){ if exportTask != nil{ if exportTask.running{ setIsExporting(true) } else { setIsExporting(false) if NSFileManager.defaultManager().fileExistsAtPath(exportPath){ statLabel.textColor = NSColor.greenColor() statLabel.stringValue = "导出成功" } else { statLabel.textColor = NSColor.redColor() statLabel.stringValue = "导出失败" } } } else { setIsExporting(false) } } func setIsExporting(exporting: Bool){ exportButton.enabled = !exporting if !exporting { exportTask = nil; indicator.stopAnimation(nil) } else { indicator.startAnimation(nil) } } @IBAction func valueChanged(sender: AnyObject) { updateArchiveInfo() } func selectedArchive()->AEArchive?{ let selectedIndex = archiveButton.indexOfSelectedItem var archive : AEArchive! if selectedIndex >= 0{ archive = archives[selectedIndex] } return archive } func selectedProvisining()->AEProvisioning?{ let selectedIndex = provisioningButton.indexOfSelectedItem var provisioning : AEProvisioning? if selectedIndex >= 0 { provisioning = provisionings[selectedIndex] } return provisioning } func updateArchiveInfo(){ let archive = self.selectedArchive() if archive == nil { infoLabel.stringValue = "没有发现包" return } iconView.image = archive!.icon let info = "\(archive!.name)\n" + "Identifier:\(archive!.identifier)\n" + "Version:\(archive!.version) Build:\(archive!.buildVersion)\n" + "Create Date:\(archive!.dateString)" infoLabel.alignment = .Left infoLabel.stringValue = info let archiveProvisioning = AEProvisioning(filePath: archive!.appPath + "/embedded.mobileprovision"); for (index,provisioning) in provisionings.enumerate(){ if provisioning.identifier == archiveProvisioning.identifier{ provisioningButton.selectItemAtIndex(index) break } } } func reloadArchives(){ let archivePaths = self.archivePaths() archives = [AEArchive]() for path in archivePaths{ archives.append(AEArchive(path: path)) } archives = archives.sort{$0.createDate.compare($1.createDate) == .OrderedDescending} let selectedItem = archiveButton.selectedItem archiveButton.removeAllItems() var archiveNames = [String]() for archive in archives{ let displayName = "\(archive.name)_\(archive.version) \(archive.dateString)" archiveNames.append(displayName); } archiveButton.addItemsWithTitles(archiveNames) for item:NSMenuItem in archiveButton.itemArray{ if item.title == selectedItem?.title{ archiveButton.selectItem(item) break } } provisionings = [AEProvisioning]() let provisioningPaths = self.provisioningPaths() for path in provisioningPaths{ provisionings.append(AEProvisioning(filePath:path)); } provisioningButton.removeAllItems() for (index,provisioning) in provisionings.enumerate(){ if let displayName = provisioning.name{ provisioningButton.addItemWithTitle("(\(index))"+displayName) } else { provisioningButton.addItemWithTitle("(\(index))unknow") } } self.updateArchiveInfo() } func archivePaths()->[String]{ let fileManger = NSFileManager.defaultManager() var archives = [String]() let archivesHome = NSHomeDirectory() + "/Library/Developer/Xcode/Archives/"; if let enumerator = fileManger.enumeratorAtPath(archivesHome){ while let file = enumerator.nextObject() as! String!{ if file.hasSuffix(".xcarchive"){ archives.append(archivesHome+file) enumerator.skipDescendants(); } } } return archives } func provisioningPaths()->[String]{ let fileManger = NSFileManager.defaultManager() var provisionings = [String]() let provisioningsHome = NSHomeDirectory() + "/Library/MobileDevice/Provisioning Profiles/"; if let enumerator = fileManger.enumeratorAtPath(provisioningsHome){ while let file = enumerator.nextObject() as! String!{ if file.hasSuffix(".mobileprovision"){ provisionings.append(provisioningsHome+file) enumerator.skipDescendants(); } } } return provisionings } override func viewDidLoad() { super.viewDidLoad() self.reloadArchives() self.view.window?.delegate = self NSNotificationCenter.defaultCenter().addObserver(self, selector:"applicationDidBecomeActiveNotification:", name: NSApplicationDidBecomeActiveNotification, object:nil) // Do any additional setup after loading the view. } func panel(sender: AnyObject, userEnteredFilename filename: String, confirmed okFlag: Bool) -> String? { if okFlag { let path = sender.URL?!.path self.exportTo(path!) return path } return nil; } func applicationDidBecomeActiveNotification(notification: NSNotification) { self.reloadArchives() } }
apache-2.0
da4c2376dccc433570897f07c0b6d851
33.879828
174
0.599729
5.332677
false
false
false
false
san2ride/Everywhere-Goods
Everywhere/Everywhere/ProductViewController.swift
1
7522
// // ProductViewController.swift // Everywhere // // Created by don't touch me on 4/6/17. // Copyright © 2017 trvl, LLC. All rights reserved. // import UIKit import MapKit import CoreLocation class ProductViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var searchProducts: UISearchBar! @IBOutlet weak var collectionView: UICollectionView! let manager = CLLocationManager() var products: ProductAPI! var productData = [Product]() var filteredProducts = [Product]() var userZipcode: String = "" var currentProduct: Product? override func viewDidLoad() { super.viewDidLoad() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBest manager.requestWhenInUseAuthorization() manager.startUpdatingLocation() products.fetchProducts() { (products) -> Void in self.productData = products print(self.productData) OperationQueue.main.addOperation { if self.userZipcode != "" { self.reloadProductsFrom(zipcode: self.userZipcode) } else { self.collectionView.reloadData() } } } } override func viewWillAppear(_ animated: Bool) { collectionView.prefetchDataSource = self self.searchProducts.delegate = self let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 42)) imageView.contentMode = .scaleAspectFit let image = UIImage(named: "logoBlack") imageView.image = image navigationItem.titleView = imageView } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if searchProducts.text != "" { return self.filteredProducts.count } if filteredProducts.count > 0 { print(filteredProducts) return self.filteredProducts.count } print(self.productData.count) return self.productData.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Product", for: indexPath) as! ProductCollectionViewCell let product: Product if searchProducts.text != "" { product = filteredProducts[indexPath.row] } else if filteredProducts.count > 0{ product = filteredProducts[indexPath.row] } else { product = productData[indexPath.row] } cell.imageView?.imageFromServer(urlString: product.image) cell.name.text = product.title cell.price.text = product.price return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath) as? ProductCollectionViewCell else { return } UIView.animate(withDuration: 0.1, delay: 0, options: [.curveEaseOut], animations: { cell.imageView?.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) }) { (finished) in UIView.animate(withDuration: 0.1, delay: 0, options: [.curveEaseIn], animations: { cell.imageView?.transform = CGAffineTransform.identity }, completion: { [weak self] finished in self?.performSegue(withIdentifier: "ShowItem", sender: self) }) } self.currentProduct = self.productData[(indexPath as NSIndexPath).row] } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let selectedIndex = collectionView.indexPathsForSelectedItems?.first { var photo: Product if filteredProducts.count > 0 { photo = filteredProducts[selectedIndex.row] } else { photo = productData[selectedIndex.row] } let showImage = segue.destination as! ProductDetailViewController print(photo.image) showImage.productImageURL = photo.image let controller = segue.destination as? ProductDetailViewController controller?.theProduct = self.currentProduct } } func reloadProductsFrom(zipcode: String) { print("Reload products") print(zipcode) if productData.isEmpty { return } filteredProducts = self.productData.filter({ (p) -> Bool in return p.tags.lowercased().range(of: zipcode.lowercased()) != nil }) self.collectionView.reloadData() } } extension UIImageView { public func imageFromServer(urlString: String) { URLSession.shared.dataTask(with: URL(string: urlString)!) { (data, response, error) in if error != nil { print(error?.localizedDescription as Any) return } DispatchQueue.main.async(execute: { () -> Void in let image = UIImage(data: data!) self.image = image }) }.resume() } } extension ProductViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { filteredProducts = self.productData.filter({ (p) -> Bool in return p.tags.lowercased().range(of: searchText.lowercased()) != nil }) self.collectionView.reloadData() } } extension ProductViewController: UICollectionViewDataSourcePrefetching { func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { } } extension ProductViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.first let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01) let userLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location!.coordinate.latitude, location!.coordinate.longitude) let region: MKCoordinateRegion = MKCoordinateRegionMake(userLocation, span) CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error) -> Void in if (error != nil) { print(error?.localizedDescription as Any) } if (placemarks?.count)! > 0 { let pm = (placemarks?[0])! as CLPlacemark if let zipcode = pm.postalCode { manager.stopUpdatingLocation() self.userZipcode = zipcode } } }) } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Failed to find user's location: \(error.localizedDescription)") } }
mit
1c0bf6d9e76e4b41bbbeee495a7411bd
31.558442
139
0.594735
5.684807
false
false
false
false
cloudant/swift-cloudant
Tests/SwiftCloudantTests/GetDocumentTests.swift
1
5270
// // GetDocumentTests.swift // SwiftCloudant // // Created by Stefan Kruger on 04/03/2016. // Copyright (c) 2016 IBM Corp. // // 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 SwiftCloudant class GetDocumentTests: XCTestCase { static var allTests = { return [ ("testPutDocument", testPutDocument), ("testGetDocument", testGetDocument), ("testGetDocumentUsingDBAdd", testGetDocumentUsingDBAdd)] }() var dbName: String? = nil var client: CouchDBClient? = nil override func setUp() { super.setUp() dbName = generateDBName() client = CouchDBClient(url: URL(string: url)!, username: username, password: password) createDatabase(databaseName: dbName!, client: client!) } override func tearDown() { deleteDatabase(databaseName: dbName!, client: client!) super.tearDown() print("Deleted database: \(dbName!)") } func testPutDocument() { let data = createTestDocuments(count: 1) let putDocumentExpectation = expectation(description: "put document") let client = CouchDBClient(url: URL(string: url)!, username: username, password: password) let put = PutDocumentOperation(id: UUID().uuidString.lowercased(), body: data[0], databaseName: dbName!) { (response, httpInfo, error) in putDocumentExpectation.fulfill() XCTAssertNil(error) XCTAssertNotNil(response) if let httpInfo = httpInfo { XCTAssert(httpInfo.statusCode == 201 || httpInfo.statusCode == 202) } } client.add(operation: put) waitForExpectations(timeout: 10.0, handler: nil) } func testGetDocument() { let data = createTestDocuments(count: 1) let getDocumentExpectation = expectation(description: "get document") let putDocumentExpectation = self.expectation(description: "put document") let id = UUID().uuidString.lowercased() let put = PutDocumentOperation(id: id, body: data[0], databaseName: dbName!) { (response, httpInfo, operationError) in putDocumentExpectation.fulfill() XCTAssertEqual(id, response?["id"] as? String); XCTAssertNotNil(response?["rev"]) XCTAssertNil(operationError) XCTAssertNotNil(httpInfo) if let httpInfo = httpInfo { XCTAssertTrue(httpInfo.statusCode / 100 == 2) } let get = GetDocumentOperation(id: id, databaseName: self.dbName!) { (response, httpInfo, error) in getDocumentExpectation.fulfill() XCTAssertNil(error) XCTAssertNotNil(response) } self.client!.add(operation: get) }; let nsPut = Operation(couchOperation: put) client?.add(operation: nsPut) nsPut.waitUntilFinished() waitForExpectations(timeout: 10.0, handler: nil) } func testGetDocumentUsingDBAdd() { let data = createTestDocuments(count: 1) let getDocumentExpectation = expectation(description: "get document") let client = CouchDBClient(url: URL(string: url)!, username: username, password: password) let id = UUID().uuidString.lowercased() let putDocumentExpectation = self.expectation(description: "put document") let put = PutDocumentOperation(id: id, body: data[0], databaseName: dbName!) { (response, httpInfo, operationError) in putDocumentExpectation.fulfill() XCTAssertEqual(id, response?["id"] as? String); XCTAssertNotNil(response?["rev"]) XCTAssertNil(operationError) XCTAssertNotNil(httpInfo) if let httpInfo = httpInfo { XCTAssertTrue(httpInfo.statusCode / 100 == 2) } }; let nsPut = Operation(couchOperation: put) client.add(operation: nsPut) nsPut.waitUntilFinished() let get = GetDocumentOperation(id: put.id!, databaseName: self.dbName!) { (response, httpInfo, error) in getDocumentExpectation.fulfill() XCTAssertNil(error) XCTAssertNotNil(response) XCTAssertNotNil(httpInfo) if let httpInfo = httpInfo { XCTAssertEqual(200, httpInfo.statusCode) } } client.add(operation: get) waitForExpectations(timeout: 10.0, handler: nil) } }
apache-2.0
2b6b94e680ec25f7354aa193d1efb993
35.597222
112
0.60759
4.902326
false
true
false
false
roambotics/swift
test/Constraints/tuple.swift
4
11336
// RUN: %target-typecheck-verify-swift // Test various tuple constraints. func f0(x: Int, y: Float) {} var i : Int var j : Int var f : Float func f1(y: Float, rest: Int...) {} func f2(_: (_ x: Int, _ y: Int) -> Int) {} func f2xy(x: Int, y: Int) -> Int {} func f2ab(a: Int, b: Int) -> Int {} func f2yx(y: Int, x: Int) -> Int {} func f3(_ x: (_ x: Int, _ y: Int) -> ()) {} func f3a(_ x: Int, y: Int) {} func f3b(_: Int) {} func f4(_ rest: Int...) {} func f5(_ x: (Int, Int)) {} func f6(_: (i: Int, j: Int), k: Int = 15) {} //===----------------------------------------------------------------------===// // Conversions and shuffles //===----------------------------------------------------------------------===// func foo(a : [(some: Int, (key: Int, value: String))]) -> String { for (i , (j, k)) in a { if i == j { return k } } } func rdar28207648() -> [(Int, CustomStringConvertible)] { let v : [(Int, Int)] = [] return v as [(Int, CustomStringConvertible)] } class rdar28207648Base {} class rdar28207648Derived : rdar28207648Base {} func rdar28207648(x: (Int, rdar28207648Derived)) -> (Int, rdar28207648Base) { return x as (Int, rdar28207648Base) } public typealias Success<T, V> = (response: T, data: V?) public enum Result { case success(Success<Any, Any>) case error(Error) } let a = Success<Int, Int>(response: 3, data: 3) let success: Result = .success(a) // Variadic functions. f4() f4(1) f4(1, 2, 3) f2(f2xy) f2(f2ab) f2(f2yx) f3(f3a) f3(f3b) // expected-error{{cannot convert value of type '(Int) -> ()' to expected argument type '(Int, Int) -> ()'}} func getIntFloat() -> (int: Int, float: Float) {} var values = getIntFloat() func wantFloat(_: Float) {} wantFloat(values.float) var e : (x: Int..., y: Int) // expected-error{{variadic expansion 'Int' must contain at least one variadic generic parameter}} typealias Interval = (a:Int, b:Int) func takeInterval(_ x: Interval) {} takeInterval(Interval(1, 2)) f5((1,1)) // Tuples with existentials var any : Any = () any = (1, 2) any = (label: 4) // expected-error {{cannot create a single-element tuple with an element label}} // Scalars don't have .0/.1/etc i = j.0 // expected-error{{value of type 'Int' has no member '0'}} any.1 // expected-error{{value of type 'Any' has no member '1'}} // expected-note@-1{{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}} any = (5.0, 6.0) as (Float, Float) _ = (any as! (Float, Float)).1 // Fun with tuples protocol PosixErrorReturn { static func errorReturnValue() -> Self } extension Int : PosixErrorReturn { static func errorReturnValue() -> Int { return -1 } } func posixCantFail<A, T : Comparable & PosixErrorReturn> (_ f: @escaping (A) -> T) -> (_ args:A) -> T { return { args in let result = f(args) assert(result != T.errorReturnValue()) return result } } func open(_ name: String, oflag: Int) -> Int { } var foo: Int = 0 var fd = posixCantFail(open)(("foo", 0)) // Tuples and lvalues class C { init() {} func f(_: C) {} } func testLValue(_ c: C) { var c = c c.f(c) let x = c c = x } // <rdar://problem/21444509> Crash in TypeChecker::coercePatternToType func invalidPatternCrash(_ k : Int) { switch k { case (k, cph_: k) as UInt8: // expected-error {{tuple pattern cannot match values of the non-tuple type 'UInt8'}} expected-warning {{cast from 'Int' to unrelated type 'UInt8' always fails}} break } } // <rdar://problem/21875219> Tuple to tuple conversion with IdentityExpr / AnyTryExpr hang class Paws { init() throws {} } func scruff() -> (AnyObject?, Error?) { do { return try (Paws(), nil) } catch { return (nil, error) } } // Test variadics with trailing closures. func variadicWithTrailingClosure(_ x: Int..., y: Int = 2, fn: (Int, Int) -> Int) { } variadicWithTrailingClosure(1, 2, 3) { $0 + $1 } variadicWithTrailingClosure(1) { $0 + $1 } variadicWithTrailingClosure() { $0 + $1 } variadicWithTrailingClosure { $0 + $1 } variadicWithTrailingClosure(1, 2, 3, y: 0) { $0 + $1 } variadicWithTrailingClosure(1, y: 0) { $0 + $1 } variadicWithTrailingClosure(y: 0) { $0 + $1 } variadicWithTrailingClosure(1, 2, 3, y: 0, fn: +) variadicWithTrailingClosure(1, y: 0, fn: +) variadicWithTrailingClosure(y: 0, fn: +) variadicWithTrailingClosure(1, 2, 3, fn: +) variadicWithTrailingClosure(1, fn: +) variadicWithTrailingClosure(fn: +) // <rdar://problem/23700031> QoI: Terrible diagnostic in tuple assignment func gcd_23700031<T>(_ a: T, b: T) { var a = a var b = b (a, b) = (b, a % b) // expected-error {{binary operator '%' cannot be applied to two 'T' operands}} } // <rdar://problem/24210190> // Don't ignore tuple labels in same-type constraints or stronger. protocol Kingdom { associatedtype King } struct Victory<General> { init<K: Kingdom>(_ king: K) where K.King == General {} // expected-note {{where 'General' = '(x: Int, y: Int)', 'K.King' = 'MagicKingdom<(Int, Int)>.King' (aka '(Int, Int)')}} } struct MagicKingdom<K> : Kingdom { typealias King = K } func magnify<T>(_ t: T) -> MagicKingdom<T> { return MagicKingdom() } func foo(_ pair: (Int, Int)) -> Victory<(x: Int, y: Int)> { return Victory(magnify(pair)) // expected-error {{initializer 'init(_:)' requires the types '(x: Int, y: Int)' and 'MagicKingdom<(Int, Int)>.King' (aka '(Int, Int)') be equivalent}} } // https://github.com/apple/swift/issues/43213 // Compiler crashes when accessing a non-existent property of a closure // parameter func call(_ f: (C) -> Void) {} func makeRequest() { call { obj in print(obj.invalidProperty) // expected-error {{value of type 'C' has no member 'invalidProperty'}} } } // <rdar://problem/25271859> QoI: Misleading error message when expression result can't be inferred from closure struct r25271859<T> { } extension r25271859 { func map<U>(f: (T) -> U) -> r25271859<U> { } func andThen<U>(f: (T) -> r25271859<U>) { } } func f(a : r25271859<(Float, Int)>) { a.map { $0.0 } .andThen { _ in print("hello") return r25271859<String>() } } // LValue to rvalue conversions. func takesRValue(_: (Int, (Int, Int))) {} func takesAny(_: Any) {} var x = 0 var y = 0 let _ = (x, (y, 0)) takesRValue((x, (y, 0))) takesAny((x, (y, 0))) // https://github.com/apple/swift/issues/45205 // Closure cannot infer tuple parameter names typealias Closure<A, B> = ((a: A, b: B)) -> String func invoke<A, B>(a: A, b: B, _ closure: Closure<A,B>) { print(closure((a, b))) } invoke(a: 1, b: "B") { $0.b } invoke(a: 1, b: "B") { $0.1 } invoke(a: 1, b: "B") { (c: (a: Int, b: String)) in return c.b } invoke(a: 1, b: "B") { c in return c.b } // Crash with one-element tuple with labeled element class Dinner {} func microwave() -> Dinner? { let d: Dinner? = nil return (n: d) // expected-error{{cannot convert return expression of type '(n: Dinner?)' to return type 'Dinner?'}} } func microwave() -> Dinner { let d: Dinner? = nil return (n: d) // expected-error{{cannot convert return expression of type '(n: Dinner?)' to return type 'Dinner'}} } // Tuple conversion with an optional func f(b: Bool) -> (a: Int, b: String)? { let x = 3 let y = "" return b ? (x, y) : nil } // Single element tuple expressions func singleElementTuple() { let _ = (label: 123) // expected-error {{cannot create a single-element tuple with an element label}} {{12-19=}} let _ = (label: 123).label // expected-error {{cannot create a single-element tuple with an element label}} {{12-19=}} let _ = ((label: 123)) // expected-error {{cannot create a single-element tuple with an element label}} {{13-20=}} let _ = ((label: 123)).label // expected-error {{cannot create a single-element tuple with an element label}} {{13-20=}} } // Tuples with duplicate labels let dupLabel1: (foo: Int, foo: Int) = (foo: 1, foo: 2) // expected-error 2{{cannot create a tuple with a duplicate element label}} func dupLabel2(x a: Int, x b: Int) -> (y: Int, y: Int) { // expected-error {{cannot create a tuple with a duplicate element label}} return (a, b) } let _ = (bar: 0, bar: "") // expected-error {{cannot create a tuple with a duplicate element label}} let zeroTuple = (0,0) if case (foo: let x, foo: let y) = zeroTuple { print(x+y) } // expected-error {{cannot create a tuple with a duplicate element label}} // expected-warning@-1 {{'if' condition is always true}} enum BishBash { case bar(foo: Int, foo: String) } // expected-error@-1 {{invalid redeclaration of 'foo'}} // expected-note@-2 {{'foo' previously declared here}} let enumLabelDup: BishBash = .bar(foo: 0, foo: "") // expected-error {{cannot create a tuple with a duplicate element label}} func dupLabelClosure(_ fn: () -> Void) {} dupLabelClosure { print((bar: "", bar: 5).bar) } // expected-error {{cannot create a tuple with a duplicate element label}} struct DupLabelSubscript { subscript(foo x: Int, foo y: Int) -> Int { return 0 } } let dupLabelSubscriptStruct = DupLabelSubscript() let _ = dupLabelSubscriptStruct[foo: 5, foo: 5] // ok // https://github.com/apple/swift/issues/55316 var dict: [String: (Int, Int)] = [:] let bignum: Int64 = 1337 dict["test"] = (bignum, 1) // expected-error {{cannot assign value of type '(Int64, Int)' to subscript of type '(Int, Int)'}} var tuple: (Int, Int) tuple = (bignum, 1) // expected-error {{cannot assign value of type '(Int64, Int)' to type '(Int, Int)'}} var optionalTuple: (Int, Int)? var optionalTuple2: (Int64, Int)? = (bignum, 1) var optionalTuple3: (UInt64, Int)? = (bignum, 1) // expected-error {{cannot convert value of type '(Int64, Int)' to specified type '(UInt64, Int)?'}} optionalTuple = (bignum, 1) // expected-error {{cannot assign value of type '(Int64, Int)' to type '(Int, Int)'}} // Optional to Optional optionalTuple = optionalTuple2 // expected-error {{cannot assign value of type '(Int64, Int)?' to type '(Int, Int)?'}} func testTupleLabelMismatchFuncConversion(fn1: @escaping ((x: Int, y: Int)) -> Void, fn2: @escaping () -> (x: Int, Int)) { // Warn on mismatches let _: ((a: Int, b: Int)) -> Void = fn1 // expected-warning {{tuple conversion from '(a: Int, b: Int)' to '(x: Int, y: Int)' mismatches labels}} let _: ((x: Int, b: Int)) -> Void = fn1 // expected-warning {{tuple conversion from '(x: Int, b: Int)' to '(x: Int, y: Int)' mismatches labels}} let _: () -> (y: Int, Int) = fn2 // expected-warning {{tuple conversion from '(x: Int, Int)' to '(y: Int, Int)' mismatches labels}} let _: () -> (y: Int, k: Int) = fn2 // expected-warning {{tuple conversion from '(x: Int, Int)' to '(y: Int, k: Int)' mismatches labels}} // Attempting to shuffle has always been illegal here let _: () -> (y: Int, x: Int) = fn2 // expected-error {{cannot convert value of type '() -> (x: Int, Int)' to specified type '() -> (y: Int, x: Int)'}} // Losing labels is okay though. let _: () -> (Int, Int) = fn2 // Gaining labels also okay. let _: ((x: Int, Int)) -> Void = fn1 let _: () -> (x: Int, y: Int) = fn2 let _: () -> (Int, y: Int) = fn2 } func testTupleLabelMismatchKeyPath() { // Very Cursed. let _: KeyPath<(x: Int, y: Int), Int> = \(a: Int, b: Int).x // expected-warning@-1 {{tuple conversion from '(a: Int, b: Int)' to '(x: Int, y: Int)' mismatches labels}} }
apache-2.0
a6671eb5c222abe891826f2081374f55
29.720867
192
0.622354
3.133223
false
false
false
false
austinzmchen/guildOfWarWorldBosses
GoWWorldBosses/Views/WBCoinView.swift
1
2857
// // WBCoinView.swift // GoWWorldBosses // // Created by Austin Chen on 2017-03-04. // Copyright © 2017 Austin Chen. All rights reserved. // import UIKit @IBDesignable class WBCoinView: UIView { @IBOutlet var contentView: UIView! @IBOutlet weak var goldLabel: UILabel! @IBOutlet weak var goldDividerView: UIView! @IBOutlet weak var silverLabel: UILabel! @IBOutlet weak var silverDividerView: UIView! @IBOutlet weak var bronzeLabel: UILabel! // MARK: life cycles override init(frame: CGRect) { // 1. setup any properties here // 2. call super.init(frame:) super.init(frame: frame) // 3. Setup view from .xib file xibSetup() } required init?(coder aDecoder: NSCoder) { // 1. setup any properties here // 2. call super.init(coder:) super.init(coder: aDecoder) // 3. Setup view from .xib file xibSetup() } func xibSetup() { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: "WBCoinView", bundle: bundle) contentView = nib.instantiate(withOwner: self, options: nil)[0] as! UIView self.addSubview(contentView) contentView.frame = self.bounds } override var intrinsicContentSize: CGSize { let s = CGSize(width: bronzeLabel.frame.maxX, height: self.goldDividerView.bounds.height) return s } // MARK: instance methods /* http://stackoverflow.com/questions/18065938/how-to-use-auto-layout-to-move-other-views-when-a-view-is-hidden to resize child views when removing other child views, need to over-constraint. eg, add leading constraint to previous view's trailing as well as leading to superview's lead constraint. I used inequality instead of priority, priority does not work for me. */ var coinValue: Int { get { let gold = Int(goldLabel.text!)! let silver = Int(silverLabel.text!)! let bronze = Int(bronzeLabel.text!)! return gold * 10000 + silver * 100 + bronze } set { // hide gold or silver if 0 let gold = newValue / 10000 goldLabel.text = String(format: "%d", gold) if gold == 0 { goldLabel.removeFromSuperview() goldDividerView.removeFromSuperview() } let silver = (newValue / 100) % 100 silverLabel.text = String(format: "%d", silver) if silver == 0 { silverLabel.removeFromSuperview() silverDividerView.removeFromSuperview() } bronzeLabel.text = String(format: "%d", newValue % 100) self.invalidateIntrinsicContentSize() } } }
mit
b569d3cf7693286ccdb0df1ec2914ff0
31.089888
261
0.588936
4.533333
false
false
false
false
richardpiazza/XCServerCoreData
Sources/Commit.swift
1
2266
import Foundation import CoreData import CodeQuickKit import XCServerAPI public class Commit: NSManagedObject { public convenience init?(managedObjectContext: NSManagedObjectContext, identifier: String, repository: Repository) { self.init(managedObjectContext: managedObjectContext) self.commitHash = identifier self.repository = repository } public func update(withCommit commit: XCSRepositoryCommit, integration: Integration? = nil) { guard let moc = self.managedObjectContext else { Log.warn("\(#function) failed; MOC is nil") return } self.message = commit.message if let commitTimestamp = commit.timestamp { // TODO: Commit Timestamp should be a DATE! self.timestamp = XCServerCoreData.dateFormatter.string(from: commitTimestamp) } if let contributor = commit.contributor { if self.commitContributor == nil { self.commitContributor = CommitContributor(managedObjectContext: moc, commit: self) } self.commitContributor?.update(withCommitContributor: contributor) } if let filePaths = commit.commitChangeFilePaths { for commitChange in filePaths { guard self.commitChanges?.contains(where: { (cc: CommitChange) -> Bool in return cc.filePath == commitChange.filePath }) == false else { continue } if let change = CommitChange(managedObjectContext: moc, commit: self) { change.update(withCommitChange: commitChange) } } } if let integration = integration { guard moc.revisionBlueprint(withCommit: self, andIntegration: integration) == nil else { return } let _ = RevisionBlueprint(managedObjectContext: moc, commit: self, integration: integration) } } public var commitTimestamp: Date? { guard let timestamp = self.timestamp else { return nil } return XCServerCoreData.dateFormatter.date(from: timestamp) } }
mit
3761c2e86e0c93e49e1d5089d613cd8f
35.548387
152
0.601059
5.608911
false
false
false
false
tiagobsbraga/HotmartTest
HotmartTest/MainViewController.swift
1
751
// // MainViewController.swift // HotmartTest // // Created by Tiago Braga on 05/02/17. // Copyright © 2017 Tiago Braga. All rights reserved. // import UIKit import SlideMenuControllerSwift class MainViewController: SlideMenuController { override func awakeFromNib() { self.mainViewController = AppStoryboard.Dashboard.instance.instantiateViewController(withIdentifier: "Main") self.leftViewController = AppStoryboard.Main.instance.instantiateViewController(withIdentifier: "Menu") SlideMenuOptions.contentViewScale = 1 SlideMenuOptions.contentViewOpacity = 0.3 SlideMenuOptions.opacityViewBackgroundColor = Style.Color.black super.awakeFromNib() } }
mit
d4db096dab821bf9d64a72800f6b9287
27.846154
116
0.714667
5.357143
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/PIPVideoWindow.swift
1
12164
// // PIPVideoWindow.swift // Telegram // // Created by keepcoder on 26/04/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import AVKit import SwiftSignalKit private let pipFrameKey: String = "kPipFrameKey3" enum PictureInPictureControlMode { case normal case pip } protocol PictureInPictureControl { func pause() func play() func didEnter() func didExit() var view: NSView { get } var isPictureInPicture: Bool { get } func setMode(_ mode: PictureInPictureControlMode, animated: Bool) } private class PictureInpictureView : Control { private let _window: Window init(frame: NSRect, window: Window) { _window = window super.init(frame: frame) autoresizesSubviews = true } override func mouseEntered(with event: NSEvent) { super.mouseEntered(with: event) } override func mouseExited(with event: NSEvent) { super.mouseEntered(with: event) } required init?(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } override var window: NSWindow? { set { } get { return _window } } } fileprivate class ModernPictureInPictureVideoWindow: NSPanel { private let saver: WindowSaver fileprivate let _window: Window fileprivate let control: PictureInPictureControl private let rect:NSRect private let restoreRect: NSRect fileprivate var forcePaused: Bool = false fileprivate let item: MGalleryItem fileprivate weak var _delegate: InteractionContentViewProtocol? fileprivate let _contentInteractions:ChatMediaLayoutParameters? fileprivate let _type: GalleryAppearType fileprivate let viewer: GalleryViewer fileprivate var eventLocalMonitor: Any? fileprivate var eventGlobalMonitor: Any? private var hideAnimated: Bool = true private let lookAtMessageDisposable = MetaDisposable() init(_ control: PictureInPictureControl, item: MGalleryItem, viewer: GalleryViewer, origin:NSPoint, delegate:InteractionContentViewProtocol? = nil, contentInteractions:ChatMediaLayoutParameters? = nil, type: GalleryAppearType) { self.viewer = viewer self._delegate = delegate self._contentInteractions = contentInteractions self._type = type self.control = control let minSize = control.view.frame.size.aspectFilled(NSMakeSize(120, 120)) let size = item.notFittedSize.aspectFilled(NSMakeSize(250, 250)).aspectFilled(minSize) let newRect = NSMakeRect(origin.x, origin.y, size.width, size.height) self.rect = newRect self.restoreRect = NSMakeRect(origin.x, origin.y, control.view.frame.width, control.view.frame.height) self.item = item _window = Window(contentRect: newRect, styleMask: [.resizable], backing: .buffered, defer: true) _window.name = "pip" self.saver = .find(for: _window) _window.setFrame(NSMakeRect(3000, 3000, saver.rect.width, saver.rect.height), display: true) super.init(contentRect: newRect, styleMask: [.resizable, .nonactivatingPanel], backing: .buffered, defer: true) //self.isOpaque = false self.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]; let view = PictureInpictureView(frame: bounds, window: _window) self.contentView = view view.forceMouseDownCanMoveWindow = true // self.contentView?.wantsLayer = true; self.contentView?.layer?.cornerRadius = 4; self.backgroundColor = .clear; control.view.frame = NSMakeRect(0, 0, newRect.width, newRect.height) // control.view.autoresizingMask = [.width, .height]; control.view.setFrameOrigin(0, 0) // contentView?.autoresizingMask = [.width, .height] contentView?.addSubview(control.view) _window.set(mouseHandler: { event -> KeyHandlerResult in NSCursor.arrow.set() return .invoked }, with: self, for: .mouseMoved, priority: .low) _window.set(mouseHandler: { event -> KeyHandlerResult in NSCursor.arrow.set() return .invoked }, with: self, for: .mouseEntered, priority: .low) _window.set(mouseHandler: { event -> KeyHandlerResult in return .invoked }, with: self, for: .mouseExited, priority: .low) _window.set(mouseHandler: { [weak self] event -> KeyHandlerResult in if event.clickCount == 2, let strongSelf = self { let inner = strongSelf.control.view.convert(event.locationInWindow, from: nil) if NSWindow.windowNumber(at: NSEvent.mouseLocation, belowWindowWithWindowNumber: 0) == strongSelf.windowNumber, strongSelf.control.view.hitTest(inner) is MediaPlayerView { strongSelf.hide() } } return .invoked }, with: self, for: .leftMouseDown, priority: .low) _window.set(mouseHandler: { [weak self] event -> KeyHandlerResult in self?.findAndMoveToCorner() return .rejected }, with: self, for: .leftMouseUp, priority: .low) self.level = .modalPanel self.isMovableByWindowBackground = true NotificationCenter.default.addObserver(self, selector: #selector(windowDidResized(_:)), name: NSWindow.didResizeNotification, object: self) eventLocalMonitor = NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved, .mouseEntered, .mouseExited, .leftMouseDown, .leftMouseUp], handler: { [weak self] event in guard let `self` = self else {return event} self._window.sendEvent(event) return event }) eventGlobalMonitor = NSEvent.addGlobalMonitorForEvents(matching: [.mouseMoved, .mouseEntered, .mouseExited, .leftMouseDown, .leftMouseUp], handler: { [weak self] event in guard let `self` = self else {return} self._window.sendEvent(event) }) if let message = item.entry.message { let messageView = item.context.account.postbox.messageView(message.id) |> deliverOnMainQueue lookAtMessageDisposable.set(messageView.start(next: { [weak self] view in if view.message == nil { self?.hideAnimated = true self?.hide() } })) } self.control.setMode(.pip, animated: true) } func hide() { if hideAnimated { contentView?._change(opacity: 0, animated: true, duration: 0.1, timingFunction: .linear) setFrame(NSMakeRect(frame.minX + (frame.width - 0) / 2, frame.minY + (frame.height - 0) / 2, 0, 0), display: true, animate: true) } orderOut(nil) window = nil _window.removeAllHandlers(for: self) if let monitor = eventLocalMonitor { NSEvent.removeMonitor(monitor) } if let monitor = eventGlobalMonitor { NSEvent.removeMonitor(monitor) } } override func orderOut(_ sender: Any?) { super.orderOut(sender) window = nil if control.isPictureInPicture { control.pause() } } func openGallery() { setFrame(restoreRect, display: true, animate: true) hideAnimated = false hide() showGalleryFromPip(item: item, gallery: self.viewer, delegate: _delegate, contentInteractions: _contentInteractions, type: _type) } deinit { if control.isPictureInPicture { control.pause() } self.control.setMode(.normal, animated: true) NotificationCenter.default.removeObserver(self) lookAtMessageDisposable.dispose() } override func animationResizeTime(_ newFrame: NSRect) -> TimeInterval { return 0.2 } @objc func windowDidResized(_ notification: Notification) { } private func findAndMoveToCorner() { if let screen = self.screen { let rect = screen.frame.offsetBy(dx: -screen.visibleFrame.minX, dy: -screen.visibleFrame.minY) let point = self.frame.offsetBy(dx: -screen.visibleFrame.minX, dy: -screen.visibleFrame.minY) var options:BorderType = [] if point.maxX > rect.width && point.minX < rect.width { options.insert(.Right) } if point.minX < 0 { options.insert(.Left) } if point.minY < 0 { options.insert(.Bottom) } var newFrame = self.frame if options.contains(.Right) { newFrame.origin.x = screen.visibleFrame.maxX - newFrame.width - 30 } if options.contains(.Bottom) { newFrame.origin.y = screen.visibleFrame.minY + 30 } if options.contains(.Left) { newFrame.origin.x = screen.visibleFrame.minX + 30 } setFrame(newFrame, display: true, animate: true) } } override var isResizable: Bool { return true } override func setFrame(_ frameRect: NSRect, display flag: Bool, animate animateFlag: Bool) { super.setFrame(frameRect, display: flag, animate: animateFlag) saver.rect = frameRect saver.save() } override func makeKeyAndOrderFront(_ sender: Any?) { super.makeKeyAndOrderFront(sender) if let screen = NSScreen.main { let savedRect: NSRect = NSMakeRect(0, 0, screen.frame.width * 0.3, screen.frame.width * 0.3) let convert_s = self.rect.size.aspectFilled(NSMakeSize(min(savedRect.width, 250), min(savedRect.height, 250))) self.aspectRatio = self.rect.size.fitted(NSMakeSize(savedRect.width, savedRect.height)) self.minSize = self.rect.size.aspectFitted(NSMakeSize(savedRect.width, savedRect.height)).aspectFilled(NSMakeSize(120, 120)) let frame = NSScreen.main?.frame ?? NSMakeRect(0, 0, 1920, 1080) self.maxSize = self.rect.size.aspectFitted(frame.size) var rect = saver.rect.size.bounds rect.origin = NSMakePoint(screen.frame.width - convert_s.width - 30, screen.frame.height - convert_s.height - 50) self.setFrame(NSMakeRect(saver.rect.minX, saver.rect.minY, convert_s.width, convert_s.height), display: true, animate: true) } } } private var window: NSWindow? var hasPictureInPicture: Bool { return window != nil } func showPipVideo(control: PictureInPictureControl, viewer: GalleryViewer, item: MGalleryItem, origin: NSPoint, delegate:InteractionContentViewProtocol? = nil, contentInteractions:ChatMediaLayoutParameters? = nil, type: GalleryAppearType) { closePipVideo() window = ModernPictureInPictureVideoWindow(control, item: item, viewer: viewer, origin: origin, delegate: delegate, contentInteractions: contentInteractions, type: type) window?.makeKeyAndOrderFront(nil) } func exitPictureInPicture() { if let window = window as? ModernPictureInPictureVideoWindow { window.openGallery() } } func pausepip() { if let window = window as? ModernPictureInPictureVideoWindow { window.control.pause() window.forcePaused = true } } func playPipIfNeeded() { if let window = window as? ModernPictureInPictureVideoWindow, window.forcePaused { window.control.play() } } func closePipVideo() { if let window = window as? ModernPictureInPictureVideoWindow { window.hide() window.control.pause() } window = nil }
gpl-2.0
82afd32814e37f958fcbf037f67e48bf
33.358757
240
0.622708
4.575997
false
false
false
false
zhangao0086/DKPhotoGallery
DKPhotoGallery/Transition/DKPhotoGalleryTransitionController.swift
2
2079
// // DKPhotoGalleryTransitionController.swift // DKPhotoGallery // // Created by ZhangAo on 09/09/2017. // Copyright © 2017 ZhangAo. All rights reserved. // import UIKit open class DKPhotoGalleryTransitionController: UIPresentationController, UIViewControllerTransitioningDelegate { open var gallery: DKPhotoGallery! internal var interactiveController: DKPhotoGalleryInteractiveTransition? init(gallery: DKPhotoGallery, presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { super.init(presentedViewController: presentedViewController, presenting: presentingViewController) self.gallery = gallery } internal func prepareInteractiveGesture() { self.interactiveController = DKPhotoGalleryInteractiveTransition(gallery: self.gallery) } // MARK: - UIViewControllerTransitioningDelegate public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { let presentAnimator = DKPhotoGalleryTransitionPresent() presentAnimator.gallery = self.gallery return presentAnimator } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { let dismissAnimator = DKPhotoGalleryTransitionDismiss() dismissAnimator.gallery = self.gallery return dismissAnimator } public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if let interactiveController = self.interactiveController, interactiveController.isInteracting { return interactiveController } else { return nil } } public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return nil } }
mit
fd03aa1e4bc7c5788a4b737617914881
38.207547
177
0.753609
6.973154
false
false
false
false
kpiteira/MobileAzureDevDays
Swift/MobileAzureDevDays/MobileAzureDevDays/SentimentClient.swift
1
3299
// // SentimentClient.swift // MobileAzureDevDays // // Created by Colby Williams on 9/22/17. // Copyright © 2017 Colby Williams. All rights reserved. // import Foundation import UIKit class SentimentClient { static let shared: SentimentClient = { let instance = SentimentClient() return instance }() let textId = "sentimentText" let contentType = "application/json" let endpoint = "https://%@.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment" let apiKeyPreference = "\(Bundle.main.bundleIdentifier ?? "cognitive.text").apiKey" let regionPreference = "\(Bundle.main.bundleIdentifier ?? "cognitive.text").region" var apiKey: String? { get { return UserDefaults.standard.string(forKey: apiKeyPreference) } set(val) { UserDefaults.standard.set(val, forKey: apiKeyPreference) } } var region: String? { get { return UserDefaults.standard.string(forKey: regionPreference)! } set(val) { UserDefaults.standard.set(val, forKey: regionPreference) } } init(){ region = "eastus2" } func obtainKey(callback: @escaping (SentimentApiKeyDocument?) -> ()) { let url = URL(string: "https://vsmcsentimentdemo.azurewebsites.net/api/GetSentimentKey") var request = URLRequest(url: url!) request.httpMethod = "GET" request.addValue(contentType, forHTTPHeaderField: "Content-Type") UIApplication.shared.isNetworkActivityIndicatorVisible = true URLSession.shared.dataTask(with: request) { (data, response, error) in if let error = error { print(error.localizedDescription) } if let data=data, let keyData = try? JSONSerialization.jsonObject(with: data) as? [String:Any], let keyJson = keyData { DispatchQueue.main.async { callback(SentimentApiKeyDocument(fromJson: keyJson)) } } else { DispatchQueue.main.async { callback(nil) } } }.resume() } func determineSentiment(_ text:String, callback: @escaping (SentimentResponse?) -> ()) { if let apiKey = apiKey, let region = region, let data = try? JSONSerialization.data(withJSONObject: [ "documents" : [ [ "language" : Locale.current.languageCode ?? "en", "id" : textId, "text" : text ] ] ], options: []) { let url = URL(string: String(format: endpoint, region)) var request = URLRequest(url: url!) request.httpMethod = "POST" request.addValue(contentType, forHTTPHeaderField: "Content-Type") request.addValue(apiKey, forHTTPHeaderField: "Ocp-Apim-Subscription-Key") request.httpBody = data UIApplication.shared.isNetworkActivityIndicatorVisible = true URLSession.shared.dataTask(with: request) { (data, response, error) in DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false } if let error = error { print(error.localizedDescription) } if let data = data, let sentimentData = try? JSONSerialization.jsonObject(with: data) as? [String:Any], let sentimentJson = sentimentData { DispatchQueue.main.async { callback(SentimentResponse(fromJson: sentimentJson)) } } else { DispatchQueue.main.async { callback(nil) } } }.resume() } } }
mit
fee7e3ff813aca7d665ea3d9a69e569f
35.644444
222
0.667981
4.1225
false
false
false
false
inamiy/ReactiveCocoaCatalog
ReactiveCocoaCatalog/Samples/MenuId.swift
1
1029
// // MenuId.swift // ReactiveCocoaCatalog // // Created by Yasuhiro Inami on 2016-04-09. // Copyright © 2016 Yasuhiro Inami. All rights reserved. // import UIKit import Result import ReactiveSwift import FontAwesome enum MenuId: Int { case friends = 0 case chats = 1 case home = 2 case settings = 3 case profile = 10 case help = 11 static let allMenuIds = [0...3, 10...11].flatMap { $0.flatMap { MenuId(rawValue: $0) } } var fontAwesome: FontAwesome { switch self { case .friends: return .users case .chats: return .comment case .home: return .home case .settings: return .gear case .profile: return .user case .help: return .question } } var tabImage: UIImage { return UIImage.fontAwesomeIcon( name: self.fontAwesome, textColor: UIColor.black, size: CGSize(width: 40, height: 40) ) } }
mit
743db10355d843bfa795b3aa1e00a27e
21.347826
92
0.557393
4.079365
false
false
false
false
GitNK/NCGraph
Graph/DFS.swift
1
6141
// // DFS.swift // NCGraph // // Created by Nikita Gromadskyi on 10/21/16. // Copyright © 2016 Nikita Gromadskyi. All rights reserved. // import Foundation extension NCGraph { /// A Boolean value indicating if `self` is directed acyclic graph public var isDAG :Bool { if edgeCount < 1 || !isDirected { return false } /// Set of deleted sink nodes var deleted = Set<Name>() /// Set of explored nodes var explored = Set<Name>() var hasCycle = false for node in nodes() { if !explored.contains(node.name){ dfsCycleFinder(sourceNode: node, explored: &explored, deleted: &deleted, hasCycle: &hasCycle) } if hasCycle {return false} /// Early exit } return !hasCycle } /// Checks if `self` is directed strongly connected graph public var isStronglyConnected: Bool { return scc()?.count == 1 } /// returns topologicaly sorted nodes for directed acyclic graph, nil if topological in not possible public func topSort() -> [NodeType]? { if !isDirected || !isDAG {return nil} var sortedNodes = [NodeType]() sortedNodes.reserveCapacity(nodeCount) var explored = Set<Name>() for node in nodes() { if !explored.contains(node.name) { dfs(sourceNode: node, explored: &explored, sortedNodes: &sortedNodes) } } return sortedNodes.reversed() } /// Method for finding strongly connected components /// of directed graph. /// - returns: 2d array representing strongly connected components, /// nil if none exist for `self` public func scc() -> [[NodeType]]? { if !isDirected || isEmpty {return nil} var _scc = [[NodeType]]() /// explored nodes var explored = Set<Name>() var newOrder = [NodeType]() /// first loop for node in nodes() { if !explored.contains(node.name) { dfsRev(sourceNode: node, explored: &explored, sortedNodes: &newOrder) } } /// reset explored nodes explored = Set<Name>() /// i-th strong component var strongComponent: [NodeType] /// second loop for node in newOrder.reversed() { if !explored.contains(node.name) { strongComponent = [NodeType]() dfs(sourceNode: node, explored: &explored, sortedNodes: &strongComponent) _scc.append(strongComponent) } } return _scc } //# MARK: - Private section private func dfs(sourceNode: NodeType, explored: inout Set<Name>, sortedNodes: inout [NodeType]) { /// stack of nodes var nodesToProcess = [sourceNode] while nodesToProcess.count > 0 { var inserted = false guard let current = nodesToProcess.last else {fatalError()} explored.insert(current.name) guard let outEdges = self.outDegreeEdgesFor(node: current) else {fatalError()} for edge in outEdges { if !explored.contains(edge.head.name) { explored.insert(edge.head.name) nodesToProcess.append(edge.head) inserted = true break } } if !inserted { nodesToProcess.removeLast() sortedNodes.append(current) } } } /// DFS with reversed direction edges private func dfsRev(sourceNode: NodeType, explored: inout Set<Name>, sortedNodes: inout [NodeType]) { /// nodes stack var nodesToProcess = [sourceNode] while nodesToProcess.count > 0 { var inserted = false guard let current = nodesToProcess.last else {fatalError()} explored.insert(current.name) guard let inEdges = self.inDegreeEdgesFor(node: current) else {fatalError()} for edge in inEdges { if !explored.contains(edge.tail.name) { explored.insert(edge.tail.name) nodesToProcess.append(edge.tail) inserted = true break } } if !inserted { nodesToProcess.removeLast() sortedNodes.append(current) } } } /// DFS Hepler for finding cycles in `self` private func dfsCycleFinder(sourceNode: NodeType, explored: inout Set<Name>, deleted: inout Set<Name>, hasCycle: inout Bool) { /// nodes stack var nodesToProcess = [sourceNode] while nodesToProcess.count > 0 { var inserted = false guard let current = nodesToProcess.last else {fatalError()} explored.insert(current.name) guard let outEdges = self.outDegreeEdgesFor(node: current) else {fatalError()} for edge in outEdges { if !explored.contains(edge.head.name) { explored.insert(edge.head.name) nodesToProcess.append(edge.head) inserted = true break } else { /// check if head node has been marked as deleted if !deleted.contains(edge.head.name) { hasCycle = true } } } if !inserted { nodesToProcess.removeLast() deleted.insert(current.name) } } } }
mit
f35512177321dd799299f94955173407
34.085714
104
0.500651
4.955609
false
false
false
false
sarvex/SwiftRecepies
Motion/Retrieving Pedometer Data/Retrieving Pedometer Data/AppDelegate.swift
1
3612
// // AppDelegate.swift // Retrieving Pedometer Data // // Created by vandad on 177//14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // /* 1 */ //import UIKit //import CoreMotion // //@UIApplicationMain //class AppDelegate: UIResponder, UIApplicationDelegate { // // var window: UIWindow? // lazy var pedometer = CMPedometer() // // func application(application: UIApplication, // didFinishLaunchingWithOptions launchOptions: // [NSObject : AnyObject]?) -> Bool { // return true // } // // func applicationDidBecomeActive(application: UIApplication) { // if CMPedometer.isStepCountingAvailable(){ // // pedometer.startPedometerUpdatesFromDate(NSDate(), withHandler: { // (data: CMPedometerData!, error: NSError!) in // // println("Number of steps = \(data.numberOfSteps)") // // }) // // } else { // println("Step counting is not available") // } // } // // func applicationWillResignActive(application: UIApplication) { // pedometer.stopPedometerUpdates() // } // //} /* 2 */ //import UIKit //import CoreMotion // ///* A really simple extension on NSDate that gives us convenience methods //for "now" and "yesterday" */ //extension NSDate{ // class func now() -> NSDate{ // return NSDate() // } // class func yesterday() -> NSDate{ // return NSDate(timeIntervalSinceNow: -(24 * 60 * 60)) // } //} // //@UIApplicationMain //class AppDelegate: UIResponder, UIApplicationDelegate { // // var window: UIWindow? // lazy var pedometer = CMPedometer() // // func application(application: UIApplication, // didFinishLaunchingWithOptions launchOptions: // [NSObject : AnyObject]?) -> Bool { // return true // } // // func applicationDidBecomeActive(application: UIApplication) { // // /* Can we ask for distance updates? */ // if CMPedometer.isDistanceAvailable(){ // // pedometer.queryPedometerDataFromDate(NSDate.yesterday(), // toDate: NSDate.now(), // withHandler: {(data: CMPedometerData!, error: NSError!) in // // println("Distance travelled from yesterday to now " + // "= \(data.distance) meters") // // }) // // } else { // println("Distance counting is not available") // } // } // // func applicationWillResignActive(application: UIApplication) { // pedometer.stopPedometerUpdates() // } // //} /* 3 */ import UIKit import CoreMotion extension NSDate{ class func now() -> NSDate{ return NSDate() } class func tenMinutesAgo() -> NSDate{ return NSDate(timeIntervalSinceNow: -(10 * 60)) } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var pedometer = CMPedometer() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { return true } func applicationDidBecomeActive(application: UIApplication) { /* Can we ask for floor climb/descending updates? */ if CMPedometer.isFloorCountingAvailable(){ pedometer.queryPedometerDataFromDate(NSDate.tenMinutesAgo(), toDate: NSDate.now(), withHandler: {(data: CMPedometerData!, error: NSError!) in println("Floors ascended = \(data.floorsAscended)") println("Floors descended = \(data.floorsAscended)") }) } else { println("Floor counting is not available") } } func applicationWillResignActive(application: UIApplication) { pedometer.stopPedometerUpdates() } }
isc
6dbed070e7165155d81d21e569d2387f
23.739726
74
0.644518
4.113895
false
false
false
false
ryansong/cameraPhotoDemo
cameraPhotoDemo/SYBCollectionViewCell.swift
1
808
// // SYBCollectionViewCell.swift // cameraPhotoDemo // // Created by Ryan on 5/2/17. // Copyright © 2017 Song Xiaoming. All rights reserved. // import UIKit class SYBCollectionViewCell: UICollectionViewCell { let imageView:UIImageView = UIImageView() override func layoutSubviews() { super.layoutSubviews() self.imageView.frame = self.bounds } func setupCell(model:SYBImageAssetModel) -> Void { self.imageView.image = model.image if (model.image == nil && model.imageAsset != nil) { model.image = model.imageAsset?.image(with: self.traitCollection) self.imageView.image = model.image } } override func prepareForReuse() { self.imageView.image = nil; } }
mit
04384e42d04952aef3a6d3b9426a68d0
23.454545
78
0.614622
4.38587
false
false
false
false
gregomni/swift
test/Constraints/diagnostics.swift
2
71113
// RUN: %target-typecheck-verify-swift protocol P { associatedtype SomeType } protocol P2 { func wonka() } extension Int : P { typealias SomeType = Int } extension Double : P { typealias SomeType = Double } func f0(_ x: Int, _ y: Float) { } func f1(_: @escaping (Int, Float) -> Int) { } func f2(_: (_: (Int) -> Int)) -> Int {} func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {} func f4(_ x: Int) -> Int { } func f5<T : P2>(_ : T) { } // expected-note@-1 {{required by global function 'f5' where 'T' = '(Int) -> Int'}} // expected-note@-2 {{required by global function 'f5' where 'T' = '(Int, String)'}} // expected-note@-3 {{required by global function 'f5' where 'T' = 'Int.Type'}} // expected-note@-4 {{where 'T' = 'Int'}} func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {} var i : Int var d : Double // Check the various forms of diagnostics the type checker can emit. // Tuple size mismatch. f1( f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}} ) // Tuple element unused. f0(i, i, // expected-error@:7 {{cannot convert value of type 'Int' to expected argument type 'Float'}} i) // expected-error{{extra argument in call}} // Cannot conform to protocols. f5(f4) // expected-error {{type '(Int) -> Int' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} f5((1, "hello")) // expected-error {{type '(Int, String)' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} f5(Int.self) // expected-error {{type 'Int.Type' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} // Tuple element not convertible. f0(i, d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}} ) // Function result not a subtype. f1( f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}} ) f3( f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}} ) f4(i, d) // expected-error {{extra argument in call}} // Missing member. i.missingMember() // expected-error{{value of type 'Int' has no member 'missingMember'}} // Generic member does not conform. extension Int { func wibble<T: P2>(_ x: T, _ y: T) -> T { return x } // expected-note {{where 'T' = 'Int'}} func wubble<T>(_ x: (Int) -> T) -> T { return x(self) } } i.wibble(3, 4) // expected-error {{instance method 'wibble' requires that 'Int' conform to 'P2'}} // Generic member args correct, but return type doesn't match. struct A : P2 { func wonka() {} } let a = A() for j in i.wibble(a, a) { // expected-error {{for-in loop requires 'A' to conform to 'Sequence'}} } // Generic as part of function/tuple types func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}} return (c: 0, i: g(())) } func f7() -> (c: Int, v: A) { let g: (Void) -> A = { _ in return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}} return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}} } func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{where 'T' = 'Int'}} // expected-note@-1 {{required by global function 'f8' where 'T' = '(Int, Double)'}} f8(3, f4) // expected-error {{global function 'f8' requires that 'Int' conform to 'P2'}} typealias Tup = (Int, Double) func f9(_ x: Tup) -> Tup { return x } f8((1,2.0), f9) // expected-error {{type '(Int, Double)' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} // <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals 1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}} [1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}} "awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}} // Does not conform to protocol. f5(i) // expected-error {{global function 'f5' requires that 'Int' conform to 'P2'}} // Make sure we don't leave open existentials when diagnosing. // <rdar://problem/20598568> func pancakes(_ p: P2) { f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}} f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}} } protocol Shoes { static func select(_ subject: Shoes) -> Self } // Here the opaque value has type (metatype_type (archetype_type ... )) func f(_ x: Shoes, asType t: Shoes.Type) { return t.select(x) // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } precedencegroup Starry { associativity: left higherThan: MultiplicationPrecedence } infix operator **** : Starry func ****(_: Int, _: String) { } i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} infix operator ***~ : Starry func ***~(_: Int, _: String) { } i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} @available(*, unavailable, message: "call the 'map()' method on the sequence") public func myMap<C : Collection, T>( // expected-note {{'myMap' has been explicitly marked unavailable here}} _ source: C, _ transform: (C.Iterator.Element) -> T ) -> [T] { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "call the 'map()' method on the optional value") public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? { fatalError("unavailable function can't be called") } // <rdar://problem/20142523> func rdar20142523() { _ = myMap(0..<10, { x in // expected-error {{'myMap' is unavailable: call the 'map()' method on the sequence}} () return x }) } // <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral func rdar21080030() { var s = "Hello" // SR-7599: This should be `cannot_call_non_function_value` if s.count() == 0 {} // expected-error{{cannot call value of non-function type 'Int'}} {{13-15=}} } // <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136()'}} r21248136() // expected-error {{generic parameter 'T' could not be inferred}} let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}} // <rdar://problem/17080659> Error Message QOI - wrong return type in an overload func recArea(_ h: Int, w : Int) { return h * w // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong func r17224804(_ monthNumber : Int) { // expected-error@+1:49 {{cannot convert value of type 'Int' to expected argument type 'String'}} let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber) } // <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?' func r17020197(_ x : Int?, y : Int) { if x! { } // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} // <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible if y {} // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} } // <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different func validateSaveButton(_ text: String) { return (text.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}} expected-note {{did you mean to add a return type?}} } // <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype class r20201968C { func blah() { r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}} } } // <rdar://problem/21459429> QoI: Poor compilation error calling assert func r21459429(_ a : Int) { assert(a != nil, "ASSERT COMPILATION ERROR") // expected-warning @-1 {{comparing non-optional value of type 'Int' to 'nil' always returns true}} } // <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an argument of type 'Int' struct StructWithOptionalArray { var array: [Int]? } func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int { return foo.array[0] // expected-error {{value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'}} // expected-note@-1{{chain the optional using '?' to access member 'subscript' only for non-'nil' base values}}{{19-19=?}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{19-19=!}} } // <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}} // <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf String().asdf // expected-error {{value of type 'String' has no member 'asdf'}} // <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment protocol r21553065Protocol {} class r21553065Class<T : AnyObject> {} // expected-note{{requirement specified as 'T' : 'AnyObject'}} _ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Class' requires that 'any r21553065Protocol' be a class type}} // Type variables not getting erased with nested closures struct Toe { let toenail: Nail // expected-error {{cannot find type 'Nail' in scope}} func clip() { toenail.inspect { x in toenail.inspect { y in } } } } // <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic class r21447318 { var x = 42 func doThing() -> r21447318 { return self } } func test21447318(_ a : r21447318, b : () -> r21447318) { a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}} b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}} } // <rdar://problem/20409366> Diagnostics for init calls should print the class name class r20409366C { init(a : Int) {} init?(a : r20409366C) { let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}} } } // <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match func r18800223(_ i : Int) { // 20099385 _ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}} // 19648528 _ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}} var buttonTextColor: String? _ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{result values in '? :' expression have mismatching types 'Int' and '(_) -> _'}} } // <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back _ = { $0 } // expected-error {{unable to infer type of a closure parameter '$0' in the current context}} _ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}} _ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}} // <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure. func rdar21784170() { let initial = (1.0 as Double, 2.0 as Double) (Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}} } // Diagnose passing an array in lieu of variadic parameters func variadic(_ x: Int...) {} func variadicArrays(_ x: [Int]...) {} func variadicAny(_ x: Any...) {} struct HasVariadicSubscript { subscript(_ x: Int...) -> Int { get { 0 } } } let foo = HasVariadicSubscript() let array = [1,2,3] let arrayWithOtherEltType = ["hello", "world"] variadic(array) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} variadic([1,2,3]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{10-11=}} {{16-17=}} variadic([1,2,3,]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{10-11=}} {{16-17=}} {{17-18=}} variadic(0, array, 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} variadic(0, [1,2,3], 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{13-14=}} {{19-20=}} variadic(0, [1,2,3,], 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{13-14=}} {{19-20=}} {{20-21=}} variadic(arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type 'Int'}} variadic(1, arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type 'Int'}} // FIXME: SR-11104 variadic(["hello", "world"]) // expected-error 2 {{cannot convert value of type 'String' to expected element type 'Int'}} // expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-2 {{remove brackets to pass array elements directly}} variadic([1] + [2] as [Int]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} foo[array] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} foo[[1,2,3]] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{5-6=}} {{11-12=}} foo[0, [1,2,3], 4] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{8-9=}} {{14-15=}} variadicAny(array) variadicAny([1,2,3]) variadicArrays(array) variadicArrays([1,2,3]) variadicArrays(arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type '[Int]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} variadicArrays(1,2,3) // expected-error 3 {{cannot convert value of type 'Int' to expected argument type '[Int]'}} protocol Proto {} func f<T: Proto>(x: [T]) {} func f(x: Int...) {} f(x: [1,2,3]) // TODO(diagnostics): Diagnose both the missing conformance and the disallowed array splat to cover both overloads. // expected-error@-2 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-3 {{remove brackets to pass array elements directly}} // <rdar://problem/21829141> BOGUS: unexpected trailing closure func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } } func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } } let expectType1 = expect(Optional(3))(Optional<Int>.self) let expectType1Check: Int = expectType1 // <rdar://problem/19804707> Swift Enum Scoping Oddity func rdar19804707() { enum Op { case BinaryOperator((Double, Double) -> Double) } var knownOps : Op knownOps = Op.BinaryOperator({$1 - $0}) knownOps = Op.BinaryOperator(){$1 - $0} knownOps = Op.BinaryOperator{$1 - $0} knownOps = .BinaryOperator({$1 - $0}) // rdar://19804707 - trailing closures for contextual member references. knownOps = .BinaryOperator(){$1 - $0} knownOps = .BinaryOperator{$1 - $0} _ = knownOps } // <rdar://problem/20491794> Error message does not tell me what the problem is enum Color { case Red case Unknown(description: String) static func rainbow() -> Color {} static func overload(a : Int) -> Color {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(a:)')}} // expected-note@-1 {{candidate expects value of type 'Int' for parameter #1 (got 'Double')}} static func overload(b : Int) -> Color {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(b:)')}} // expected-note@-1 {{candidate expects value of type 'Int' for parameter #1 (got 'Double')}} static func frob(_ a : Int, b : inout Int) -> Color {} static var svar: Color { return .Red } } let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error@-1 {{cannot convert value of type 'Array<(Int, _)>' to specified type '(Int, Color)'}} // expected-error@-2 {{cannot infer contextual base in reference to member 'Unknown'}} let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }} let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }} let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }} let _: Color = .Unknown // expected-error {{member 'Unknown(description:)' expects argument of type 'String'}} let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}} // expected-error@-1 {{cannot convert value of type 'Int' to expected argument type 'String'}} let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}} let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type '(Double, Float)' to specified type '(Int, Float)'}} let _ : Color = .rainbow // expected-error {{member 'rainbow()' is a function that produces expected type 'Color'; did you mean to call it?}} {{25-25=()}} let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .overload(1.0) // expected-error {{no exact matches in call to static method 'overload'}} let _: Color = .overload(1) // expected-error {{no exact matches in call to static method 'overload'}} let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}} // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}} // expected-error@-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{28-28=&}} let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}} // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'?}} someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'?}} someColor = .svar() // expected-error {{cannot call value of non-function type 'Color'}} someColor = .svar(1) // expected-error {{cannot call value of non-function type 'Color'}} func testTypeSugar(_ a : Int) { typealias Stride = Int let x = Stride(a) x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } // <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr func r21974772(_ y : Int) { let x = &(1.0 + y) // expected-error {{use of extraneous '&'}} } // <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc protocol r22020088P {} func r22020088Foo<T>(_ t: T) {} func r22020088bar(_ p: r22020088P?) { r22020088Foo(p.fdafs) // expected-error {{value of type '(any r22020088P)?' has no member 'fdafs'}} } // <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type func f(_ arguments: [String]) -> [ArraySlice<String>] { return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" }) } struct AOpts : OptionSet { let rawValue : Int } class B { func function(_ x : Int8, a : AOpts) {} func f2(_ a : AOpts) {} static func f1(_ a : AOpts) {} } class GenClass<T> {} struct GenStruct<T> {} enum GenEnum<T> {} func test(_ a : B) { B.f1(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}} a.function(42, a: nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}} a.function(42, nil) // expected-error {{missing argument label 'a:' in call}} // expected-error@-1 {{'nil' is not compatible with expected argument type 'AOpts'}} a.f2(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}} func foo1(_ arg: Bool) -> Int {return nil} func foo2<T>(_ arg: T) -> GenClass<T> {return nil} func foo3<T>(_ arg: T) -> GenStruct<T> {return nil} func foo4<T>(_ arg: T) -> GenEnum<T> {return nil} // expected-error@-4 {{'nil' is incompatible with return type 'Int'}} // expected-error@-4 {{'nil' is incompatible with return type 'GenClass<T>'}} // expected-error@-4 {{'nil' is incompatible with return type 'GenStruct<T>'}} // expected-error@-4 {{'nil' is incompatible with return type 'GenEnum<T>'}} let clsr1: () -> Int = {return nil} let clsr2: () -> GenClass<Bool> = {return nil} let clsr3: () -> GenStruct<String> = {return nil} let clsr4: () -> GenEnum<Double?> = {return nil} // expected-error@-4 {{'nil' is not compatible with closure result type 'Int'}} // expected-error@-4 {{'nil' is not compatible with closure result type 'GenClass<Bool>'}} // expected-error@-4 {{'nil' is not compatible with closure result type 'GenStruct<String>'}} // expected-error@-4 {{'nil' is not compatible with closure result type 'GenEnum<Double?>'}} var number = 0 var genClassBool = GenClass<Bool>() var funcFoo1 = foo1 number = nil genClassBool = nil funcFoo1 = nil // expected-error@-3 {{'nil' cannot be assigned to type 'Int'}} // expected-error@-3 {{'nil' cannot be assigned to type 'GenClass<Bool>'}} // expected-error@-3 {{'nil' cannot be assigned to type '(Bool) -> Int'}} } // <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure typealias MyClosure = ([Int]) -> Bool func r21684487() { var closures = Array<MyClosure>() let testClosure = {(list: [Int]) -> Bool in return true} let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions;}} } // <rdar://problem/18397777> QoI: special case comparisons with nil func r18397777(_ d : r21447318?) { let c = r21447318() if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to 'nil' always returns true}} } if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}} } if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{8-8= == nil)}} } if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{18-18= == nil)}} } } // <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list func r22255907_1<T>(_ a : T, b : Int) {} func r22255907_2<T>(_ x : Int, a : T, b: Int) {} func reachabilityForInternetConnection() { var variable: Int = 42 r22255907_1(&variable, b: 2) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}} r22255907_2(1, a: &variable, b: 2)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}} } // <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}} _ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}} // <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init func r22263468(_ a : String?) { typealias MyTuple = (Int, String) // TODO(diagnostics): This is a regression from diagnosing missing optional unwrap for `a`, we have to // re-think the way errors in tuple elements are detected because it's currently impossible to detect // exactly what went wrong here and aggregate fixes for different elements at the same time. _ = MyTuple(42, a) // expected-error {{tuple type '(_const Int, String?)' is not convertible to tuple type 'MyTuple' (aka '(Int, String)')}} } // rdar://71829040 - "ambiguous without more context" error for tuple type mismatch. func r71829040() { func object(forKey: String) -> Any? { nil } let flags: [String: String] // expected-error@+1 {{tuple type '(String, Bool)' is not convertible to tuple type '(String, String)'}} flags = Dictionary(uniqueKeysWithValues: ["keyA", "keyB"].map { ($0, object(forKey: $0) as? Bool ?? false) }) } // rdar://22470302 - Crash with parenthesized call result. class r22470302Class { func f() {} } func r22470302(_ c: r22470302Class) { print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}} } // <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile extension String { @available(*, unavailable, message: "calling this is unwise") func unavail<T : Sequence> // expected-note {{'unavail' has been explicitly marked unavailable here}} (_ a : T) -> String where T.Iterator.Element == String {} } extension Array { func g() -> String { return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}} } func h() -> String { return "foo".unavail([0]) // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}} } } // <rdar://problem/22519983> QoI: Weird error when failing to infer archetype func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {} // expected-note @-1 {{in call to function 'safeAssign'}} let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure struct Radar21692808<Element> { init(count: Int, value: Element) {} // expected-note {{'init(count:value:)' declared here}} } func radar21692808() -> Radar21692808<Int> { return Radar21692808<Int>(count: 1) { // expected-error {{trailing closure passed to parameter of type 'Int' that does not accept a closure}} return 1 } } // <rdar://problem/17557899> - This shouldn't suggest calling with (). func someOtherFunction() {} func someFunction() -> () { // Producing an error suggesting that this return someOtherFunction // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic func r23560128() { var a : (Int,Int)? a.0 = 42 // expected-error{{value of optional type '(Int, Int)?' must be unwrapped to refer to member '0' of wrapped base type '(Int, Int)'}} // expected-note@-1{{chain the optional }} } // <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping struct ExampleStruct21890157 { var property = "property" } var example21890157: ExampleStruct21890157? example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' must be unwrapped to refer to member 'property' of wrapped base type 'ExampleStruct21890157'}} // expected-note@-1{{chain the optional }} struct UnaryOp {} _ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}} // expected-note@-1 {{overloads for '-' exist with these partially matching parameter lists: (Double), (Float)}} // <rdar://problem/23433271> Swift compiler segfault in failure diagnosis func f23433271(_ x : UnsafePointer<Int>) {} func segfault23433271(_ a : UnsafeMutableRawPointer) { f23433271(a[0]) // expected-error {{value of type 'UnsafeMutableRawPointer' has no subscripts}} } // <rdar://problem/23272739> Poor diagnostic due to contextual constraint func r23272739(_ contentType: String) { let actualAcceptableContentTypes: Set<String> = [] return actualAcceptableContentTypes.contains(contentType) // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets func r23641896() { var g = "Hello World" g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<String.Index>'}} _ = g[12] // expected-error {{'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.}} } // <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note func test17875634() { var match: [(Int, Int)] = [] var row = 1 var col = 2 match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}} } // <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values enum AssocTest { case one(Int) } // FIXME(rdar://problem/65688291) - on iOS simulator this diagnostic is flaky, // either `referencing operator function '==' on 'Equatable'` or `operator function '==' requires` if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{requires that 'AssocTest' conform to 'Equatable'}} // expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}} // <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types func r24251022() { var a = 1 var b: UInt32 = 2 _ = a + b // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UInt32, UInt32)}} a += a + b // expected-error {{cannot convert value of type 'UInt32' to expected argument type 'Int'}} a += b // expected-error@:8 {{cannot convert value of type 'UInt32' to expected argument type 'Int'}} } func overloadSetResultType(_ a : Int, b : Int) -> Int { // https://twitter.com/_jlfischer/status/712337382175952896 // TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}} } postfix operator +++ postfix func +++ <T>(_: inout T) -> T { fatalError() } // <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) { let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}} _ = bytes[i+++] // expected-error {{cannot pass immutable value to mutating operator: 'i' is a 'let' constant}} } // SR-1594: Wrong error description when using === on non-class types class SR1594 { func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) { _ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}} _ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}} _ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}} _ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}} _ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}} _ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}} } } func nilComparison(i: Int, o: AnyObject) { _ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}} _ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}} _ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}} _ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}} // FIXME(integers): uncomment these tests once the < is no longer ambiguous // _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}} _ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}} _ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}} } // <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion func testImplConversion(a : Float?) -> Bool {} func testImplConversion(a : Int?) -> Bool { let someInt = 42 let a : Int = testImplConversion(someInt) // expected-error {{missing argument label 'a:' in call}} {{36-36=a: }} // expected-error@-1 {{cannot convert value of type 'Bool' to specified type 'Int'}} } // <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands class Foo23752537 { var title: String? var message: String? } extension Foo23752537 { func isEquivalent(other: Foo23752537) { // TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" // expected-error@+1 {{unexpected non-void return value in void function}} return (self.title != other.title && self.message != other.message) // expected-note {{did you mean to add a return type?}} } } // <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" func rdar27391581(_ a : Int, b : Int) -> Int { return a == b && b != 0 // expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}} } // <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {} func read<T : BinaryInteger>() -> T? { var buffer : T let n = withUnsafeMutablePointer(to: &buffer) { (p) in read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<T>' to expected argument type 'UnsafeMutableRawPointer'}} } } func f23213302() { var s = Set<Int>() s.subtract(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}} } // <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context func rdar24202058(a : Int) { return a <= 480 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // SR-1752: Warning about unused result with ternary operator struct SR1752 { func foo() {} } let sr1752: SR1752? true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void // Make sure RawRepresentable fix-its don't crash in the presence of type variables class NSCache<K, V> { func object(forKey: K) -> V? {} } class CacheValue { func value(x: Int) -> Int {} // expected-note {{found candidate with type '(Int) -> Int'}} func value(y: String) -> String {} // expected-note {{found candidate with type '(String) -> String'}} } func valueForKey<K>(_ key: K) -> CacheValue? { let cache = NSCache<K, CacheValue>() return cache.object(forKey: key)?.value // expected-error {{no exact matches in reference to instance method 'value'}} } // SR-1255 func foo1255_1() { return true || false // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } func foo1255_2() -> Int { return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}} } // Diagnostic message for initialization with binary operations as right side let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}} let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}} let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}} // SR-2208 struct Foo2208 { func bar(value: UInt) {} } func test2208() { let foo = Foo2208() let a: Int = 1 let b: Int = 2 let result = a / b foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} foo.bar(value: UInt(result)) // Ok } // SR-2164: Erroneous diagnostic when unable to infer generic type struct SR_2164<A, B> { // expected-note 4 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}} init(a: A) {} init(b: B) {} init(c: Int) {} init(_ d: A) {} init(e: A?) {} } struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}} init(_ a: [A]) {} } struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}} init(a: [A: Double]) {} } SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164(c: 2) // expected-error@-1 {{generic parameter 'A' could not be inferred}} // expected-error@-2 {{generic parameter 'B' could not be inferred}} // expected-note@-3 {{explicitly specify the generic arguments to fix this issue}} {{8-8=<Any, Any>}} SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}} SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}} let _ = SR_2164<Int, Bool>(a: 0) // Ok let _ = SR_2164<Int, Bool>(b: true) // Ok SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}} SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}} // <rdar://problem/29850459> Swift compiler misreports type error in ternary expression let r29850459_flag = true let r29850459_a: Int = 0 let r29850459_b: Int = 1 func r29850459() -> Bool { return false } let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} // SR-6272: Tailored diagnostics with fixits for numerical conversions func SR_6272_a() { enum Foo: Int { case bar } // expected-error@+1 {{cannot convert value of type 'Float' to expected argument type 'Int'}} {{35-35=Int(}} {{43-43=)}} let _: Int = Foo.bar.rawValue * Float(0) // expected-error@+1 {{cannot convert value of type 'Int' to expected argument type 'Float'}} {{18-18=Float(}} {{34-34=)}} let _: Float = Foo.bar.rawValue * Float(0) // expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{none}} // expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}} Foo.bar.rawValue * Float(0) } func SR_6272_b() { let lhs = Float(3) let rhs = Int(0) // expected-error@+1 {{cannot convert value of type 'Int' to expected argument type 'Float'}} {{24-24=Float(}} {{27-27=)}} let _: Float = lhs * rhs // expected-error@+1 {{cannot convert value of type 'Float' to expected argument type 'Int'}} {{16-16=Int(}} {{19-19=)}} let _: Int = lhs * rhs // expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{none}} // expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}} lhs * rhs } func SR_6272_c() { // expected-error@+1 {{cannot convert value of type 'String' to expected argument type 'Int'}} {{none}} Int(3) * "0" struct S {} // expected-error@+1 {{cannot convert value of type 'S' to expected argument type 'Int'}} {{none}} Int(10) * S() } struct SR_6272_D: ExpressibleByIntegerLiteral { typealias IntegerLiteralType = Int init(integerLiteral: Int) {} static func +(lhs: SR_6272_D, rhs: Int) -> Float { return 42.0 } } func SR_6272_d() { let x: Float = 1.0 // expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}} // expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}} let _: Float = SR_6272_D(integerLiteral: 42) + x // expected-error@+1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} {{50-50=Int(}} {{54-54=)}} let _: Float = SR_6272_D(integerLiteral: 42) + 42.0 // expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}} // expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}} let _: Float = SR_6272_D(integerLiteral: 42) + x + 1.0 } // Ambiguous overload inside a trailing closure func ambiguousCall() -> Int {} // expected-note {{found this candidate}} func ambiguousCall() -> Float {} // expected-note {{found this candidate}} func takesClosure(fn: () -> ()) {} takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}} // SR-4692: Useless diagnostics calling non-static method class SR_4692_a { private static func foo(x: Int, y: Bool) { self.bar(x: x) // expected-error@-1 {{instance member 'bar' cannot be used on type 'SR_4692_a'}} } private func bar(x: Int) { } } class SR_4692_b { static func a() { self.f(x: 3, y: true) // expected-error@-1 {{instance member 'f' cannot be used on type 'SR_4692_b'}} } private func f(a: Int, b: Bool, c: String) { self.f(x: a, y: b) } private func f(x: Int, y: Bool) { } } // rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful struct R32101765 { let prop32101765 = 0 } let _: KeyPath<R32101765, Float> = \.prop32101765 // expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}} let _: KeyPath<R32101765, Float> = \R32101765.prop32101765 // expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}} let _: KeyPath<R32101765, Float> = \.prop32101765.unknown // expected-error@-1 {{type 'Int' has no member 'unknown'}} let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown // expected-error@-1 {{type 'Int' has no member 'unknown'}} // rdar://problem/32390726 - Bad Diagnostic: Don't suggest `var` to `let` when binding inside for-statement for var i in 0..<10 { // expected-warning {{variable 'i' was never mutated; consider removing 'var' to make it constant}} {{5-9=}} _ = i + 1 } // SR-5045 - Attempting to return result of reduce(_:_:) in a method with no return produces ambiguous error func sr5045() { let doubles: [Double] = [1, 2, 3] return doubles.reduce(0, +) // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // rdar://problem/32934129 - QoI: misleading diagnostic class L_32934129<T : Comparable> { init(_ value: T) { self.value = value } init(_ value: T, _ next: L_32934129<T>?) { self.value = value self.next = next } var value: T var next: L_32934129<T>? = nil func length() -> Int { func inner(_ list: L_32934129<T>?, _ count: Int) { guard let list = list else { return count } // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} return inner(list.next, count + 1) } return inner(self, 0) // expected-error {{cannot convert return expression of type '()' to return type 'Int'}} } } // rdar://problem/31671195 - QoI: erroneous diagnostic - cannot call value of non-function type class C_31671195 { var name: Int { fatalError() } func name(_: Int) { fatalError() } } C_31671195().name(UInt(0)) // expected-error@-1 {{cannot convert value of type 'UInt' to expected argument type 'Int'}} // rdar://problem/28456467 - QoI: erroneous diagnostic - cannot call value of non-function type class AST_28456467 { var hasStateDef: Bool { return false } } protocol Expr_28456467 {} class ListExpr_28456467 : AST_28456467, Expr_28456467 { let elems: [Expr_28456467] init(_ elems:[Expr_28456467] ) { self.elems = elems } override var hasStateDef: Bool { return elems.first(where: { $0.hasStateDef }) != nil // expected-error@-1 {{value of type 'any Expr_28456467' has no member 'hasStateDef'}} } } func sr5081() { var a = ["1", "2", "3", "4", "5"] var b = [String]() b = a[2...4] // expected-error {{cannot assign value of type 'ArraySlice<String>' to type '[String]'}} } // TODO(diagnostics):Figure out what to do when expressions are complex and completely broken func rdar17170728() { var i: Int? = 1 var j: Int? var k: Int? = 2 let _ = [i, j, k].reduce(0 as Int?) { $0 && $1 ? $0! + $1! : ($0 ? $0! : ($1 ? $1! : nil)) // expected-error@-1 4 {{optional type 'Int?' cannot be used as a boolean; test for '!= nil' instead}} } let _ = [i, j, k].reduce(0 as Int?) { // expected-error {{missing argument label 'into:' in call}} // expected-error@-1 {{cannot convert value of type 'Int?' to expected argument type '(inout @escaping (Bool, Bool) -> Bool?, Int?) throws -> ()'}} $0 && $1 ? $0 + $1 : ($0 ? $0 : ($1 ? $1 : nil)) // expected-error@-1 {{binary operator '+' cannot be applied to two 'Bool' operands}} } } // https://bugs.swift.org/browse/SR-5934 - failure to emit diagnostic for bad // generic constraints func elephant<T, U>(_: T) where T : Collection, T.Element == U, T.Element : Hashable {} // expected-note {{where 'U' = 'T'}} func platypus<T>(a: [T]) { _ = elephant(a) // expected-error {{global function 'elephant' requires that 'T' conform to 'Hashable'}} } // Another case of the above. func badTypes() { let sequence:AnySequence<[Int]> = AnySequence() { AnyIterator() { [3] }} // Notes, attached to declarations, explain that there is a difference between Array.init(_:) and // RangeReplaceableCollection.init(_:) which are both applicable in this case. let array = [Int](sequence) // expected-error@-1 {{no exact matches in call to initializer}} } // rdar://34357545 func unresolvedTypeExistential() -> Bool { return (Int.self==_{}) // expected-error@-1 {{type of expression is ambiguous without more context}} // expected-error@-2 {{type placeholder not allowed here}} } do { struct Array {} let foo: Swift.Array = Array() // expected-error {{cannot convert value of type 'Array' to specified type 'Array<Element>'}} // expected-error@-1 {{generic parameter 'Element' could not be inferred}} struct Error {} let bar: Swift.Error = Error() //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz: (Swift.Error) = Error() //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz2: Swift.Error = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz3: (Swift.Error) = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz4: ((Swift.Error)) = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} } // SyntaxSugarTypes with unresolved types func takesGenericArray<T>(_ x: [T]) {} takesGenericArray(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}} func takesNestedGenericArray<T>(_ x: [[T]]) {} takesNestedGenericArray(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[[Int]]'}} func takesSetOfGenericArrays<T>(_ x: Set<[T]>) {} takesSetOfGenericArrays(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<[Int]>'}} func takesArrayOfSetOfGenericArrays<T>(_ x: [Set<[T]>]) {} takesArrayOfSetOfGenericArrays(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Set<[Int]>]'}} func takesArrayOfGenericOptionals<T>(_ x: [T?]) {} takesArrayOfGenericOptionals(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int?]'}} func takesGenericDictionary<T, U>(_ x: [T : U]) {} // expected-note {{in call to function 'takesGenericDictionary'}} takesGenericDictionary(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '[T : U]'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} // expected-error@-2 {{generic parameter 'U' could not be inferred}} typealias Z = Int func takesGenericDictionaryWithTypealias<T>(_ x: [T : Z]) {} // expected-note {{in call to function 'takesGenericDictionaryWithTypealias'}} takesGenericDictionaryWithTypealias(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '[T : Z]'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} func takesGenericFunction<T>(_ x: ([T]) -> Void) {} // expected-note {{in call to function 'takesGenericFunction'}} takesGenericFunction(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '([T]) -> Void'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} func takesTuple<T>(_ x: ([T], [T])) {} // expected-note {{in call to function 'takesTuple'}} takesTuple(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '([T], [T])'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} // Void function returns non-void result fix-it func voidFunc() { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{16-16= -> <#Return Type#>}} } func voidFuncWithArgs(arg1: Int) { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{33-33= -> <#Return Type#>}} } func voidFuncWithCondFlow() { if Bool.random() { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{28-28= -> <#Return Type#>}} } else { return 2 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{28-28= -> <#Return Type#>}} } } func voidFuncWithNestedVoidFunc() { func nestedVoidFunc() { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{24-24= -> <#Return Type#>}} } } func voidFuncWithEffects1() throws { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{35-35= -> <#Return Type#>}} } @available(SwiftStdlib 5.5, *) func voidFuncWithEffects2() async throws { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{41-41= -> <#Return Type#>}} } @available(SwiftStdlib 5.5, *) // expected-error@+1 {{'async' must precede 'throws'}} func voidFuncWithEffects3() throws async { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{41-41= -> <#Return Type#>}} } @available(SwiftStdlib 5.5, *) func voidFuncWithEffects4() async { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{34-34= -> <#Return Type#>}} } func voidFuncWithEffects5(_ closure: () throws -> Void) rethrows { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{65-65= -> <#Return Type#>}} } @available(SwiftStdlib 5.5, *) func voidGenericFuncWithEffects<T>(arg: T) async where T: CustomStringConvertible { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{49-49= -> <#Return Type#>}} } // Special cases: These should not offer a note + fix-it func voidFuncExplicitType() -> Void { return 1 // expected-error {{unexpected non-void return value in void function}} } class ClassWithDeinit { deinit { return 0 // expected-error {{unexpected non-void return value in void function}} } } class ClassWithVoidProp { var propertyWithVoidType: () { return 5 } // expected-error {{unexpected non-void return value in void function}} } class ClassWithPropContainingSetter { var propWithSetter: Int { get { return 0 } set { return 1 } // expected-error {{unexpected non-void return value in void function}} } } // https://bugs.swift.org/browse/SR-11964 struct Rect { let width: Int let height: Int } struct Frame { func rect(width: Int, height: Int) -> Rect { Rect(width: width, height: height) } let rect: Rect } func foo(frame: Frame) { frame.rect.width + 10.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} } // Make sure we prefer the conformance failure. func f11(_ n: Int) {} func f11<T : P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{where 'T' = 'Int'}} f11(3, f4) // expected-error {{global function 'f11' requires that 'Int' conform to 'P2'}} let f12: (Int) -> Void = { _ in } // expected-note {{candidate '(Int) -> Void' requires 1 argument, but 2 were provided}} func f12<T : P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{candidate requires that 'Int' conform to 'P2' (requirement specified as 'T' : 'P2')}} f12(3, f4)// expected-error {{no exact matches in call to global function 'f12'}} // SR-12242 struct SR_12242_R<Value> {} struct SR_12242_T {} protocol SR_12242_P {} func fSR_12242() -> SR_12242_R<[SR_12242_T]> {} func genericFunc<SR_12242_T: SR_12242_P>(_ completion: @escaping (SR_12242_R<[SR_12242_T]>) -> Void) { let t = fSR_12242() completion(t) // expected-error {{cannot convert value of type 'diagnostics.SR_12242_R<[diagnostics.SR_12242_T]>' to expected argument type 'diagnostics.SR_12242_R<[SR_12242_T]>'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('diagnostics.SR_12242_T' and 'SR_12242_T') are expected to be equal}} } func assignGenericMismatch() { var a: [Int]? var b: [String] a = b // expected-error {{cannot assign value of type '[String]' to type '[Int]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} b = a // expected-error {{cannot assign value of type '[Int]' to type '[String]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}} // expected-error@-2 {{value of optional type '[Int]?' must be unwrapped to a value of type '[Int]'}} // expected-note@-3 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-4 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } // [Int] to [String]? argument to param conversion let value: [Int] = [] func gericArgToParamOptional(_ param: [String]?) {} gericArgToParamOptional(value) // expected-error {{convert value of type '[Int]' to expected argument type '[String]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}} // Inout Expr conversions func gericArgToParamInout1(_ x: inout [[Int]]) {} func gericArgToParamInout2(_ x: inout [[String]]) { gericArgToParamInout1(&x) // expected-error {{cannot convert value of type '[[String]]' to expected argument type '[[Int]]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} } func gericArgToParamInoutOptional(_ x: inout [[String]]?) { gericArgToParamInout1(&x) // expected-error {{cannot convert value of type '[[String]]?' to expected argument type '[[Int]]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} // expected-error@-2 {{value of optional type '[[String]]?' must be unwrapped to a value of type '[[String]]'}} // expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } func gericArgToParamInout(_ x: inout [[Int]]) { // expected-note {{change variable type to '[[String]]?' if it doesn't need to be declared as '[[Int]]'}} gericArgToParamInoutOptional(&x) // expected-error {{cannot convert value of type '[[Int]]' to expected argument type '[[String]]?'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}} // expected-error@-2 {{inout argument could be set to a value with a type other than '[[Int]]'; use a value declared as type '[[String]]?' instead}} } // SR-12725 struct SR12725<E> {} // expected-note {{arguments to generic parameter 'E' ('Int' and 'Double') are expected to be equal}} func generic<T>(_ value: inout T, _ closure: (SR12725<T>) -> Void) {} let arg: Int generic(&arg) { (g: SR12725<Double>) -> Void in } // expected-error {{cannot convert value of type '(SR12725<Double>) -> Void' to expected argument type '(SR12725<Int>) -> Void'}} // rdar://problem/62428353 - bad error message for passing `T` where `inout T` was expected func rdar62428353<T>(_ t: inout T) { let v = t // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} rdar62428353(v) // expected-error {{cannot pass immutable value as inout argument: 'v' is a 'let' constant}} } func rdar62989214() { struct Flag { var isTrue: Bool } @propertyWrapper @dynamicMemberLookup struct Wrapper<Value> { var wrappedValue: Value subscript<Subject>( dynamicMember keyPath: WritableKeyPath<Value, Subject> ) -> Wrapper<Subject> { get { fatalError() } } } func test(arr: Wrapper<[Flag]>, flag: Flag) { arr[flag].isTrue // expected-error {{cannot convert value of type 'Flag' to expected argument type 'Int'}} } } // SR-5688 func SR5688_1() -> String? { "" } SR5688_1!.count // expected-error {{function 'SR5688_1' was used as a property; add () to call it}} {{9-9=()}} func SR5688_2() -> Int? { 0 } let _: Int = SR5688_2! // expected-error {{function 'SR5688_2' was used as a property; add () to call it}} {{22-22=()}} // rdar://74696023 - Fallback error when passing incorrect optional type to `==` operator func rdar74696023() { struct MyError { var code: Int = 0 } func test(error: MyError?, code: Int32) { guard error?.code == code else { fatalError() } // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } } extension Int { static var optionalIntMember: Int? { 0 } static var optionalThrowsMember: Int? { get throws { 0 } } } func testUnwrapFixIts(x: Int?) throws { let _ = x + 2 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{11-11=(}} {{12-12= ?? <#default value#>)}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{12-12=!}} let _ = (x ?? 0) + 2 let _ = 2 + x // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{15-15=(}} {{16-16= ?? <#default value#>)}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{16-16=!}} let _ = 2 + (x ?? 0) func foo(y: Int) {} foo(y: x) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{11-11= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{11-11=!}} foo(y: x ?? 0) let _ = x < 2 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{12-12= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{12-12=!}} let _ = x ?? 0 < 2 let _ = 2 < x // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{16-16= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{16-16=!}} let _ = 2 < x ?? 0 let _: Int = (.optionalIntMember) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{35-35= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{35-35=!}} let _: Int = (.optionalIntMember ?? 0) let _ = 1 + .optionalIntMember // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{15-15=(}} {{33-33= ?? <#default value#>)}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{33-33=!}} let _ = 1 + (.optionalIntMember ?? 0) let _ = try .optionalThrowsMember + 1 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{15-15=(}} {{36-36= ?? <#default value#>)}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{36-36=!}} let _ = try (.optionalThrowsMember ?? 0) + 1 let _ = .optionalIntMember?.bitWidth > 0 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{39-39= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{11-11=(}} {{39-39=)!}} let _ = (.optionalIntMember?.bitWidth)! > 0 let _ = .optionalIntMember?.bitWidth ?? 0 > 0 let _ = .random() ? .optionalIntMember : 0 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{41-41= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{41-41=!}} let _ = .random() ? .optionalIntMember ?? 0 : 0 let _: Int = try try try .optionalThrowsMember // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{49-49= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{49-49=!}} let _: Int = try try try .optionalThrowsMember ?? 0 let _: Int = try! .optionalThrowsMember // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{42-42= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{42-42=!}} let _: Int = try! .optionalThrowsMember ?? 0 } func rdar86611718(list: [Int]) { String(list.count()) // expected-error@-1 {{cannot call value of non-function type 'Int'}} }
apache-2.0
ceac9f83147ca45dd24df51ae4ec40f5
46.662869
228
0.670088
3.645138
false
false
false
false
Zewo/Zewo
Sources/Core/String/String.swift
1
3047
import Foundation extension Character { public var isASCII: Bool { return unicodeScalars.reduce(true, { $0 && $1.isASCII }) } public var isAlphabetic: Bool { return isLowercase || isUppercase } public var isDigit: Bool { return ("0" ... "9").contains(self) } } extension String { public func uppercasedFirstCharacter() -> String { let first = prefix(1).capitalized let other = dropFirst() return first + other } } extension CharacterSet { public static var urlAllowed: CharacterSet { let uppercaseAlpha = CharacterSet(charactersIn: "A" ... "Z") let lowercaseAlpha = CharacterSet(charactersIn: "a" ... "z") let numeric = CharacterSet(charactersIn: "0" ... "9") let symbols: CharacterSet = ["_", "-", "~", "."] return uppercaseAlpha .union(lowercaseAlpha) .union(numeric) .union(symbols) } } extension String { public func trimmed() -> String { let regex = try! NSRegularExpression(pattern: " +", options: .caseInsensitive) return regex.stringByReplacingMatches( in: self, options: [], range: NSRange(location: 0, length: utf8.count), withTemplate: " " ).trimmingCharacters(in: .whitespaces) } public func camelCaseSplit() -> [String] { var entries: [String] = [] var runes: [[Character]] = [] var lastClass = 0 var currentClass = 0 for character in self { switch true { case character.isLowercase: currentClass = 1 case character.isUppercase: currentClass = 2 case character.isDigit: currentClass = 3 default: currentClass = 4 } if currentClass == lastClass { var rune = runes[runes.count - 1] rune.append(character) runes[runes.count - 1] = rune } else { runes.append([character]) } lastClass = currentClass } // handle upper case -> lower case sequences, e.g. // "PDFL", "oader" -> "PDF", "Loader" if runes.count >= 2 { for i in 0 ..< runes.count - 1 { if runes[i][0].isUppercase && runes[i + 1][0].isLowercase { runes[i + 1] = [runes[i][runes[i].count - 1]] + runes[i + 1] runes[i] = Array(runes[i][..<(runes[i].count - 1)]) } } } for rune in runes where rune.count > 0 { entries.append(String(rune)) } return entries } } extension UUID : LosslessStringConvertible { public init?(_ string: String) { guard let uuid = UUID(uuidString: string) else { return nil } self = uuid } }
mit
90422112e9213dbe30b0395d46a3085f
27.212963
87
0.501477
4.575075
false
false
false
false
justinlevi/asymptotik-rnd-scenekit-kaleidoscope
Atk_Rnd_VisualToys/KaleidoscopeViewController.swift
1
25047
// // KaleidoscopeViewController.swift // Atk_Rnd_VisualToys // // Created by Rick Boykin on 8/4/14. // Copyright (c) 2014 Asymptotik Limited. All rights reserved. // import Foundation import UIKit import QuartzCore import SceneKit import Darwin import GLKit import OpenGLES import AVFoundation import CoreVideo import CoreMedia enum MirrorTextureSoure { case Image, Color, Video } enum RecordingStatus { case Stopped, Finishing, FinishRequested, Recording } class KaleidoscopeViewController: UIViewController, SCNSceneRendererDelegate, SCNProgramDelegate, UIGestureRecognizerDelegate { @IBOutlet weak var settingsOffsetConstraint: NSLayoutConstraint! @IBOutlet weak var settingsWidthConstraint: NSLayoutConstraint! @IBOutlet weak var settingsButton: UIButton! @IBOutlet weak var settingsContainerView: UIView! @IBOutlet weak var videoButton: UIButton! @IBOutlet weak var imageRecording: UIImageView! var textureSource = MirrorTextureSoure.Video var hasMirror = false var videoCapture = VideoCaptureBuffer() var videoRecorder:FrameBufferVideoRecorder? var videoRecordingTmpUrl: NSURL!; var recordingStatus = RecordingStatus.Stopped; var defaultFBO:GLint = 0 var snapshotRequested = false; private weak var settingsViewController:KaleidoscopeSettingsViewController? = nil var textureRotation:GLfloat = 0.0 var textureRotationSpeed:GLfloat = 0.1 var rotateTexture = false var screenTexture:ScreenTextureQuad? override func viewDidLoad() { super.viewDidLoad() // create a new scene let scene = SCNScene() // retrieve the SCNView let scnView = self.view as! SCNView // set the scene to the view scnView.scene = scene // allows the user to manipulate the camera scnView.allowsCameraControl = true // show statistics such as fps and timing information scnView.showsStatistics = false // configure the view scnView.backgroundColor = UIColor.blackColor() // Anti alias scnView.antialiasingMode = SCNAntialiasingMode.Multisampling4X // delegate to self scnView.delegate = self scene.rootNode.runAction(SCNAction.customActionWithDuration(5, actionBlock:{ (triNode:SCNNode, elapsedTime:CGFloat) -> Void in })) // create and add a camera to the scene let cameraNode = SCNNode() let camera = SCNCamera() //camera.usesOrthographicProjection = true cameraNode.camera = camera scene.rootNode.addChildNode(cameraNode) scnView.pointOfView = cameraNode; // place the camera cameraNode.position = SCNVector3(x: 0, y: 0, z: 15) cameraNode.pivot = SCNMatrix4MakeTranslation(0, 0, 0) // add a tap gesture recognizer //let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:") //let pinchGesture = UIPinchGestureRecognizer(target: self, action: "handlePinch:") //let panGesture = UIPanGestureRecognizer(target: self, action: "handlePan:") //var gestureRecognizers:[AnyObject] = [tapGesture, pinchGesture, panGesture] //if let recognizers = scnView.gestureRecognizers { // gestureRecognizers += recognizers //} //scnView.gestureRecognizers = gestureRecognizers for controller in self.childViewControllers { if controller.isKindOfClass(KaleidoscopeSettingsViewController) { let settingsViewController = controller as! KaleidoscopeSettingsViewController settingsViewController.kaleidoscopeViewController = self self.settingsViewController = settingsViewController } } self.videoRecordingTmpUrl = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("video.mov") self.screenTexture = ScreenTextureQuad() self.screenTexture!.initialize() OpenGlUtils.checkError("init") } override func viewWillLayoutSubviews() { let viewFrame = self.view.frame if(self.settingsViewController?.view.frame.width > viewFrame.width) { var frame = self.settingsViewController!.view.frame frame.size.width = viewFrame.width self.settingsOffsetConstraint.constant = -frame.size.width self.settingsWidthConstraint.constant = frame.size.width } } func createSphereNode(color:UIColor) -> SCNNode { let sphere = SCNSphere() let material = SCNMaterial() material.diffuse.contents = color sphere.materials = [material]; let sphereNode = SCNNode() sphereNode.geometry = sphere sphereNode.scale = SCNVector3Make(0.25, 0.25, 0.25) return sphereNode } func createCorners() { let scnView = self.view as! SCNView let extents = scnView.getExtents() let minEx = extents.min let maxEx = extents.max let scene = scnView.scene! let sphereCenterNode = createSphereNode(UIColor.redColor()) sphereCenterNode.position = SCNVector3Make(0.0, 0.0, 0.0) scene.rootNode.addChildNode(sphereCenterNode) let sphereLLNode = createSphereNode(UIColor.blueColor()) sphereLLNode.position = SCNVector3Make(minEx.x, minEx.y, 0.0) scene.rootNode.addChildNode(sphereLLNode) let sphereURNode = createSphereNode(UIColor.greenColor()) sphereURNode.position = SCNVector3Make(maxEx.x, maxEx.y, 0.0) scene.rootNode.addChildNode(sphereURNode) } private var _videoActionRate = FrequencyCounter(); func createMirror() -> Bool { var ret:Bool = false if !hasMirror { //createCorners() let scnView:SCNView = self.view as! SCNView let scene = scnView.scene! let triNode = SCNNode() //let geometry = Geometry.createKaleidoscopeMirrorWithEquilateralTriangles(scnView) let geometry = Geometry.createKaleidoscopeMirrorWithIsoscelesTriangles(scnView) //var geometry = Geometry.createSquare(scnView) triNode.geometry = geometry triNode.position = SCNVector3(x: 0, y: 0, z: 0) if(self.textureSource == .Video) { geometry.materials = [self.createVideoTextureMaterial()] } else if(self.textureSource == .Color) { let material = SCNMaterial() material.diffuse.contents = UIColor.randomColor() geometry.materials = [material] } else if(self.textureSource == .Image) { let me = UIImage(named: "me2") let material = SCNMaterial() material.diffuse.contents = me geometry.materials = [material] } //triNode.scale = SCNVector3(x: 0.5, y: 0.5, z: 0.5) triNode.name = "mirrors" let videoAction = SCNAction.customActionWithDuration(10000000000, actionBlock:{ (triNode:SCNNode, elapsedTime:CGFloat) -> Void in //NSLog("Running action: processNextVideoTexture") if self._videoActionRate.count == 0 { self._videoActionRate.start() } self._videoActionRate.increment() if self._videoActionRate.count % 30 == 0 { //NSLog("Video Action Rate: \(self._videoActionRate.frequency)/sec") } self.videoCapture.processNextVideoTexture() }) /* var swellAction = SCNAction.repeatActionForever(SCNAction.sequence( [ SCNAction.scaleTo(1.01, duration: 1), SCNAction.scaleTo(1.0, duration: 1), ])) */ let actions = SCNAction.group([videoAction]) triNode.runAction(actions) scene.rootNode.addChildNode(triNode) hasMirror = true ret = true } return ret; } func createVideoTextureMaterial() -> SCNMaterial { let material = SCNMaterial() let program = SCNProgram() let vertexShaderURL = NSBundle.mainBundle().URLForResource("Shader", withExtension: "vsh") let fragmentShaderURL = NSBundle.mainBundle().URLForResource("Shader", withExtension: "fsh") var vertexShaderSource: NSString? do { vertexShaderSource = try NSString(contentsOfURL: vertexShaderURL!, encoding: NSUTF8StringEncoding) } catch _ { vertexShaderSource = nil } var fragmentShaderSource: NSString? do { fragmentShaderSource = try NSString(contentsOfURL: fragmentShaderURL!, encoding: NSUTF8StringEncoding) } catch _ { fragmentShaderSource = nil } program.vertexShader = vertexShaderSource as? String program.fragmentShader = fragmentShaderSource as? String // Bind the position of the geometry and the model view projection // you would do the same for other geometry properties like normals // and other geometry properties/transforms. // // The attributes and uniforms in the shaders are defined as: // attribute vec4 position; // attribute vec2 textureCoordinate; // uniform mat4 modelViewProjection; program.setSemantic(SCNGeometrySourceSemanticVertex, forSymbol: "position", options: nil) program.setSemantic(SCNGeometrySourceSemanticTexcoord, forSymbol: "textureCoordinate", options: nil) program.setSemantic(SCNModelViewProjectionTransform, forSymbol: "modelViewProjection", options: nil) program.delegate = self material.program = program material.doubleSided = true material.handleBindingOfSymbol("SamplerY", usingBlock: { (programId:UInt32, location:UInt32, node:SCNNode!, renderer:SCNRenderer!) -> Void in glUniform1i(GLint(location), 0) } ) material.handleBindingOfSymbol("SamplerUV", usingBlock: { (programId:UInt32, location:UInt32, node:SCNNode!, renderer:SCNRenderer!) -> Void in glUniform1i(GLint(location), 1) } ) material.handleBindingOfSymbol("TexRotation", usingBlock: { (programId:UInt32, location:UInt32, node:SCNNode!, renderer:SCNRenderer!) -> Void in glUniform1f(GLint(location), self.textureRotation) } ) return material } // SCNProgramDelegate func program(program: SCNProgram, handleError error: NSError) { NSLog("%@", error) } func renderer(aRenderer: SCNSceneRenderer, willRenderScene scene: SCNScene, atTime time: NSTimeInterval) { if _renderCount >= 1 && self.recordingStatus == RecordingStatus.Recording { if self.videoRecorder != nil{ self.videoRecorder!.bindRenderTextureFramebuffer() } } //self.videoRecorder!.bindRenderTextureFramebuffer() } // SCNSceneRendererDelegate private var _renderCount = 0 func renderer(aRenderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: NSTimeInterval) { if _renderCount == 1 { self.createMirror() if(self.textureSource == .Video) { if let scnView:SCNView = self.view as? SCNView where scnView.eaglContext != nil { self.videoCapture.initVideoCapture(scnView.eaglContext!) } } glGetIntegerv(GLenum(GL_FRAMEBUFFER_BINDING), &self.defaultFBO) NSLog("Default framebuffer: %d", self.defaultFBO) } if _renderCount >= 1 { if self.snapshotRequested { self.takeShot() self.snapshotRequested = false } if self.recordingStatus == RecordingStatus.Recording { // var scnView = self.view as! SCNView glFlush() glFinish() if self.videoRecorder != nil{ self.videoRecorder!.grabFrameFromRenderTexture(time) // Works here glBindFramebuffer(GLenum(GL_FRAMEBUFFER), GLuint(self.defaultFBO)) self.screenTexture!.draw(self.videoRecorder!.target, name: self.videoRecorder!.name) } } else if self.recordingStatus == RecordingStatus.FinishRequested { self.recordingStatus = RecordingStatus.Finishing Async.background({ () -> Void in self.finishRecording() }) } //glFinish() //glBindFramebuffer(GLenum(GL_FRAMEBUFFER), GLuint(self.defaultFBO)) //self.screenTexture!.draw(self.videoRecorder!.target, name: self.videoRecorder!.name) } _renderCount++; /* let scnView:SCNView = self.view as SCNView var camera = scnView.pointOfView!.camera slideVelocity = Rotation.rotateCamera(scnView.pointOfView!, velocity: slideVelocity) */ } private var _lastRenderTime: NSTimeInterval = 0.0 func renderer(aRenderer: SCNSceneRenderer, updateAtTime time: NSTimeInterval) { if(_lastRenderTime > 0.0) { if self.rotateTexture { self.textureRotation += self.textureRotationSpeed * Float(time - _lastRenderTime) } else { self.textureRotation = 0.0 } } _lastRenderTime = time; } func handleTap(recognizer: UIGestureRecognizer) { // retrieve the SCNView let scnView:SCNView = self.view as! SCNView // check what nodes are tapped let viewPoint = recognizer.locationInView(scnView) for var node:SCNNode? = scnView.pointOfView; node != nil; node = node?.parentNode { NSLog("Node: " + node!.description) NSLog("Node pivot: " + node!.pivot.description) NSLog("Node constraints: \(node!.constraints?.description)") } let projectedOrigin = scnView.projectPoint(SCNVector3Zero) let vpWithZ = SCNVector3Make(Float(viewPoint.x), Float(viewPoint.y), projectedOrigin.z) let scenePoint = scnView.unprojectPoint(vpWithZ) print("tapPoint: (\(viewPoint.x), \(viewPoint.y)) scenePoint: (\(scenePoint.x), \(scenePoint.y), \(scenePoint.z))") } private var currentScale:Float = 1.0 private var lastScale:CGFloat = 1.0 func handlePinch(recognizer: UIPinchGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { lastScale = recognizer.scale } else if recognizer.state == UIGestureRecognizerState.Changed { let scnView:SCNView = self.view as! SCNView let cameraNode = scnView.pointOfView! let position = cameraNode.position var scale:Float = 1.0 - Float(recognizer.scale - lastScale) scale = min(scale, 40.0 / currentScale) scale = max(scale, 0.1 / currentScale) currentScale = scale lastScale = recognizer.scale let z = max(0.02, position.z * scale) cameraNode.position.z = z } } var slideVelocity = CGPointMake(0.0, 0.0) var cameraRot = CGPointMake(0.0, 0.0) var panPoint = CGPointMake(0.0, 0.0) func handlePan(recognizer: UIPanGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { panPoint = recognizer.locationInView(self.view) } else if recognizer.state == UIGestureRecognizerState.Changed { let pt = recognizer.locationInView(self.view) cameraRot.x += (pt.x - panPoint.x) * CGFloat(M_PI / 180.0) cameraRot.y += (pt.y - panPoint.y) * CGFloat(M_PI / 180.0) panPoint = pt } let x = Float(15 * sin(cameraRot.x)) let z = Float(15 * cos(cameraRot.x)) slideVelocity = recognizer.velocityInView(self.view) let scnView:SCNView = self.view as! SCNView let cameraNode = scnView.pointOfView! cameraNode.position = SCNVector3Make(x, 0, z) var vect = SCNVector3Make(0, 0, 0) - cameraNode.position vect.normalize() let at1 = atan2(vect.x, vect.z) let at2 = Float(atan2(0.0, -1.0)) let angle = at1 - at2 NSLog("Angle: %f", angle) cameraNode.rotation = SCNVector4Make(0, 1, 0, angle) } // // Settings // func startBreathing(depth:CGFloat, duration:NSTimeInterval) { self.stopBreathing() let scnView:SCNView = self.view as! SCNView let mirrorNode = scnView.scene?.rootNode.childNodeWithName("mirrors", recursively: false) if let mirrorNode = mirrorNode { let breatheAction = SCNAction.repeatActionForever(SCNAction.sequence( [ SCNAction.scaleTo(depth, duration: duration/2.0), SCNAction.scaleTo(1.0, duration: duration/2.0), ])) mirrorNode.runAction(breatheAction, forKey: "breatheAction") } } func stopBreathing() { let scnView = self.view as! SCNView let mirrorNode = scnView.scene?.rootNode.childNodeWithName("mirrors", recursively: false) if let mirrorNode = mirrorNode { mirrorNode.removeActionForKey("breatheAction") } } var isUsingFrontFacingCamera:Bool { get { return self.videoCapture.isUsingFrontFacingCamera } set { if newValue != self.videoCapture.isUsingFrontFacingCamera { self.videoCapture.switchCameras() } } } var maxZoom:CGFloat { get { return self.videoCapture.maxZoom } } var zoom:CGFloat { get { return self.videoCapture.zoom } set { self.videoCapture.zoom = newValue } } var isSettingsOpen = false @IBAction func settingsButtonFired(sender: UIButton) { if !self.isSettingsOpen { self.settingsViewController!.settingsWillOpen() } self.view.layoutIfNeeded() let offset = (self.isSettingsOpen ? -(self.settingsWidthConstraint.constant) : 0) UIView.animateWithDuration(0.6, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: ({ self.settingsOffsetConstraint.constant = offset self.view.layoutIfNeeded() }), completion: { (finished:Bool) -> Void in self.isSettingsOpen = !self.isSettingsOpen let scnView = self.view as! SCNView scnView.allowsCameraControl = !self.isSettingsOpen if !self.isSettingsOpen { self.settingsViewController!.settingsDidClose() } }) } @IBAction func videoButtonFired(sender: UIButton) { if self.recordingStatus == RecordingStatus.Stopped { self.setupVideoRecorderRecording() self.recordingStatus = RecordingStatus.Recording; self.imageRecording.hidden = false } else if self.recordingStatus == RecordingStatus.Recording { self.imageRecording.hidden = true self.stopRecording() } } private func setupVideoRecorderRecording() { self.deleteFile(self.videoRecordingTmpUrl) if(self.videoRecorder == nil) { // retrieve the SCNView if let scnView = self.view as? SCNView where scnView.eaglContext != nil { let width:GLsizei = GLsizei(scnView.bounds.size.width * UIScreen.mainScreen().scale) let height:GLsizei = GLsizei(scnView.bounds.size.height * UIScreen.mainScreen().scale) self.videoRecorder = FrameBufferVideoRecorder(movieUrl: self.videoRecordingTmpUrl, width: width, height: height) self.videoRecorder!.initVideoRecorder(scnView.eaglContext!) self.videoRecorder!.generateFramebuffer(scnView.eaglContext!) } } } private func stopRecording() { if self.recordingStatus == RecordingStatus.Recording { self.recordingStatus = RecordingStatus.FinishRequested; } } private func finishRecording() { self.videoRecorder?.finish({ (status:FrameBufferVideoRecorderStatus) -> Void in NSLog("Video recorder finished with status: " + status.description); if(status == FrameBufferVideoRecorderStatus.Completed) { let fileManager: NSFileManager = NSFileManager.defaultManager() if fileManager.fileExistsAtPath(self.videoRecordingTmpUrl.path!) { UISaveVideoAtPathToSavedPhotosAlbum(self.videoRecordingTmpUrl.path!, self, "video:didFinishSavingWithError:contextInfo:", nil) } else { NSLog("File does not exist: " + self.videoRecordingTmpUrl.path!); } } }) } func video(videoPath:NSString, didFinishSavingWithError error:NSErrorPointer, contextInfo:UnsafeMutablePointer<Void>) { NSLog("Finished saving video") self.videoRecorder = nil; self.recordingStatus = RecordingStatus.Stopped self.deleteFile(self.videoRecordingTmpUrl) } func deleteFile(fileUrl:NSURL) { let fileManager: NSFileManager = NSFileManager.defaultManager() if fileManager.fileExistsAtPath(fileUrl.path!) { var error:NSError? = nil; do { try fileManager.removeItemAtURL(fileUrl) } catch let error1 as NSError { error = error1 } if(error != nil) { NSLog("Error deleing file: %@ Error: %@", fileUrl, error!) } } } func takeShot() { let image = self.imageFromSceneKitView(self.view as! SCNView) UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) } func imageFromSceneKitView(sceneKitView:SCNView) -> UIImage { let w:Int = Int(sceneKitView.bounds.size.width * UIScreen.mainScreen().scale) let h:Int = Int(sceneKitView.bounds.size.height * UIScreen.mainScreen().scale) let myDataLength:Int = w * h * Int(4) let buffer = UnsafeMutablePointer<CGFloat>(calloc(myDataLength, Int(sizeof(CUnsignedChar)))) glReadPixels(0, 0, GLint(w), GLint(h), GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), buffer) let provider = CGDataProviderCreateWithData(nil, buffer, Int(myDataLength), nil) let bitsPerComponent:Int = 8 let bitsPerPixel:Int = 32 let bytesPerRow:Int = 4 * w let colorSpaceRef = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo.ByteOrderDefault let renderingIntent = CGColorRenderingIntent.RenderingIntentDefault // make the cgimage let decode:UnsafePointer<CGFloat> = nil; let cgImage = CGImageCreate(w, h, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, decode, false, renderingIntent) return UIImage(CGImage: cgImage!) } // // UIViewControlle overrides // override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return UIInterfaceOrientationMask.AllButUpsideDown } else { return UIInterfaceOrientationMask.All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
539c6c3cefa1eb18d8888734d2a2d8e5
35.195087
171
0.599752
5.090854
false
false
false
false
drscotthawley/add-menu-popover-demo
PopUpMenuTest/ViewController.swift
1
1401
// // ViewController.swift // PopUpMenuTest // // Created by Scott Hawley on 8/31/15. // Copyright © 2015 Scott Hawley. All rights reserved. // import UIKit class ViewController: UIViewController, UIPopoverPresentationControllerDelegate { @IBOutlet weak var addbutton: UIBarButtonItem! @IBOutlet weak var messageLabel: UILabel! var menuSelections : [String] = [] @IBAction func addButtonPress(sender: AnyObject) { self.performSegueWithIdentifier("showView", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showView" { let vc = segue.destinationViewController let controller = vc.popoverPresentationController if controller != nil { controller?.delegate = self } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. messageLabel.text = "" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } }
gpl-2.0
135f311ffe8918fb35f7ae3175fef823
25.923077
127
0.65
5.577689
false
false
false
false
jkolb/Swiftish
Sources/Swiftish/Bounds3.swift
1
9624
/* The MIT License (MIT) Copyright (c) 2015-2017 Justin Kolb Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ public struct Bounds3<T: Vectorable> : Hashable { public var center: Vector3<T> public var extents: Vector3<T> public init() { self.init(center: Vector3<T>(), extents: Vector3<T>()) } public init(minimum: Vector3<T>, maximum: Vector3<T>) { precondition(minimum.x <= maximum.x) precondition(minimum.y <= maximum.y) precondition(minimum.z <= maximum.z) let center = (maximum + minimum) / 2 let extents = (maximum - minimum) / 2 self.init(center: center, extents: extents) } public init(center: Vector3<T>, extents: Vector3<T>) { precondition(extents.x >= 0) precondition(extents.y >= 0) precondition(extents.z >= 0) self.center = center self.extents = extents } public init(union: [Bounds3<T>]) { var minmax = [Vector3<T>]() for other in union { if !other.isNull { minmax.append(other.minimum) minmax.append(other.maximum) } } self.init(containingPoints: minmax) } public init(containingPoints points: [Vector3<T>]) { if points.count == 0 { self.init() return } var minimum = Vector3<T>(+T.greatestFiniteMagnitude, +T.greatestFiniteMagnitude, +T.greatestFiniteMagnitude) var maximum = Vector3<T>(-T.greatestFiniteMagnitude, -T.greatestFiniteMagnitude, -T.greatestFiniteMagnitude) for point in points { if point.x < minimum.x { minimum.x = point.x } if point.x > maximum.x { maximum.x = point.x } if point.y < minimum.y { minimum.y = point.y } if point.y > maximum.y { maximum.y = point.y } if point.z < minimum.z { minimum.z = point.z } if point.z > maximum.z { maximum.z = point.z } } self.init(minimum: minimum, maximum: maximum) } public var minimum: Vector3<T> { return center - extents } public var maximum: Vector3<T> { return center + extents } public var isNull: Bool { return center == Vector3<T>() && extents == Vector3<T>() } public func contains(point: Vector3<T>) -> Bool { if point.x < minimum.x { return false } if point.y < minimum.y { return false } if point.z < minimum.z { return false } if point.x > maximum.x { return false } if point.y > maximum.y { return false } if point.z > maximum.z { return false } return true } /// If `other` bounds intersects current bounds, return their intersection. /// A `null` Bounds3 object is returned if any of those are `null` or if they don't intersect at all. /// /// - Note: A Bounds3 object `isNull` if it's center and extents are zero. /// - Parameter other: The second Bounds3 object to intersect with. /// - Returns: A Bounds3 object intersection. public func intersection(other: Bounds3<T>) -> Bounds3<T> { if isNull { return self } else if other.isNull { return other } else if minimum.x <= other.maximum.x && other.minimum.x <= maximum.x && maximum.y <= other.minimum.y && other.maximum.y <= minimum.y && maximum.z <= other.minimum.z && other.maximum.z <= minimum.z { let minX = max(minimum.x, other.minimum.x) let minY = max(minimum.y, other.minimum.y) let minZ = max(minimum.z, other.minimum.z) let maxX = min(maximum.x, other.maximum.x) let maxY = min(maximum.y, other.maximum.y) let maxZ = min(maximum.z, other.maximum.z) return Bounds3<T>(minimum: Vector3<T>(minX, minY, minZ), maximum: Vector3<T>(maxX, maxY, maxZ)) } return Bounds3<T>() } public func union(other: Bounds3<T>) -> Bounds3<T> { if isNull { return other } else if other.isNull { return self } else { return Bounds3<T>(containingPoints: [minimum, maximum, other.minimum, other.maximum]) } } public func union(others: [Bounds3<T>]) -> Bounds3<T> { var minmax = [Vector3<T>]() if !isNull { minmax.append(minimum) minmax.append(maximum) } for other in others { if !other.isNull { minmax.append(other.minimum) minmax.append(other.maximum) } } if minmax.count == 0 { return self } else { return Bounds3<T>(containingPoints: minmax) } } public var description: String { return "{\(center), \(extents)}" } public var corners: [Vector3<T>] { let max: Vector3<T> = maximum let corner0: Vector3<T> = max * Vector3<T>(+1, +1, +1) let corner1: Vector3<T> = max * Vector3<T>(-1, +1, +1) let corner2: Vector3<T> = max * Vector3<T>(+1, -1, +1) let corner3: Vector3<T> = max * Vector3<T>(+1, +1, -1) let corner4: Vector3<T> = max * Vector3<T>(-1, -1, +1) let corner5: Vector3<T> = max * Vector3<T>(+1, -1, -1) let corner6: Vector3<T> = max * Vector3<T>(-1, +1, -1) let corner7: Vector3<T> = max * Vector3<T>(-1, -1, -1) return [ corner0, corner1, corner2, corner3, corner4, corner5, corner6, corner7, ] } public static func distance2<T>(_ point: Vector3<T>, _ bounds: Bounds3<T>) -> T { var distanceSquared: T = 0 let minimum = bounds.minimum let maximum = bounds.maximum for index in 0..<3 { let p = point[index] let bMin = minimum[index] let bMax = maximum[index] if p < bMin { let delta = bMin - p distanceSquared = distanceSquared + delta * delta } if p > bMax { let delta = p - bMax distanceSquared = distanceSquared + delta * delta } } return distanceSquared } public func intersectsOrIsInside(_ plane: Plane<T>) -> Bool { let projectionRadiusOfBox = Vector3<T>.sum(extents * Vector3<T>.abs(plane.normal)) let distanceOfBoxCenterFromPlane = Vector3<T>.dot(plane.normal, center) - plane.distance let intersects = abs(distanceOfBoxCenterFromPlane) <= projectionRadiusOfBox let isInside = projectionRadiusOfBox <= distanceOfBoxCenterFromPlane return intersects || isInside } public func intersectsOrIsInside(_ frustum: Frustum<T>) -> Bool { if isNull { return false } // In order of most likely to cause early exit if !intersectsOrIsInside(frustum.near) { return false } if !intersectsOrIsInside(frustum.left) { return false } if !intersectsOrIsInside(frustum.right) { return false } if !intersectsOrIsInside(frustum.top) { return false } if !intersectsOrIsInside(frustum.bottom) { return false } if !intersectsOrIsInside(frustum.far) { return false } return true } public func intersects(_ plane: Plane<T>) -> Bool { let projectionRadiusOfBox = Vector3<T>.sum(extents * Vector3<T>.abs(plane.normal)) let distanceOfBoxCenterFromPlane = Swift.abs(Vector3<T>.dot(plane.normal, center) - plane.distance) return distanceOfBoxCenterFromPlane <= projectionRadiusOfBox } public func intersects(_ bounds: Bounds3<T>) -> Bool { if Swift.abs(center.x - bounds.center.x) > (extents.x + bounds.extents.x) { return false } if Swift.abs(center.y - bounds.center.y) > (extents.y + bounds.extents.y) { return false } if Swift.abs(center.z - bounds.center.z) > (extents.z + bounds.extents.z) { return false } return true } public func transform(_ t: Transform3<T>) -> Bounds3<T> { return Bounds3<T>(containingPoints: corners.map({ $0.transform(t) })) } }
mit
769fea16f716d2232b4a7059d63e9490
34.252747
206
0.568579
4.00833
false
false
false
false
muukii0803/PhotosPicker
PhotosPicker/Sources/PhotosPickerController.swift
2
3441
// PhotosPickerController.swift // // Copyright (c) 2015 muukii // // 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 import Photos import AssetsLibrary import CoreLocation /** * PhotosPickerController */ public class PhotosPickerController: UINavigationController { public private(set) var collectionController: PhotosPickerCollectionsController? /// public var allowsEditing: Bool = false public var didFinishPickingAssets: ((controller: PhotosPickerController, assets: [PhotosPickerAsset]) -> Void)? public var didCancel: ((controller: PhotosPickerController) -> Void)? public var setupSections: ((defaultSection: PhotosPickerCollectionsSection) -> [PhotosPickerCollectionsSection])? /** :returns: */ public init() { let controller = PhotosPicker.CollectionsControllerClass(nibName: nil, bundle: nil) super.init(rootViewController: controller) self.collectionController = controller } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.setup() } private func setup() { if PhotosPicker.authorizationStatus != .Authorized { if AvailablePhotos() { PhotosPicker.requestAuthorization({ (status) -> Void in self.setup() }) } return } PhotosPicker.requestDefaultSection { section in self.collectionController?.sectionInfo = self.setupSections?(defaultSection: section) } } public static var defaultSelectionHandler = { (collectionsController: PhotosPickerCollectionsController, item: PhotosPickerCollectionsItem) -> Void in let controller = PhotosPicker.AssetsControllerClass() controller.item = item collectionsController.navigationController?.pushViewController(controller, animated: true) } }
mit
e15bb9b47e38f9340bcbfd000a7038f4
34.112245
154
0.671898
5.44462
false
false
false
false
ksco/swift-algorithm-club-cn
Union-Find/UnionFind.playground/Contents.swift
1
2968
//: Playground - noun: a place where people can play public struct UnionFind<T: Hashable> { private var index = [T: Int]() private var parent = [Int]() private var size = [Int]() public mutating func addSetWith(element: T) { index[element] = parent.count parent.append(parent.count) size.append(1) } private mutating func setByIndex(index: Int) -> Int { if parent[index] == index { return index } else { parent[index] = setByIndex(parent[index]) return parent[index] } } public mutating func setOf(element: T) -> Int? { if let indexOfElement = index[element] { return setByIndex(indexOfElement) } else { return nil } } public mutating func unionSetsContaining(firstElement: T, and secondElement: T) { if let firstSet = setOf(firstElement), secondSet = setOf(secondElement) { if firstSet != secondSet { if size[firstSet] < size[secondSet] { parent[firstSet] = secondSet size[secondSet] += size[firstSet] } else { parent[secondSet] = firstSet size[firstSet] += size[secondSet] } } } } public mutating func inSameSet(firstElement: T, and secondElement: T) -> Bool { if let firstSet = setOf(firstElement), secondSet = setOf(secondElement) { return firstSet == secondSet } else { return false } } } var dsu = UnionFind<Int>() for i in 1...10 { dsu.addSetWith(i) } // now our dsu contains 10 independent sets // let's divide our numbers into two sets by divisibility by 2 for i in 3...10 { if i % 2 == 0 { dsu.unionSetsContaining(2, and: i) } else { dsu.unionSetsContaining(1, and: i) } } // check our division print(dsu.inSameSet(2, and: 4)) print(dsu.inSameSet(4, and: 6)) print(dsu.inSameSet(6, and: 8)) print(dsu.inSameSet(8, and: 10)) print(dsu.inSameSet(1, and: 3)) print(dsu.inSameSet(3, and: 5)) print(dsu.inSameSet(5, and: 7)) print(dsu.inSameSet(7, and: 9)) print(dsu.inSameSet(7, and: 4)) print(dsu.inSameSet(3, and: 6)) var dsuForStrings = UnionFind<String>() let words = ["all", "border", "boy", "afternoon", "amazing", "awesome", "best"] dsuForStrings.addSetWith("a") dsuForStrings.addSetWith("b") // In that example we divide strings by its first letter for word in words { dsuForStrings.addSetWith(word) if word.hasPrefix("a") { dsuForStrings.unionSetsContaining("a", and: word) } else if word.hasPrefix("b") { dsuForStrings.unionSetsContaining("b", and: word) } } print(dsuForStrings.inSameSet("a", and: "all")) print(dsuForStrings.inSameSet("all", and: "awesome")) print(dsuForStrings.inSameSet("amazing", and: "afternoon")) print(dsuForStrings.inSameSet("b", and: "boy")) print(dsuForStrings.inSameSet("best", and: "boy")) print(dsuForStrings.inSameSet("border", and: "best")) print(dsuForStrings.inSameSet("amazing", and: "boy")) print(dsuForStrings.inSameSet("all", and: "border"))
mit
e8b310eb2aa03e1a3ab6cd687d23cbdd
23.733333
83
0.653976
3.212121
false
false
false
false
ijoshsmith/json2swift
json2swift/json-schema-inference.swift
1
5642
// // json-schema-inference.swift // json2swift // // Created by Joshua Smith on 10/10/16. // Copyright © 2016 iJoshSmith. All rights reserved. // import Foundation // MARK: - JSONElementSchema extension extension JSONElementSchema { static func inferred(from jsonElementArray: [JSONElement], named name: String) -> JSONElementSchema { let jsonElement = [name: jsonElementArray] let schema = JSONElementSchema.inferred(from: jsonElement, named: name) let (_, attributeType) = schema.attributes.first! switch attributeType { case .elementArray(_, let elementSchema, _): return elementSchema case .emptyArray: return JSONElementSchema(name: name) default: abort() } } static func inferred(from jsonElement: JSONElement, named name: String) -> JSONElementSchema { let attributes = createAttributeMap(for: jsonElement) return JSONElementSchema(name: name, attributes: attributes) } private static func createAttributeMap(for jsonElement: JSONElement) -> JSONAttributeMap { let attributes = jsonElement.map { (name, value) -> (String, JSONType) in let type = JSONType.inferType(of: value, named: name) return (name, type) } return JSONAttributeMap(entries: attributes) } } // MARK: - JSONType extension fileprivate extension JSONType { static func inferType(of value: Any, named name: String) -> JSONType { switch value { case let element as JSONElement: return inferType(of: element, named: name) case let array as [Any]: return inferType(of: array, named: name) case let nsValue as NSValue: return inferType(of: nsValue) case let string as String: return inferType(of: string) case is NSNull: return .nullable default: assertionFailure("Unexpected type of value in JSON: \(value)") abort() } } private static func inferType(of element: JSONElement, named name: String) -> JSONType { let schema = JSONElementSchema.inferred(from: element, named: name) return .element(isRequired: true, schema: schema) } private static func inferType(of array: [Any], named name: String) -> JSONType { let arrayWithoutNulls = array.filter { $0 is NSNull == false } if let elements = arrayWithoutNulls as? [JSONElement] { let hasNullableElements = arrayWithoutNulls.count < array.count return inferType(ofElementArray: elements, named: name, hasNullableElements: hasNullableElements) } else { return inferType(ofValueArray: array, named: name) } } private static func inferType(ofElementArray elementArray: [JSONElement], named name: String, hasNullableElements: Bool) -> JSONType { if elementArray.isEmpty { return .emptyArray } let schemas = elementArray.map { jsonElement in JSONElementSchema.inferred(from: jsonElement, named: name) } let mergedSchema = JSONElementSchema.inferredByMergingAttributes(of: schemas, named: name) return .elementArray(isRequired: true, elementSchema: mergedSchema, hasNullableElements: hasNullableElements) } private static func inferType(ofValueArray valueArray: [JSONValue], named name: String) -> JSONType { if valueArray.isEmpty { return .emptyArray } let valueType = inferValueType(of: valueArray, named: name) return .valueArray(isRequired: true, valueType: valueType) } private static func inferValueType(of values: [JSONValue], named name: String) -> JSONType { let types = values.map { inferType(of: $0, named: name) } switch types.count { case 0: abort() // Should never introspect an empty array. case 1: return types[0] default: return types.dropFirst().reduce(types[0]) { $0.findCompatibleType(with: $1) } } } private static func inferType(of nsValue: NSValue) -> JSONType { if nsValue.isBoolType { return .bool(isRequired: true) } else { return .number(isRequired: true, isFloatingPoint: nsValue.isFloatType) } } private static func inferType(of string: String) -> JSONType { if let dateFormat = string.extractDateFormat() { return .date(isRequired: true, format: dateFormat) } else if string.isWebAddress { return .url(isRequired: true) } else { return .string(isRequired: true) } } } // MARK: - String extension fileprivate extension String { func extractDateFormat() -> String? { let trimmed = trimmingCharacters(in: CharacterSet.whitespaces) return String.extractDateFormat(from: trimmed) } private static func extractDateFormat(from string: String) -> String? { guard let prefixRange = string.range(of: dateFormatPrefix) else { return nil } guard prefixRange.lowerBound == string.startIndex else { return nil } return String(string[prefixRange.upperBound...]) } var isWebAddress: Bool { guard let url = URL(string: self) else { return false } return url.scheme != nil && url.host != nil } } // MARK: - NSValue extension fileprivate extension NSValue { var isBoolType: Bool { return CFNumberGetType((self as! CFNumber)) == CFNumberType.charType } var isFloatType: Bool { return CFNumberIsFloatType((self as! CFNumber)) } }
mit
6e648b036dc0222196badfc4572868c3
40.477941
138
0.64758
4.455766
false
false
false
false
jonnguy/HSTracker
HSTracker/UIs/Trackers/CardHudContainer.swift
1
5038
// // CardHudContainer.swift // HSTracker // // Created by Benjamin Michotte on 16/06/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import AppKit class CardHudContainer: OverWindowController { var positions: [Int: [NSPoint]] = [:] var huds: [CardHud] = [] @IBOutlet weak var container: NSView! override func windowDidLoad() { super.windowDidLoad() for _ in 0 ..< 10 { let hud = CardHud() hud.alphaValue = 0.0 container.addSubview(hud) huds.append(hud) } initPoints() } func initPoints() { positions[1] = [ NSPoint(x: 144, y: -3) ] positions[2] = [ NSPoint(x: 97, y: -1), NSPoint(x: 198, y: -1) ] positions[3] = [ NSPoint(x: 42, y: 19), NSPoint(x: 146, y: -1), NSPoint(x: 245, y: 8) ] positions[4] = [ NSPoint(x: 31, y: 28), NSPoint(x: 109, y: 6), NSPoint(x: 185, y: -1), NSPoint(x: 262, y: 5) ] positions[5] = [ NSPoint(x: 21, y: 26), NSPoint(x: 87, y: 6), NSPoint(x: 148, y: -4), NSPoint(x: 211, y: -2), NSPoint(x: 274, y: 9) ] positions[6] = [ NSPoint(x: 19, y: 36), NSPoint(x: 68, y: 15), NSPoint(x: 123, y: 2), NSPoint(x: 175, y: -3), NSPoint(x: 229, y: 0), NSPoint(x: 278, y: 9) ] positions[7] = [ NSPoint(x: 12.0, y: 36.0), NSPoint(x: 57.0, y: 16.0), NSPoint(x: 104.0, y: 4.0), NSPoint(x: 153.0, y: -1.0), NSPoint(x: 194.0, y: -3.0), NSPoint(x: 240.0, y: 6.0), NSPoint(x: 283.0, y: 19.0) ] positions[8] = [ NSPoint(x: 14.0, y: 38.0), NSPoint(x: 52.0, y: 22.0), NSPoint(x: 92.0, y: 6.0), NSPoint(x: 134.0, y: -2.0), NSPoint(x: 172.0, y: -5.0), NSPoint(x: 210.0, y: -4.0), NSPoint(x: 251.0, y: 1.0), NSPoint(x: 289.0, y: 10.0) ] positions[9] = [ NSPoint(x: 16.0, y: 38.0), NSPoint(x: 57.0, y: 25.0), NSPoint(x: 94.0, y: 12.0), NSPoint(x: 127.0, y: 3.0), NSPoint(x: 162.0, y: -1.0), NSPoint(x: 201.0, y: -6.0), NSPoint(x: 238.0, y: 2.0), NSPoint(x: 276.0, y: 13.0), NSPoint(x: 315.0, y: 28.0) ] positions[10] = [ NSPoint(x: 21.0, y: 40.0), NSPoint(x: 53.0, y: 30.0), NSPoint(x: 86.0, y: 20.0), NSPoint(x: 118.0, y: 8.0), NSPoint(x: 149.0, y: -1.0), NSPoint(x: 181.0, y: -2.0), NSPoint(x: 211.0, y: -0.0), NSPoint(x: 245.0, y: 1.0), NSPoint(x: 281.0, y: 12.0), NSPoint(x: 319.0, y: 23.0) ] } func reset() { for hud in huds { hud.alphaValue = 0.0 hud.frame = NSRect.zero } } func update(entities: [Entity], cardCount: Int) { for (i, hud) in huds.enumerated() { var hide = true if let entity = entities.first(where: { $0[.zone_position] == i + 1 }) { hud.entity = entity var pos: NSPoint? if let points = positions[cardCount], points.count > i { pos = points[i] if let pos = pos { hide = false let rect = NSRect(x: pos.x * SizeHelper.hearthstoneWindow.scaleX, y: pos.y * SizeHelper.hearthstoneWindow.scaleY, width: 36, height: 45) hud.needsDisplay = true // this will avoid a weird move if hud.frame == NSRect.zero { hud.frame = rect } NSAnimationContext.runAnimationGroup({ (context) in context.duration = 0.5 hud.animator().frame = rect hud.animator().alphaValue = 1.0 }, completionHandler: nil) } } } if hide { NSAnimationContext.runAnimationGroup({ (context) in context.duration = 0.5 hud.animator().alphaValue = 0.0 }, completionHandler: nil) } } } }
mit
ea450f32b00374f815b3aa52196e0c36
29.343373
89
0.386738
3.853864
false
false
false
false
ale84/ABLE
ABLE/Mocks/CBServiceMock.swift
1
611
// // Created by Alessio Orlando on 14/06/18. // Copyright © 2019 Alessio Orlando. All rights reserved. // import Foundation import CoreBluetooth public class CBServiceMock: CBServiceType { public var cbCharacteristics: [CBCharacteristicType]? public var isPrimary: Bool public var characteristics: [CBCharacteristic]? public var uuid: CBUUID public init(with id: CBUUID = CBUUID(), isPrimary: Bool = true, characteristics: [CBCharacteristic]? = nil) { self.uuid = id self.isPrimary = isPrimary self.characteristics = characteristics } }
mit
39ead2e771bd47b257cc14b3baafa72d
25.521739
113
0.686885
4.84127
false
false
false
false
TylerTheCompiler/TTPOverlayViewController
Example/ViewController.swift
2
4582
// The MIT License (MIT) // // Copyright (c) 2017 Tyler Prevost // // 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 import OverlayViewController class ViewController: UIViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let segue = segue as? OverlaySegue { let overlayVC = segue.overlayViewController if let senderView = sender as? UIView { overlayVC.sourceFrameForOverlayViewHandler = { [weak senderView] _ in return senderView?.frame ?? .null } } overlayVC.minimumMargins = { overlayVC in switch overlayVC.viewSizeClass { case .phonePortrait: return UIEdgeInsets(top: 50, left: 20, bottom: 50, right: 20) case .smallPhoneLandscape: return UIEdgeInsets(top: 30, left: 20, bottom: 30, right: 20) case .largePhoneLandscape: return UIEdgeInsets(top: 60, left: 50, bottom: 60, right: 50) case .padWideTall: return UIEdgeInsets(top: 100, left: 50, bottom: 100, right: 50) case .padWideShort: return UIEdgeInsets(top: 60, left: 60, bottom: 60, right: 60) case .padThin: return UIEdgeInsets(top: 80, left: 30, bottom: 80, right: 30) default: return .zero } } } } @IBAction func unwindToViewController(_ segue: UIStoryboardSegue) { // empty } } enum UserInterfaceIdiomSizeClass { case phonePortrait case smallPhoneLandscape case largePhoneLandscape case pad case padThin case tv case carPlay case unknown } extension UITraitCollection { var userInterfaceIdiomSizeClass: UserInterfaceIdiomSizeClass { switch (horizontalSizeClass, verticalSizeClass, userInterfaceIdiom) { case (.compact, .compact, .phone): return .smallPhoneLandscape case (.compact, .regular, .phone): return .phonePortrait case (.regular, .compact, .phone): return .largePhoneLandscape case (.compact, .regular, .pad): return .padThin case (.regular, .regular, .pad): return .pad case (_, _, .tv): return .tv case (_, _, .carPlay): return .carPlay default: return .unknown } } } enum ViewSizeClass { case phonePortrait case smallPhoneLandscape case largePhoneLandscape case padWideTall case padWideShort case padThin case tv case carPlay case unknown } extension UIView { var viewSizeClass: ViewSizeClass { let windowFrame = window?.frame ?? .zero switch (traitCollection.userInterfaceIdiomSizeClass, windowFrame.width > windowFrame.height) { case (.phonePortrait, _): return .phonePortrait case (.smallPhoneLandscape, _): return .smallPhoneLandscape case (.largePhoneLandscape, _): return .largePhoneLandscape case (.padThin, _): return .padThin case (.pad, true): return .padWideShort case (.pad, false): return .padWideTall case (.tv, _): return .tv case (.carPlay, _): return .carPlay default: return .unknown } } } extension UIViewController { var viewSizeClass: ViewSizeClass { guard isViewLoaded else { return .unknown } return view.viewSizeClass } }
mit
08dfc43ba6b58fed3b0bbb3976cf873a
34.796875
102
0.635749
4.823158
false
false
false
false
vincent-cheny/DailyRecord
DailyRecord/ChartViewController.swift
1
13333
// // ChartViewController.swift // DailyRecord // // Created by ChenYong on 16/2/12. // Copyright © 2016年 LazyPanda. All rights reserved. // import UIKit import RealmSwift import PNChart class ChartViewController: UIViewController { @IBOutlet weak var dateType: UIBarButtonItem! @IBOutlet weak var chartType: UIBarButtonItem! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var pieChart: CustomPNPieChart! @IBOutlet weak var lineChart: PNLineChart! let realm = try! Realm() let dateFormatter = NSDateFormatter() var showDate = NSDate() var dateRange: [NSTimeInterval]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. dateFormatter.dateFormat = "yyyy.M.d" updateTime(dateType.title!, diff: 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBarHidden = false; } @IBAction func plusDate(sender: AnyObject) { updateTime(dateType.title!, diff: 1) } @IBAction func minusDate(sender: AnyObject) { updateTime(dateType.title!, diff: -1) } @IBAction func switchChartType(sender: AnyObject) { let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.Alert) addChartType(alert, type: "饼状图") addChartType(alert, type: "折线图") self.presentViewController(alert, animated: true, completion: nil) } @IBAction func switchDateType(sender: AnyObject) { let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.Alert) addDateType(alert, type: "本周") addDateType(alert, type: "本月") addDateType(alert, type: "本年") self.presentViewController(alert, animated: true, completion: nil) } @IBAction func respondToRightSwipeGesture(sender: AnyObject) { updateTime(dateType.title!, diff: -1) } @IBAction func respondToLeftSwipeGesture(sender: AnyObject) { updateTime(dateType.title!, diff: 1) } @IBAction func respondToUpSwipeGesture(sender: AnyObject) { switchChartType() } @IBAction func respondToDownSwipeGesture(sender: AnyObject) { switchChartType() } func switchChartType() { if chartType.title == "饼状图" { chartType.title = "折线图" } else { chartType.title = "饼状图" } updateChart() } func addChartType(alert: UIAlertController, type: String) { alert.addAction(UIAlertAction(title: type, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in self.chartType.title = type self.updateChart() })) } func addDateType(alert: UIAlertController, type: String) { alert.addAction(UIAlertAction(title: type, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in self.dateType.title = type self.showDate = NSDate() self.updateTime(type, diff: 0) })) } func updateTime(type: String, diff: Int) { switch type { case "本周": let weekComponent = NSDateComponents() weekComponent.day = diff * 7; showDate = NSCalendar.currentCalendar().dateByAddingComponents(weekComponent, toDate: showDate, options: NSCalendarOptions())! timeLabel.text = Utils.getWeek(dateFormatter, date: showDate) dateRange = Utils.getWeekRange(showDate) updateChart() case "本月": let monthComponent = NSDateComponents() monthComponent.month = diff; showDate = NSCalendar.currentCalendar().dateByAddingComponents(monthComponent, toDate: showDate, options: NSCalendarOptions())! timeLabel.text = Utils.getYearMonth(showDate) dateRange = Utils.getMonthRange(showDate) updateChart() case "本年": let yearComponent = NSDateComponents() yearComponent.year = diff; showDate = NSCalendar.currentCalendar().dateByAddingComponents(yearComponent, toDate: showDate, options: NSCalendarOptions())! timeLabel.text = Utils.getYear(showDate) dateRange = Utils.getYearRange(showDate) updateChart() default: break } } func updateChart() { let black = realm.objects(Industry).filter("type = '黑业' AND time BETWEEN {%@, %@}", dateRange[0], dateRange[1]).count let blackCheck = realm.objects(Industry).filter("type = '黑业对治' AND time BETWEEN {%@, %@}", dateRange[0], dateRange[1]).count let white = realm.objects(Industry).filter("type = '白业' AND time BETWEEN {%@, %@}", dateRange[0], dateRange[1]).count let whiteCheck = realm.objects(Industry).filter("type = '白业对治' AND time BETWEEN {%@, %@}", dateRange[0], dateRange[1]).count pieChart.hidden = true lineChart.hidden = true if black + blackCheck + white + whiteCheck > 0 { switch chartType.title! { case "饼状图": pieChart.hidden = false var dataItems = [PNPieChartDataItem]() if black > 0 { dataItems.append(PNPieChartDataItem(value: CGFloat(black), color: UIColor.blackColor(), description: "黑业")) } if blackCheck > 0 { dataItems.append(PNPieChartDataItem(value: CGFloat(blackCheck), color: UIColor.greenColor(), description: "黑业对治")) } if white > 0 { dataItems.append(PNPieChartDataItem(value: CGFloat(white), color: UIColor.whiteColor(), description: "白业")) } if whiteCheck > 0 { dataItems.append(PNPieChartDataItem(value: CGFloat(whiteCheck), color: UIColor.redColor(), description: "白业对治")) } pieChart.updateChartData(dataItems) pieChart.descriptionTextColor = UIColor.lightGrayColor() pieChart.descriptionTextFont = UIFont.systemFontOfSize(11.0) pieChart.descriptionTextShadowColor = UIColor.clearColor() pieChart.displayAnimated = false pieChart.showAbsoluteValues = true pieChart.userInteractionEnabled = false pieChart.strokeChart() pieChart.legendStyle = PNLegendItemStyle.Stacked pieChart.legendFontColor = UIColor.lightGrayColor() pieChart.legendFont = UIFont.boldSystemFontOfSize(12.0) let legend = pieChart.getLegendWithMaxWidth(200) legend.frame = CGRect(x: 0, y: view.frame.width * 2 / 3, width: legend.frame.size.width, height: legend.frame.size.height) pieChart.addSubview(legend) break case "折线图": lineChart.hidden = false lineChart.displayAnimated = false lineChart.chartMarginLeft = 35 lineChart.chartCavanHeight = lineChart.frame.height - 250 var data01Array: [NSNumber]! var data02Array: [NSNumber]! var data03Array: [NSNumber]! var data04Array: [NSNumber]! switch dateType.title! { case "本周": lineChart.setXLabels(["", "2", "", "4", "", "6", ""], withWidth: (view.frame.width - 75) / 8) data01Array = getEveryDayData("黑业") data02Array = getEveryDayData("黑业对治") data03Array = getEveryDayData("白业") data04Array = getEveryDayData("白业对治") case "本月": lineChart.setXLabels(["", "", "", "", "", "", "", "", "", "10", "", "", "", "", "", "", "", "", "", "20", "", "", "", "", "", "", "", "", "", "30", ""], withWidth: (view.frame.width - 75) / 32) data01Array = getEveryDayData("黑业") data02Array = getEveryDayData("黑业对治") data03Array = getEveryDayData("白业") data04Array = getEveryDayData("白业对治") case "本年": lineChart.setXLabels(["", "", "", "", "5", "", "", "", "", "10", "", ""], withWidth: (view.frame.width - 75) / 13) data01Array = getEveryMonthData("黑业") data02Array = getEveryMonthData("黑业对治") data03Array = getEveryMonthData("白业") data04Array = getEveryMonthData("白业对治") default: break } lineChart.showCoordinateAxis = true lineChart.yFixedValueMin = 0.0 lineChart.backgroundColor = UIColor.clearColor() lineChart.axisColor = UIColor.lightGrayColor() let data01 = PNLineChartData() data01.inflexionPointStyle = PNLineChartPointStyle.Circle; data01.inflexionPointWidth = 2 data01.dataTitle = "黑业" data01.color = UIColor.blackColor() data01.itemCount = UInt(data01Array.count) data01.getData = { (index: UInt) -> PNLineChartDataItem in let yValue = data01Array[Int(index)] return PNLineChartDataItem.init(y: CGFloat(yValue)) } let data02 = PNLineChartData() data02.inflexionPointStyle = PNLineChartPointStyle.Circle; data02.inflexionPointWidth = 2 data02.dataTitle = "黑业对治" data02.color = UIColor.greenColor() data02.itemCount = UInt(data02Array.count) data02.getData = { (index: UInt) -> PNLineChartDataItem in let yValue = data02Array[Int(index)] return PNLineChartDataItem.init(y: CGFloat(yValue)) } let data03 = PNLineChartData() data03.inflexionPointStyle = PNLineChartPointStyle.Circle; data03.inflexionPointWidth = 2 data03.dataTitle = "白业" data03.color = UIColor.whiteColor() data03.itemCount = UInt(data03Array.count) data03.getData = { (index: UInt) -> PNLineChartDataItem in let yValue = data03Array[Int(index)] return PNLineChartDataItem.init(y: CGFloat(yValue)) } let data04 = PNLineChartData() data04.inflexionPointStyle = PNLineChartPointStyle.Circle; data04.inflexionPointWidth = 2 data04.dataTitle = "白业对治" data04.color = UIColor.redColor() data04.itemCount = UInt(data04Array.count) data04.getData = { (index: UInt) -> PNLineChartDataItem in let yValue = data04Array[Int(index)] return PNLineChartDataItem.init(y: CGFloat(yValue)) } lineChart.chartData = [data01, data02, data03, data04] lineChart.strokeChart() lineChart.legendStyle = PNLegendItemStyle.Stacked lineChart.legendFont = UIFont.boldSystemFontOfSize(12.0) lineChart.legendFontColor = UIColor.lightGrayColor() let legend = lineChart.getLegendWithMaxWidth(320) legend.frame = CGRect(x: 100, y: view.frame.height - 280, width: legend.frame.size.width, height: legend.frame.size.height) lineChart.addSubview(legend) default: break } } } func getEveryDayData(type: String) -> [NSNumber] { var result = [NSNumber]() let dayDuration = Double(60 * 60 * 24) var startDay = dateRange[0] while startDay < dateRange[1] { result.append(realm.objects(Industry).filter("type = %@ AND time BETWEEN {%@, %@}", type, startDay, startDay + dayDuration - 1).count) startDay += dayDuration } return result } func getEveryMonthData(type: String) -> [NSNumber] { var result = [NSNumber]() let calendar = NSCalendar.currentCalendar() let monthComponent = NSDateComponents() monthComponent.month = 1; var startDay = dateRange[0] while startDay < dateRange[1] { let nextStartDay = calendar.dateByAddingComponents(monthComponent, toDate: NSDate(timeIntervalSince1970: startDay), options: NSCalendarOptions())!.timeIntervalSince1970 result.append(realm.objects(Industry).filter("type = %@ AND time BETWEEN {%@, %@}", type, startDay, nextStartDay - 1).count) startDay = nextStartDay } return result } }
gpl-2.0
87b642c6bfc5a2675a51e7569f6e140b
44.835664
213
0.58163
4.768279
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/DistinctUntilChanged.swift
57
2189
// // DistinctUntilChanged.swift // RxSwift // // Created by Krunoslav Zaher on 3/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class DistinctUntilChangedSink<O: ObserverType, Key>: Sink<O>, ObserverType { typealias E = O.E private let _parent: DistinctUntilChanged<E, Key> private var _currentKey: Key? = nil init(parent: DistinctUntilChanged<E, Key>, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<E>) { switch event { case .next(let value): do { let key = try _parent._selector(value) var areEqual = false if let currentKey = _currentKey { areEqual = try _parent._comparer(currentKey, key) } if areEqual { return } _currentKey = key forwardOn(event) } catch let error { forwardOn(.error(error)) dispose() } case .error, .completed: forwardOn(event) dispose() } } } class DistinctUntilChanged<Element, Key>: Producer<Element> { typealias KeySelector = (Element) throws -> Key typealias EqualityComparer = (Key, Key) throws -> Bool fileprivate let _source: Observable<Element> fileprivate let _selector: KeySelector fileprivate let _comparer: EqualityComparer init(source: Observable<Element>, selector: @escaping KeySelector, comparer: @escaping EqualityComparer) { _source = source _selector = selector _comparer = comparer } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = DistinctUntilChangedSink(parent: self, observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) return (sink: sink, subscription: subscription) } }
apache-2.0
0aea779fcfe99ad113ddba337926932f
30.257143
144
0.572669
4.939052
false
false
false
false
PLJNS/TZStackView
TZStackView/TZStackView.swift
1
25972
// // TZStackView.swift // TZStackView // // Created by Tom van Zummeren on 10/06/15. // Copyright © 2015 Tom van Zummeren. All rights reserved. // import UIKit struct TZAnimationDidStopQueueEntry: Equatable { let view: UIView let hidden: Bool } func ==(lhs: TZAnimationDidStopQueueEntry, rhs: TZAnimationDidStopQueueEntry) -> Bool { return lhs.view === rhs.view } @IBDesignable public class TZStackView: UIView { public var distribution: TZStackViewDistribution = .Fill { didSet { setNeedsUpdateConstraints() } } public var axis: UILayoutConstraintAxis = .Horizontal { didSet { setNeedsUpdateConstraints() } } public var alignment: TZStackViewAlignment = .Fill public var spacing: CGFloat = 0 public var layoutMarginsRelativeArrangement = false public var arrangedSubviews: [UIView] = [] { didSet { setNeedsUpdateConstraints() registerHiddenListeners(oldValue) } } private var kvoContext = UInt8() private var stackViewConstraints = [NSLayoutConstraint]() private var subviewConstraints = [NSLayoutConstraint]() private var spacerViews = [UIView]() private var animationDidStopQueueEntries = [TZAnimationDidStopQueueEntry]() private var registeredKvoSubviews = [UIView]() private var animatingToHiddenViews = [UIView]() public override init(frame: CGRect) { super.init(frame: CGRectZero) } public init(arrangedSubviews: [UIView] = []) { super.init(frame: CGRectZero) for arrangedSubview in arrangedSubviews { arrangedSubview.translatesAutoresizingMaskIntoConstraints = false addSubview(arrangedSubview) } // Closure to invoke didSet() { self.arrangedSubviews = arrangedSubviews }() } deinit { // This removes `hidden` value KVO observers using didSet() { self.arrangedSubviews = [] }() } private func registerHiddenListeners(previousArrangedSubviews: [UIView]) { for subview in previousArrangedSubviews { self.removeHiddenListener(subview) } for subview in arrangedSubviews { self.addHiddenListener(subview) } } private func addHiddenListener(view: UIView) { view.addObserver(self, forKeyPath: "hidden", options: [.Old, .New], context: &kvoContext) registeredKvoSubviews.append(view) } private func removeHiddenListener(view: UIView) { if let index = registeredKvoSubviews.indexOf(view) { view.removeObserver(self, forKeyPath: "hidden", context: &kvoContext) registeredKvoSubviews.removeAtIndex(index) } } public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let view = object as? UIView, change = change where keyPath == "hidden" { let hidden = view.hidden let previousValue = change["old"] as! Bool if hidden == previousValue { return } if hidden { animatingToHiddenViews.append(view) } // Perform the animation setNeedsUpdateConstraints() setNeedsLayout() layoutIfNeeded() removeHiddenListener(view) view.hidden = false if let _ = view.layer.animationKeys() { UIView.setAnimationDelegate(self) animationDidStopQueueEntries.insert(TZAnimationDidStopQueueEntry(view: view, hidden: hidden), atIndex: 0) UIView.setAnimationDidStopSelector("hiddenAnimationStopped") } else { didFinishSettingHiddenValue(view, hidden: hidden) } } } private func didFinishSettingHiddenValue(arrangedSubview: UIView, hidden: Bool) { arrangedSubview.hidden = hidden if let index = animatingToHiddenViews.indexOf(arrangedSubview) { animatingToHiddenViews.removeAtIndex(index) } addHiddenListener(arrangedSubview) } func hiddenAnimationStopped() { var queueEntriesToRemove = [TZAnimationDidStopQueueEntry]() for entry in animationDidStopQueueEntries { let view = entry.view if view.layer.animationKeys() == nil { didFinishSettingHiddenValue(view, hidden: entry.hidden) queueEntriesToRemove.append(entry) } } for entry in queueEntriesToRemove { if let index = animationDidStopQueueEntries.indexOf(entry) { animationDidStopQueueEntries.removeAtIndex(index) } } } public func addArrangedSubview(view: UIView) { view.translatesAutoresizingMaskIntoConstraints = false addSubview(view) arrangedSubviews.append(view) } public func removeArrangedSubview(view: UIView) { if let index = arrangedSubviews.indexOf(view) { arrangedSubviews.removeAtIndex(index) } } public func insertArrangedSubview(view: UIView, atIndex stackIndex: Int) { view.translatesAutoresizingMaskIntoConstraints = false addSubview(view) arrangedSubviews.insert(view, atIndex: stackIndex) } override public func willRemoveSubview(subview: UIView) { removeArrangedSubview(subview) } override public func updateConstraints() { removeConstraints(stackViewConstraints) stackViewConstraints.removeAll() for arrangedSubview in arrangedSubviews { arrangedSubview.removeConstraints(subviewConstraints) } subviewConstraints.removeAll() for arrangedSubview in arrangedSubviews { if alignment != .Fill { let guideConstraint: NSLayoutConstraint switch axis { case .Horizontal: guideConstraint = constraint(item: arrangedSubview, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 25) case .Vertical: guideConstraint = constraint(item: arrangedSubview, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 25) } subviewConstraints.append(guideConstraint) arrangedSubview.addConstraint(guideConstraint) } if isHidden(arrangedSubview) { let hiddenConstraint: NSLayoutConstraint switch axis { case .Horizontal: hiddenConstraint = constraint(item: arrangedSubview, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, constant: 0) case .Vertical: hiddenConstraint = constraint(item: arrangedSubview, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, constant: 0) } subviewConstraints.append(hiddenConstraint) arrangedSubview.addConstraint(hiddenConstraint) } } for spacerView in spacerViews { spacerView.removeFromSuperview() } spacerViews.removeAll() if arrangedSubviews.count > 0 { let visibleArrangedSubviews = arrangedSubviews.filter({!self.isHidden($0)}) switch distribution { case .FillEqually, .Fill, .FillProportionally: if alignment != .Fill || layoutMarginsRelativeArrangement { addSpacerView() } stackViewConstraints += createMatchEdgesContraints(arrangedSubviews) stackViewConstraints += createFirstAndLastViewMatchEdgesContraints() if alignment == .FirstBaseline && axis == .Horizontal { stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } if distribution == .FillEqually { stackViewConstraints += createFillEquallyConstraints(arrangedSubviews) } if distribution == .FillProportionally { stackViewConstraints += createFillProportionallyConstraints(arrangedSubviews) } stackViewConstraints += createFillConstraints(arrangedSubviews, constant: spacing) case .EqualSpacing: var views = [UIView]() var index = 0 for arrangedSubview in arrangedSubviews { if isHidden(arrangedSubview) { continue } if index > 0 { views.append(addSpacerView()) } views.append(arrangedSubview) index++ } if spacerViews.count == 0 { addSpacerView() } stackViewConstraints += createMatchEdgesContraints(arrangedSubviews) stackViewConstraints += createFirstAndLastViewMatchEdgesContraints() switch axis { case .Horizontal: stackViewConstraints.append(constraint(item: self, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, priority: 49)) if alignment == .FirstBaseline { stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } case .Vertical: stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } stackViewConstraints += createFillConstraints(views, constant: 0) stackViewConstraints += createFillEquallyConstraints(spacerViews) stackViewConstraints += createFillConstraints(arrangedSubviews, relatedBy: .GreaterThanOrEqual, constant: spacing) case .EqualCentering: for (index, _) in visibleArrangedSubviews.enumerate() { if index > 0 { addSpacerView() } } if spacerViews.count == 0 { addSpacerView() } stackViewConstraints += createMatchEdgesContraints(arrangedSubviews) stackViewConstraints += createFirstAndLastViewMatchEdgesContraints() switch axis { case .Horizontal: stackViewConstraints.append(constraint(item: self, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, priority: 49)) if alignment == .FirstBaseline { stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } case .Vertical: stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } var previousArrangedSubview: UIView? for (index, arrangedSubview) in visibleArrangedSubviews.enumerate() { if let previousArrangedSubview = previousArrangedSubview { let spacerView = spacerViews[index - 1] switch axis { case .Horizontal: stackViewConstraints.append(constraint(item: previousArrangedSubview, attribute: .CenterX, toItem: spacerView, attribute: .Leading)) stackViewConstraints.append(constraint(item: arrangedSubview, attribute: .CenterX, toItem: spacerView, attribute: .Trailing)) case .Vertical: stackViewConstraints.append(constraint(item: previousArrangedSubview, attribute: .CenterY, toItem: spacerView, attribute: .Top)) stackViewConstraints.append(constraint(item: arrangedSubview, attribute: .CenterY, toItem: spacerView, attribute: .Bottom)) } } previousArrangedSubview = arrangedSubview } stackViewConstraints += createFillEquallyConstraints(spacerViews, priority: 150) stackViewConstraints += createFillConstraints(arrangedSubviews, relatedBy: .GreaterThanOrEqual, constant: spacing) } if spacerViews.count > 0 { stackViewConstraints += createSurroundingSpacerViewConstraints(spacerViews[0], views: visibleArrangedSubviews) } if layoutMarginsRelativeArrangement { if spacerViews.count > 0 { stackViewConstraints.append(constraint(item: self, attribute: .BottomMargin, toItem: spacerViews[0])) stackViewConstraints.append(constraint(item: self, attribute: .LeftMargin, toItem: spacerViews[0])) stackViewConstraints.append(constraint(item: self, attribute: .RightMargin, toItem: spacerViews[0])) stackViewConstraints.append(constraint(item: self, attribute: .TopMargin, toItem: spacerViews[0])) } } addConstraints(stackViewConstraints) } super.updateConstraints() } override public func prepareForInterfaceBuilder() { } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } private func addSpacerView() -> TZSpacerView { let spacerView = TZSpacerView() spacerView.translatesAutoresizingMaskIntoConstraints = false spacerViews.append(spacerView) insertSubview(spacerView, atIndex: 0) return spacerView } private func createSurroundingSpacerViewConstraints(spacerView: UIView, views: [UIView]) -> [NSLayoutConstraint] { if alignment == .Fill { return [] } var topPriority: Float = 1000 var topRelation: NSLayoutRelation = .LessThanOrEqual var bottomPriority: Float = 1000 var bottomRelation: NSLayoutRelation = .GreaterThanOrEqual if alignment == .Top || alignment == .Leading { topPriority = 999.5 topRelation = .Equal } if alignment == .Bottom || alignment == .Trailing { bottomPriority = 999.5 bottomRelation = .Equal } var constraints = [NSLayoutConstraint]() for view in views { switch axis { case .Horizontal: constraints.append(constraint(item: spacerView, attribute: .Top, relatedBy: topRelation, toItem: view, priority: topPriority)) constraints.append(constraint(item: spacerView, attribute: .Bottom, relatedBy: bottomRelation, toItem: view, priority: bottomPriority)) case .Vertical: constraints.append(constraint(item: spacerView, attribute: .Leading, relatedBy: topRelation, toItem: view, priority: topPriority)) constraints.append(constraint(item: spacerView, attribute: .Trailing, relatedBy: bottomRelation, toItem: view, priority: bottomPriority)) } } switch axis { case .Horizontal: constraints.append(constraint(item: spacerView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 51)) case .Vertical: constraints.append(constraint(item: spacerView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 51)) } return constraints } private func createFillProportionallyConstraints(views: [UIView]) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() var totalSize: CGFloat = 0 var totalCount = 0 for arrangedSubview in views { if isHidden(arrangedSubview) { continue } switch axis { case .Horizontal: totalSize += arrangedSubview.intrinsicContentSize().width case .Vertical: totalSize += arrangedSubview.intrinsicContentSize().height } totalCount++ } totalSize += (CGFloat(totalCount - 1) * spacing) var priority: Float = 1000 let countDownPriority = (views.filter({!self.isHidden($0)}).count > 1) for arrangedSubview in views { if countDownPriority { priority-- } if isHidden(arrangedSubview) { continue } switch axis { case .Horizontal: let multiplier = arrangedSubview.intrinsicContentSize().width / totalSize constraints.append(constraint(item: arrangedSubview, attribute: .Width, toItem: self, multiplier: multiplier, priority: priority)) case .Vertical: let multiplier = arrangedSubview.intrinsicContentSize().height / totalSize constraints.append(constraint(item: arrangedSubview, attribute: .Height, toItem: self, multiplier: multiplier, priority: priority)) } } return constraints } // Matchs all Width or Height attributes of all given views private func createFillEquallyConstraints(views: [UIView], priority: Float = 1000) -> [NSLayoutConstraint] { switch axis { case .Horizontal: return equalAttributes(views: views.filter({ !self.isHidden($0) }), attribute: .Width, priority: priority) case .Vertical: return equalAttributes(views: views.filter({ !self.isHidden($0) }), attribute: .Height, priority: priority) } } // Chains together the given views using Leading/Trailing or Top/Bottom private func createFillConstraints(views: [UIView], priority: Float = 1000, relatedBy relation: NSLayoutRelation = .Equal, constant: CGFloat) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() var previousView: UIView? for view in views { if let previousView = previousView { var c: CGFloat = 0 if !isHidden(previousView) && !isHidden(view) { c = constant } else if isHidden(previousView) && !isHidden(view) && views.first != previousView { c = (constant / 2) } else if isHidden(view) && !isHidden(previousView) && views.last != view { c = (constant / 2) } switch axis { case .Horizontal: constraints.append(constraint(item: view, attribute: .Leading, relatedBy: relation, toItem: previousView, attribute: .Trailing, constant: c, priority: priority)) case .Vertical: constraints.append(constraint(item: view, attribute: .Top, relatedBy: relation, toItem: previousView, attribute: .Bottom, constant: c, priority: priority)) } } previousView = view } return constraints } // Matches all Bottom/Top or Leading Trailing constraints of te given views and matches those attributes of the first/last view to the container private func createMatchEdgesContraints(views: [UIView]) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() switch axis { case .Horizontal: switch alignment { case .Fill: constraints += equalAttributes(views: views, attribute: .Bottom) constraints += equalAttributes(views: views, attribute: .Top) case .Center: constraints += equalAttributes(views: views, attribute: .CenterY) case .Leading, .Top: constraints += equalAttributes(views: views, attribute: .Top) case .Trailing, .Bottom: constraints += equalAttributes(views: views, attribute: .Bottom) case .FirstBaseline: constraints += equalAttributes(views: views, attribute: .FirstBaseline) } case .Vertical: switch alignment { case .Fill: constraints += equalAttributes(views: views, attribute: .Leading) constraints += equalAttributes(views: views, attribute: .Trailing) case .Center: constraints += equalAttributes(views: views, attribute: .CenterX) case .Leading, .Top: constraints += equalAttributes(views: views, attribute: .Leading) case .Trailing, .Bottom: constraints += equalAttributes(views: views, attribute: .Trailing) case .FirstBaseline: constraints += [] } } return constraints } private func createFirstAndLastViewMatchEdgesContraints() -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() let visibleViews = arrangedSubviews.filter({!self.isHidden($0)}) let firstView = visibleViews.first let lastView = visibleViews.last var topView = arrangedSubviews.first! var bottomView = arrangedSubviews.first! if spacerViews.count > 0 { if alignment == .Center { topView = spacerViews[0] bottomView = spacerViews[0] } else if alignment == .Top || alignment == .Leading { bottomView = spacerViews[0] } else if alignment == .Bottom || alignment == .Trailing { topView = spacerViews[0] } else if alignment == .FirstBaseline { switch axis { case .Horizontal: bottomView = spacerViews[0] case .Vertical: topView = spacerViews[0] bottomView = spacerViews[0] } } } let firstItem = layoutMarginsRelativeArrangement ? spacerViews[0] : self switch axis { case .Horizontal: if let firstView = firstView { constraints.append(constraint(item: firstItem, attribute: .Leading, toItem: firstView)) } if let lastView = lastView { constraints.append(constraint(item: firstItem, attribute: .Trailing, toItem: lastView)) } constraints.append(constraint(item: firstItem, attribute: .Top, toItem: topView)) constraints.append(constraint(item: firstItem, attribute: .Bottom, toItem: bottomView)) if alignment == .Center { constraints.append(constraint(item: firstItem, attribute: .CenterY, toItem: arrangedSubviews.first!)) } case .Vertical: if let firstView = firstView { constraints.append(constraint(item: firstItem, attribute: .Top, toItem: firstView)) } if let lastView = lastView { constraints.append(constraint(item: firstItem, attribute: .Bottom, toItem: lastView)) } constraints.append(constraint(item: firstItem, attribute: .Leading, toItem: topView)) constraints.append(constraint(item: firstItem, attribute: .Trailing, toItem: bottomView)) if alignment == .Center { constraints.append(constraint(item: firstItem, attribute: .CenterX, toItem: arrangedSubviews.first!)) } } return constraints } private func equalAttributes(views views: [UIView], attribute: NSLayoutAttribute, priority: Float = 1000) -> [NSLayoutConstraint] { var currentPriority = priority var constraints = [NSLayoutConstraint]() if views.count > 0 { var firstView: UIView? let countDownPriority = (currentPriority < 1000) for view in views { if let firstView = firstView { constraints.append(constraint(item: firstView, attribute: attribute, toItem: view, priority: currentPriority)) } else { firstView = view } if countDownPriority { currentPriority-- } } } return constraints } // Convenience method to help make NSLayoutConstraint in a less verbose way private func constraint(item view1: AnyObject, attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation = .Equal, toItem view2: AnyObject?, attribute attr2: NSLayoutAttribute? = nil, multiplier: CGFloat = 1, constant c: CGFloat = 0, priority: Float = 1000) -> NSLayoutConstraint { let attribute2 = attr2 != nil ? attr2! : attr1 let constraint = NSLayoutConstraint(item: view1, attribute: attr1, relatedBy: relation, toItem: view2, attribute: attribute2, multiplier: multiplier, constant: c) constraint.priority = priority return constraint } private func isHidden(view: UIView) -> Bool { if view.hidden { return true } return animatingToHiddenViews.indexOf(view) != nil } }
mit
e15a033e2bb6a03ffbe9fbcc4de52e67
41.092382
300
0.592083
5.669286
false
false
false
false
moysklad/ios-remap-sdk
Sources/MoyskladiOSRemapSDK/Structs/Contract.swift
1
3407
// // Contract.swift // MoyskladNew // // Created by Anton Efimenko on 24.10.16. // Copyright © 2016 Andrey Parshakov. All rights reserved. // //import Money import Foundation public enum MSContractType : String { case commission = "Commission" case sales = "Sales" } public enum MSRewardType : String { case percentOfSales = "PercentOfSales" case none = "None" } /** Represents Contract. Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#договор) */ public class MSContract: MSAttributedEntity, Metable { public var meta: MSMeta public var id : MSID public var info : MSInfo public var accountId: String public var owner: MSEntity<MSEmployee>? public var shared: Bool public var group: MSEntity<MSGroup> public var code: String? public var externalCode: String? public var archived: Bool public var moment: Date? public var sum: Money public var contractType: MSContractType? public var rewardType: MSRewardType? public var rewardPercent: Int? public var ownAgent: MSEntity<MSAgent>? public var agent: MSEntity<MSAgent>? public var state: MSEntity<MSState>? public var organizationAccount: MSEntity<MSAccount>? public var agentAccount: MSEntity<MSAccount>? public var rate: MSRate? public init(meta: MSMeta, id : MSID, info : MSInfo, accountId: String, owner: MSEntity<MSEmployee>?, shared: Bool, group: MSEntity<MSGroup>, code: String?, externalCode: String?, archived: Bool, moment: Date?, sum: Money, contractType: MSContractType?, rewardType: MSRewardType?, rewardPercent: Int?, ownAgent: MSEntity<MSAgent>?, agent: MSEntity<MSAgent>?, state: MSEntity<MSState>?, organizationAccount: MSEntity<MSAccount>?, agentAccount: MSEntity<MSAccount>?, rate: MSRate?, attributes: [MSEntity<MSAttribute>]?) { self.meta = meta self.id = id self.info = info self.accountId = accountId self.owner = owner self.shared = shared self.group = group self.code = code self.externalCode = externalCode self.archived = archived self.moment = moment self.sum = sum self.contractType = contractType self.rewardType = rewardType self.rewardPercent = rewardPercent self.ownAgent = ownAgent self.agent = agent self.state = state self.organizationAccount = organizationAccount self.agentAccount = agentAccount self.rate = rate super.init(attributes: attributes) } public func copy() -> MSContract { return MSContract(meta: meta.copy(), id: id.copy(), info: info, accountId: accountId, owner: owner, shared: shared, group: group, code: code, externalCode: externalCode, archived: archived, moment: moment, sum: sum, contractType: contractType, rewardType: rewardType, rewardPercent: rewardPercent, ownAgent: ownAgent, agent: agent, state: state, organizationAccount: organizationAccount, agentAccount: agentAccount, rate: rate, attributes: attributes) } public func hasChanges(comparedTo other: MSContract) -> Bool { return (try? JSONSerialization.data(withJSONObject: dictionary(metaOnly: false), options: [])) ?? nil == (try? JSONSerialization.data(withJSONObject: other.dictionary(metaOnly: false), options: [])) ?? nil } }
mit
810d04c3460987f57eff12839935bf57
31.682692
459
0.689026
3.897936
false
false
false
false
gcba/hermes
sdks/swift/Pods/SwifterSwift/Sources/Extensions/Foundation/IntExtensions.swift
1
5795
// // IntExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/6/16. // Copyright © 2016 Omar Albeik. All rights reserved. // import Foundation #if os(macOS) import Cocoa #else import UIKit #endif // MARK: - Properties public extension Int { /// SwifterSwift: CountableRange 0..<Int. public var countableRange: CountableRange<Int> { return 0..<self } /// SwifterSwift: Radian value of degree input. public var degreesToRadians: Double { return Double.pi * Double(self) / 180.0 } /// SwifterSwift: Degree value of radian input public var radiansToDegrees: Double { return Double(self) * 180 / Double.pi } /// SwifterSwift: Number of digits of integer value. public var digitsCount: Int { return String(self).characters.count } /// SwifterSwift: UInt. public var uInt: UInt { return UInt(self) } /// SwifterSwift: Double. public var double: Double { return Double(self) } /// SwifterSwift: Float. public var float: Float { return Float(self) } /// SwifterSwift: CGFloat. public var cgFloat: CGFloat { return CGFloat(self) } /// SwifterSwift: Roman numeral string from integer (if applicable). public var romanNumeral: String? { // https://gist.github.com/kumo/a8e1cb1f4b7cff1548c7 guard self > 0 else { // there is no roman numerals for 0 or negative numbers return nil } let romanValues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] var romanValue = "" var startingValue = self for (index, romanChar) in romanValues.enumerated() { let arabicValue = arabicValues[index] let div = startingValue / arabicValue if (div > 0) { for _ in 0..<div { romanValue += romanChar } startingValue -= arabicValue * div } } return romanValue } /// SwifterSwift: String formatted for values over ±1000 (example: 1k, -2k, 100k, 1kk, -5kk..) public var kFormatted: String { var sign: String { return self >= 0 ? "" : "-" } let abs = self.abs if abs == 0 { return "0k" } else if abs >= 0 && abs < 1000 { return "0k" } else if abs >= 1000 && abs < 1000000 { return String(format: "\(sign)%ik", abs / 1000) } return String(format: "\(sign)%ikk", abs / 100000) } } // MARK: - Methods public extension Int { /// SwifterSwift: Random integer between two integer values. /// /// - Parameters: /// - min: minimum number to start random from. /// - max: maximum number random number end before. /// - Returns: random double between two double values. public static func random(between min: Int, and max: Int) -> Int { return random(inRange: min...max) } /// SwifterSwift: Random integer in a closed interval range. /// /// - Parameter range: closed interval range. /// - Returns: random double in the given closed range. public static func random(inRange range: ClosedRange<Int>) -> Int { let delta = UInt32(range.upperBound - range.lowerBound + 1) return range.lowerBound + Int(arc4random_uniform(delta)) } /// SwifterSwift: check if given integer prime or not. /// Warning: Using big numbers can be computationally expensive! /// - Returns: true or false depending on prime-ness public func isPrime() -> Bool { guard self > 1 || self % 2 == 0 else { return false } // To improve speed on latter loop :) if self == 2 { return true } // Explanation: It is enough to check numbers until // the square root of that number. If you go up from N by one, // other multiplier will go 1 down to get similar result // (integer-wise operation) such way increases speed of operation let base = Int(sqrt(Double(self)) + 1) for i in Swift.stride(from: 3, to: base, by: 2) { if self % i == 0 { return false } } return true } } // MARK: - Initializers public extension Int { /// SwifterSwift: Created a random integer between two integer values. /// /// - Parameters: /// - min: minimum number to start random from. /// - max: maximum number random number end before. public init(randomBetween min: Int, and max: Int) { self = Int.random(between: min, and: max) } /// SwifterSwift: Create a random integer in a closed interval range. /// /// - Parameter range: closed interval range. public init(randomInRange range: ClosedRange<Int>) { self = Int.random(inRange: range) } } // MARK: - Operators precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence } infix operator ** : PowerPrecedence /// SwifterSwift: Value of exponentiation. /// /// - Parameters: /// - lhs: base integer. /// - rhs: exponent integer. /// - Returns: exponentiation result (example: 2 ** 3 = 8). public func ** (lhs: Int, rhs: Int) -> Double { // http://nshipster.com/swift-operators/ return pow(Double(lhs), Double(rhs)) } prefix operator √ /// SwifterSwift: Square root of integer. /// /// - Parameter int: integer value to find square root for /// - Returns: square root of given integer. public prefix func √ (int: Int) -> Double { // http://nshipster.com/swift-operators/ return sqrt(Double(int)) } infix operator ± /// SwifterSwift: Tuple of plus-minus operation. /// /// - Parameters: /// - lhs: integer number. /// - rhs: integer number. /// - Returns: tuple of plus-minus operation (example: 2 ± 3 -> (5, -1)). public func ± (lhs: Int, rhs: Int) -> (Int, Int) { // http://nshipster.com/swift-operators/ return (lhs + rhs, lhs - rhs) } prefix operator ± /// SwifterSwift: Tuple of plus-minus operation. /// /// - Parameter int: integer number /// - Returns: tuple of plus-minus operation (example: ± 2 -> (2, -2)). public prefix func ± (int: Int) -> (Int, Int) { // http://nshipster.com/swift-operators/ return 0 ± int }
mit
e8dc3a3aefa980d51130531ab3cd1e78
25.045045
95
0.65652
3.385246
false
false
false
false
TENDIGI/Obsidian-UI-iOS
src/Permissions.swift
1
8264
// // Permissions.swift // Alfredo // // Created by Eric Kunz on 8/14/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import Foundation import AddressBook import EventKit import CoreLocation import AVFoundation import Photos /// Easily acces the app's permissions to open class Permissions { public enum PermissionStatus { case authorized, unauthorized, unknown, disabled } // MARK: Constants fileprivate let AskedForNotificationsDefaultsKey = "AskedForNotificationsDefaultsKey" // MARK: Managers lazy var locationManager = CLLocationManager() // MARK:- Permissions // MARK: Contacts /// The authorization status of access to the device's contacts. open func authorizationStatusContacts() -> PermissionStatus { let status = ABAddressBookGetAuthorizationStatus() switch status { case .authorized: return .authorized case .restricted, .denied: return .unauthorized case .notDetermined: return .unknown } } /** Requests authorization by presenting the system alert. This will not present the alert and will return false if the authorization is unauthorized or already denied. - returns: Bool indicates if authorization was requested (true) or if it is not requested because it is already authorized, unauthorized, disabled (false). */ open func askAuthorizationContacts() { switch authorizationStatusContacts() { case .unknown: ABAddressBookRequestAccessWithCompletion(nil, nil) default: break } } // MARK: Location Always /// The authorization status of access to the device's location at all times. open func authorizationStatusLocationAlways() -> PermissionStatus { if !CLLocationManager.locationServicesEnabled() { return .disabled } let status = CLLocationManager.authorizationStatus() switch status { case .authorizedAlways: return .authorized case .restricted, .denied: return .unauthorized case .notDetermined, .authorizedWhenInUse: return .unknown } } /** Requests authorization by presenting the system alert. This will not present the alert and will return false if the authorization is unauthorized or already denied. - returns: Bool indicates if authorization was requested (true) or if it is not requested because it is already authorized, unauthorized, disabled (false). */ open func askAuthorizationLocationAlways() -> Bool { switch authorizationStatusLocationAlways() { case .unknown: locationManager.requestAlwaysAuthorization() return true case .unauthorized, .authorized, .disabled: return false } } // MARK: Location While In Use /// The authorization status of access to the device's location. open func authorizationStatusLocationInUse() -> PermissionStatus { if !CLLocationManager.locationServicesEnabled() { return .disabled } let status = CLLocationManager.authorizationStatus() switch status { case .authorizedWhenInUse, .authorizedAlways: return .authorized case .restricted, .denied: return .unauthorized case .notDetermined: return .unknown } } /** Requests authorization by presenting the system alert. This will not present the alert and will return false if the authorization is unauthorized or already denied. - returns: Bool indicates if authorization was requested (true) or if it is not requested because it is already authorized, unauthorized, disabled (false). */ open func askAuthorizationLocationInUse() -> Bool { switch authorizationStatusLocationAlways() { case .unknown: locationManager.requestAlwaysAuthorization() return true case .unauthorized, .authorized, .disabled: return false } } // MARK: Notifications /// The authorization status of the app receiving notifications. open func authorizationStatusNotifications() -> PermissionStatus { let settings = UIApplication.shared.currentUserNotificationSettings if settings?.types != UIUserNotificationType() { return .authorized } else { if UserDefaults.standard.bool(forKey: AskedForNotificationsDefaultsKey) { return .unauthorized } else { return .unknown } } } /** Requests authorization by presenting the system alert. This will not present the alert and will return false if the authorization is unauthorized or already denied. - returns: Bool indicates if authorization was requested (true) or if it is not requested because it is already authorized, unauthorized, disabled (false). */ open func askAuthorizationNotifications() -> Bool { switch authorizationStatusNotifications() { case .unknown: let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil) UIApplication.shared.registerUserNotificationSettings(settings) return true case .unauthorized, .authorized, .disabled: return false } } // MARK: Photos /// The authorization status for access to the photo library. open func authorizationStatusPhotos() -> PermissionStatus { let status = PHPhotoLibrary.authorizationStatus() switch status { case .authorized: return .authorized case .denied, .restricted: return .unauthorized case .notDetermined: return .unknown } } /** Requests authorization by presenting the system alert. This will not present the alert and will return false if the authorization is unauthorized or already denied. - returns: Bool indicates if authorization was requested (true) or if it is not requested because it is already authorized, unauthorized, disabled (false). */ open func askAuthorizationStatusPhotos() -> Bool { let status = authorizationStatusPhotos() switch status { case .unknown: PHPhotoLibrary.requestAuthorization { (status: PHAuthorizationStatus) -> Void in } return true case .authorized, .disabled, .unauthorized: return false } } // MARK: Camera /// The authorization status for use of the camera. open func authorizationStatusCamera() -> PermissionStatus { let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) switch status { case .authorized: return .authorized case .denied, .restricted: return .unauthorized case .notDetermined: return .unknown } } /** Requests authorization by presenting the system alert. This will not present the alert and will return false if the authorization is unauthorized or already denied. - returns: Bool indicates if authorization was requested (true) or if it is not requested because it is already authorized, unauthorized, disabled (false). */ open func askAuthorizationStatusCamera() -> Bool { let status = authorizationStatusCamera() switch status { case .unknown: AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) -> Void in }) return true case .disabled, .unauthorized, .authorized: return false } } // MARK: System Settings /** Opens the app's system settings If the app has its own settings bundle they will be opened, else the main settings view will be presented. */ open func openAppSettings() { let url = URL(string: UIApplicationOpenSettingsURLString)! if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } } }
mit
cbe645fe7cc0d6285ac738653d079133
30.907336
119
0.653679
5.742877
false
false
false
false
lorismaz/LaDalle
LaDalle/LaDalle/BusinessDetailsViewController.swift
1
6334
// // BusinessDetailsViewController.swift // LaDalle // // Created by Loris Mazloum on 9/16/16. // Copyright © 2016 Loris Mazloum. All rights reserved. // import UIKit import MapKit import CoreLocation class BusinessDetailsViewController: UIViewController, MKMapViewDelegate, UITableViewDelegate, UITableViewDataSource { //MARK: Global Declarations var business: Business? var userLocation: CLLocation? var reviews: [Review] = [Review]() //MARK: Properties and Outlets @IBOutlet weak var businessMapView: MKMapView! @IBOutlet weak var businessNameLabel: UILabel! @IBOutlet weak var businessReviewImageView: UIImageView! @IBOutlet weak var businessReviewCountLabel: UILabel! @IBOutlet weak var reviewTableView: UITableView! @IBAction func actionButtonTapped(_ sender: UIBarButtonItem) { shareSheetController() } //MARK: - Annotations //MARK: - Overlays //MARK: - Map setup //MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() guard let currentBusiness = business else { return } currentBusiness.getReviews(completionHandler: { (reviews) in self.main.addOperation { self.reviews = reviews for review in reviews { print("Review: \(review.text)") //self.businessReviewLabel.text = review.text } self.reviewTableView.reloadData() } }) //Delegates reviewTableView.delegate = self reviewTableView.dataSource = self // set estimated height reviewTableView.estimatedRowHeight = 95.0 // set automaticdimension reviewTableView.rowHeight = UITableViewAutomaticDimension businessMapView.delegate = self populateBusinessInfo() addAnnotation() zoomToBusinessLocation() } //The Main OperationQueue is where any UI changes or updates happen private let main = OperationQueue.main //The Async OperationQueue is where any background tasks such as //Loading from the network, and parsing JSON happen. //This makes sure the Main UI stays sharp, responsive, and smooth private let async: OperationQueue = { //The Queue is being created by this closure let operationQueue = OperationQueue() //This represents how many tasks can run at the same time, in this case 8 tasks //That means that we can load 8 images at a time operationQueue.maxConcurrentOperationCount = 8 return operationQueue }() func zoomToBusinessLocation() { guard let currentBusiness = self.business else { return } guard let userLocation = self.userLocation else { return } let businessLocation = CLLocation(latitude: currentBusiness.coordinate.latitude, longitude: currentBusiness.coordinate.longitude) //get distance between user and business let distanceFromBusiness = userLocation.distance(from: businessLocation) print("Distance: \(distanceFromBusiness) meters") //let distanceFromBusiness = userCoordinate.distance(from: currentBusiness.coordinate) let regionRadius: CLLocationDistance = distanceFromBusiness * 10 print("Region Radius: \(regionRadius) meters") let coordinateRegion = MKCoordinateRegionMakeWithDistance(businessLocation.coordinate, regionRadius, regionRadius) businessMapView.setRegion(coordinateRegion, animated: true) } func addAnnotation(){ guard let currentBusiness = business else { return } businessMapView.addAnnotation(currentBusiness) } func populateBusinessInfo() { guard let business = business else { return } businessNameLabel.text = business.name let ratingImageName = Business.getRatingImage(rating: business.rating) businessReviewImageView.image = UIImage(named: ratingImageName) //businessReviewImageView.image businessReviewCountLabel.text = "Based on " + String(business.reviewCount) + " reviews." } func shareSheetController() { guard let business = business else { return } var activities: [Any] = [] let message = "Trying out \(business.name), thanks to La Dalle by @lorismaz & the new @Yelp Fusion API" activities.append(message) if let image: UIImage = Business.getImage(from: business.imageUrl) { activities.append(image) } if business.url != "" { activities.append(business.url) } let shareSheet = UIActivityViewController(activityItems: activities, applicationActivities: nil) shareSheet.excludedActivityTypes = [ UIActivityType.postToWeibo, UIActivityType.mail, UIActivityType.print, UIActivityType.copyToPasteboard, UIActivityType.assignToContact, UIActivityType.saveToCameraRoll, UIActivityType.addToReadingList, UIActivityType.postToFlickr, UIActivityType.postToVimeo, UIActivityType.postToTencentWeibo ] present(shareSheet, animated: true, completion: nil) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return reviews.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = indexPath.row let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewCell", for: indexPath) as! ReviewCell // Get current row's category let review = reviews[row] // Design the cell cell.reviewContentTextView.text = review.text cell.userNameLabel.text = review.user.name return cell } }
mit
aa3a2060bbef3c304805f5bf172393f5
32.157068
137
0.630033
5.72604
false
false
false
false
manikad24/JASidePanelsSwift
JASidePanelsSwift/Classes/UIViewController+JASidePanel.swift
1
885
// // UIViewController+JASidePanel.swift // Pods // // Created by Manikandan Prabhu on 18/11/16. // // import Foundation import UIKit extension UIViewController{ public func sidePanelController() -> JASidePanelController { var iter = self.parent while (iter != nil) { if (iter is JASidePanelController) { return (iter as! JASidePanelController) } else if (iter!.parent! != iter) { iter = iter!.parent! } else { iter = nil } } return JASidePanelController() } } extension Int { var f: CGFloat { return CGFloat(self) } } extension Float { var f: CGFloat { return CGFloat(self) } } extension Double { var f: CGFloat { return CGFloat(self) } } extension CGFloat { var swf: Float { return Float(self) } }
mit
a8a5c38bc92e4c19e1e5c36091e636c3
19.113636
64
0.566102
3.96861
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Chat/New Chat/Cells/AudioMessageCell.swift
1
3803
// // AudioMessageCell.swift // Rocket.Chat // // Created by Filipe Alvarenga on 15/10/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit import Foundation import AVFoundation import RocketChatViewController final class AudioMessageCell: BaseAudioMessageCell, SizingCell { static let identifier = String(describing: AudioMessageCell.self) static let sizingCell: UICollectionViewCell & ChatCell = { guard let cell = AudioMessageCell.instantiateFromNib() else { return AudioMessageCell() } return cell }() @IBOutlet weak var avatarContainerView: UIView! { didSet { avatarContainerView.layer.cornerRadius = 4 avatarView.frame = avatarContainerView.bounds avatarContainerView.addSubview(avatarView) } } @IBOutlet weak var viewPlayerBackground: UIView! { didSet { viewPlayerBackground.layer.borderWidth = 1 viewPlayerBackground.layer.cornerRadius = 4 } } @IBOutlet weak var username: UILabel! @IBOutlet weak var date: UILabel! @IBOutlet weak var statusView: UIImageView! @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! @IBOutlet weak var buttonPlay: UIButton! @IBOutlet weak var readReceiptButton: UIButton! @IBOutlet weak var slider: UISlider! { didSet { slider.value = 0 slider.setThumbImage(UIImage(named: "Player Progress Button"), for: .normal) } } @IBOutlet weak var labelAudioTime: UILabel! { didSet { labelAudioTime.font = labelAudioTime.font.bold() } } override var playing: Bool { didSet { updatePlayingState(with: buttonPlay) } } override var loading: Bool { didSet { updateLoadingState(with: activityIndicatorView, and: labelAudioTime) } } deinit { updateTimer?.invalidate() } override func awakeFromNib() { super.awakeFromNib() updateTimer = setupPlayerTimer(with: slider, and: labelAudioTime) insertGesturesIfNeeded(with: username) } override func configure(completeRendering: Bool) { configure(readReceipt: readReceiptButton) configure( with: avatarView, date: date, status: statusView, and: username, completeRendering: completeRendering ) if completeRendering { updateAudio() } } override func prepareForReuse() { super.prepareForReuse() slider.value = 0 labelAudioTime.text = "--:--" playing = false loading = false } // MARK: IBAction @IBAction func didStartSlidingSlider(_ sender: UISlider) { startSlidingSlider(sender) } @IBAction func didFinishSlidingSlider(_ sender: UISlider) { finishSlidingSlider(sender) } @IBAction func didPressPlayButton(_ sender: UIButton) { pressPlayButton(sender) } } // MARK: Theming extension AudioMessageCell { override func applyTheme() { super.applyTheme() let theme = self.theme ?? .light date.textColor = theme.auxiliaryText username.textColor = theme.titleText viewPlayerBackground.backgroundColor = theme.chatComponentBackground labelAudioTime.textColor = theme.auxiliaryText updatePlayingState(with: buttonPlay) viewPlayerBackground.layer.borderColor = theme.borderColor.cgColor } } // MARK: AVAudioPlayerDelegate extension AudioMessageCell { override func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { playing = false slider.value = 0.0 } }
mit
93609c9a2b7539f033d3e035aab9f44a
25.22069
97
0.643609
5.035762
false
false
false
false
ben-ng/swift
stdlib/public/SDK/Intents/INStartWorkoutIntent.swift
1
1359
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 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 // //===----------------------------------------------------------------------===// @_exported import Intents import Foundation #if os(iOS) @available(iOS 10.0, *) extension INStartWorkoutIntent { @nonobjc public convenience init( workoutName: INSpeakableString? = nil, goalValue: Double? = nil, workoutGoalUnitType: INWorkoutGoalUnitType = .unknown, workoutLocationType: INWorkoutLocationType = .unknown, isOpenEnded: Bool? = nil ) { self.init(__workoutName: workoutName, goalValue: goalValue.map { NSNumber(value: $0) }, workoutGoalUnitType: workoutGoalUnitType, workoutLocationType: workoutLocationType, isOpenEnded: isOpenEnded.map { NSNumber(value: $0) }) } @nonobjc public final var goalValue: Double? { return __goalValue?.doubleValue } @nonobjc public final var isOpenEnded: Bool? { return __isOpenEnded?.boolValue } } #endif
apache-2.0
c6d42b49fd15e2d3e3ffb95b6b6add26
29.886364
80
0.626932
4.5
false
false
false
false
RobotRebels/Kratos2
Kratos2/Kratos2/Acronym.swift
1
495
// // Acronym.swift // Kratos2 // // Created by nbelopotapov on 17/05/17. // Copyright © 2017 RobotRebles. All rights reserved. // import UIKit class Acronym { var long: String = "" var short: String = "" var description: String = "" init() {} init(long: String, short: String, description: String) { self.long = long self.short = short self.description = description } init(dict: [String: AnyObject]?) { } }
mit
56f8bd8278b2769f6289b95fee8c0526
16.642857
60
0.566802
3.605839
false
false
false
false
Rdxer/SnapKit
Sources/LayoutConstraintItem.swift
6
3013
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public protocol LayoutConstraintItem: AnyObject { } @available(iOS 9.0, OSX 10.11, *) extension ConstraintLayoutGuide : LayoutConstraintItem { } extension ConstraintView : LayoutConstraintItem { } extension LayoutConstraintItem { internal func prepare() { if let view = self as? ConstraintView { view.translatesAutoresizingMaskIntoConstraints = false } } internal var superview: ConstraintView? { if let view = self as? ConstraintView { return view.superview } if #available(iOS 9.0, OSX 10.11, *), let guide = self as? ConstraintLayoutGuide { return guide.owningView } return nil } internal var constraints: [Constraint] { return self.constraintsSet.allObjects as! [Constraint] } internal func add(constraints: [Constraint]) { let constraintsSet = self.constraintsSet for constraint in constraints { constraintsSet.add(constraint) } } internal func remove(constraints: [Constraint]) { let constraintsSet = self.constraintsSet for constraint in constraints { constraintsSet.remove(constraint) } } private var constraintsSet: NSMutableSet { let constraintsSet: NSMutableSet if let existing = objc_getAssociatedObject(self, &constraintsKey) as? NSMutableSet { constraintsSet = existing } else { constraintsSet = NSMutableSet() objc_setAssociatedObject(self, &constraintsKey, constraintsSet, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } return constraintsSet } } private var constraintsKey: UInt8 = 0
mit
d45d904b8936c75d94d793fbd9e24214
31.397849
111
0.67607
4.805423
false
false
false
false
sosaucily/rottentomatoes
rottentomatoes/ViewController.swift
1
4344
// // ViewController.swift // rottentomatoes // // Created by Jesse Smith on 9/14/14. // Copyright (c) 2014 Jesse Smith. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var movieTableView: UITableView! var refreshControl: UIRefreshControl! var moviesArray: NSArray? let RottenTomatoesAPIKey = "3ep56bczb367ku9hruf7xpdq" override func viewDidLoad() { super.viewDidLoad() self.getMovieData() refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: "onRefresh", forControlEvents: UIControlEvents.ValueChanged) movieTableView.insertSubview(refreshControl, atIndex: 0) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (moviesArray != nil) ? moviesArray!.count : 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = movieTableView.dequeueReusableCellWithIdentifier("com.codepath.rottentomatoes.moviecell") as MovieTableViewCell let movieDictionary = self.moviesArray![indexPath.row] as NSDictionary cell.titleLabel.text = movieDictionary["title"] as NSString cell.descriptionLabel.text = movieDictionary["synopsis"] as NSString let postersDict = movieDictionary["posters"] as NSDictionary let thumbUrl = postersDict["thumbnail"] as NSString cell.thumbnailImageView.setImageWithURL(NSURL(string: thumbUrl)) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let detailsViewController = MovieDetailsViewController(nibName: "MovieDetails", bundle: nil) let movieDictionary = self.moviesArray![indexPath.row] as NSDictionary let postersDict = movieDictionary["posters"] as NSDictionary let thumbUrl = postersDict["thumbnail"] as NSString detailsViewController.fullImageUrl = thumbUrl.stringByReplacingOccurrencesOfString("tmb", withString: "ori") detailsViewController.movieDescriptionDict = movieDictionary self.navigationController?.pushViewController(detailsViewController, animated: true) } func getMovieData() { let RottenTomatoesURLString = "http://api.rottentomatoes.com/api/public/v1.0/lists/dvds/top_rentals.json?apikey=" + RottenTomatoesAPIKey let manager = AFHTTPRequestOperationManager() manager.GET(RottenTomatoesURLString, parameters: nil, success: self.updateViewWithMovies, failure: self.fetchMoviesError) let request = NSMutableURLRequest(URL: NSURL.URLWithString(RottenTomatoesURLString)) } func updateViewWithMovies(operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void { self.moviesArray = responseObject["movies"] as? NSArray self.movieTableView.reloadData() self.refreshControl.endRefreshing() self.hideNetworkError() } func fetchMoviesError(operation: AFHTTPRequestOperation!, error: NSError!) -> Void { self.showNetworkError() self.refreshControl.endRefreshing() } func onRefresh() { self.getMovieData() } func showNetworkError() { if (self.view.subviews.count == 1) { var networkErrorView: UILabel = UILabel (frame:CGRectMake(0, 65, 0, 0)); networkErrorView.backgroundColor = UIColor.grayColor() networkErrorView.alpha = 0.9 networkErrorView.textColor = UIColor.blackColor() networkErrorView.font = UIFont.boldSystemFontOfSize(10) networkErrorView.text = "Network Error!" UIView.animateWithDuration(0.25, animations: { networkErrorView.frame = CGRectMake(0, 65, 320, 30) }) self.view.addSubview(networkErrorView) } } func hideNetworkError() { if (self.view.subviews.count == 2) { self.view.subviews[1].removeFromSuperview() } } }
mit
7c82bfabaa2497d22574fc0214d17572
35.2
144
0.660912
5.284672
false
false
false
false
fizx/jane
ruby/lib/vendor/grpc-swift/Sources/SwiftGRPC/Runtime/ServiceServer.swift
4
5516
/* * Copyright 2018, gRPC 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 Dispatch import Foundation import SwiftProtobuf open class ServiceServer { public let address: String public let server: Server public var shouldLogRequests = true fileprivate let servicesByName: [String: ServiceProvider] /// Create a server that accepts insecure connections. public init(address: String, serviceProviders: [ServiceProvider]) { gRPC.initialize() self.address = address server = Server(address: address) servicesByName = Dictionary(uniqueKeysWithValues: serviceProviders.map { ($0.serviceName, $0) }) } /// Create a server that accepts secure connections. public init(address: String, certificateString: String, keyString: String, rootCerts: String? = nil, serviceProviders: [ServiceProvider]) { gRPC.initialize() self.address = address server = Server(address: address, key: keyString, certs: certificateString, rootCerts: rootCerts) servicesByName = Dictionary(uniqueKeysWithValues: serviceProviders.map { ($0.serviceName, $0) }) } /// Create a server that accepts secure connections. public init?(address: String, certificateURL: URL, keyURL: URL, rootCertsURL: URL? = nil, serviceProviders: [ServiceProvider]) { guard let certificate = try? String(contentsOf: certificateURL, encoding: .utf8), let key = try? String(contentsOf: keyURL, encoding: .utf8) else { return nil } var rootCerts: String? if let rootCertsURL = rootCertsURL { guard let rootCertsString = try? String(contentsOf: rootCertsURL, encoding: .utf8) else { return nil } rootCerts = rootCertsString } gRPC.initialize() self.address = address server = Server(address: address, key: key, certs: certificate, rootCerts: rootCerts) servicesByName = Dictionary(uniqueKeysWithValues: serviceProviders.map { ($0.serviceName, $0) }) } /// Start the server. public func start() { server.run { [weak self] handler in guard let strongSelf = self else { print("ERROR: ServiceServer has been asked to handle a request even though it has already been deallocated") return } let unwrappedMethod = handler.method ?? "(nil)" if strongSelf.shouldLogRequests == true { let unwrappedHost = handler.host ?? "(nil)" let unwrappedCaller = handler.caller ?? "(nil)" print("Server received request to " + unwrappedHost + " calling " + unwrappedMethod + " from " + unwrappedCaller + " with metadata " + handler.requestMetadata.dictionaryRepresentation.description) } do { do { let methodComponents = unwrappedMethod.components(separatedBy: "/") guard methodComponents.count >= 3 && methodComponents[0].isEmpty, let providerForServiceName = strongSelf.servicesByName[methodComponents[1]] else { throw HandleMethodError.unknownMethod } if let responseStatus = try providerForServiceName.handleMethod(unwrappedMethod, handler: handler), !handler.completionQueue.hasBeenShutdown { // The handler wants us to send the status for them; do that. // But first, ensure that all outgoing messages have been enqueued, to avoid ending the stream prematurely: handler.call.messageQueueEmpty.wait() try handler.sendStatus(responseStatus) } } catch _ as HandleMethodError { print("ServiceServer call to unknown method '\(unwrappedMethod)'") if !handler.completionQueue.hasBeenShutdown { // The method is not implemented by the service - send a status saying so. try handler.call.perform(OperationGroup( call: handler.call, operations: [ .sendInitialMetadata(Metadata()), .receiveCloseOnServer, .sendStatusFromServer(.unimplemented, "unknown method " + unwrappedMethod, Metadata()) ]) { _ in handler.shutdown() }) } } } catch { // The individual sessions' `run` methods (which are called by `self.handleMethod`) only throw errors if // they encountered an error that has not also been "seen" by the actual request handler implementation. // Therefore, this error is "really unexpected" and should be logged here - there's nowhere else to log it otherwise. print("ServiceServer unexpected error handling method '\(unwrappedMethod)': \(error)") do { if !handler.completionQueue.hasBeenShutdown { try handler.sendStatus((error as? ServerStatus) ?? .processingError) } } catch { print("ServiceServer unexpected error handling method '\(unwrappedMethod)'; sending status failed as well: \(error)") handler.shutdown() } } } } }
mit
cbf20e6b991b8e8f48433b1d9c912794
42.433071
141
0.6686
4.796522
false
false
false
false
DesenvolvimentoSwift/Taster
Taster/MapViewController.swift
1
2505
// // MapViewController.swift // pt.fca.Taster // // © 2016 Luis Marcelino e Catarina Silva // Desenvolvimento em Swift para iOS // FCA - Editora de Informática // import UIKit import MapKit class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var map: MKMapView! var food:Food? override func viewDidLoad() { map.delegate = self map.showsUserLocation = true } override func viewWillAppear(_ animated: Bool) { showFoodsOnMap() } func showFoodsOnMap () { //map.removeAnnotations(self.map.annotations) for f in FoodRepository.repository.foods { if let loc = f.location { map.setRegion(MKCoordinateRegionMake(loc, MKCoordinateSpanMake(1, 1)), animated: true) let pin = CustomPin(coordinate: loc, food:f, title: f.name, subtitle: " ") self.map.addAnnotation(pin) } } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let identifier = "identifier" var annotationView:MKPinAnnotationView? if annotation.isKind(of: CustomPin.self) { annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView if annotationView == nil { annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) annotationView!.canShowCallout = true annotationView!.pinTintColor = UIColor.purple let btn = UIButton(type: .detailDisclosure) annotationView!.rightCalloutAccessoryView = btn } else { annotationView!.annotation = annotation } return annotationView } return nil } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { let annotation = view.annotation as! CustomPin food = annotation.food self.performSegue(withIdentifier: "mapFoodDetail", sender: annotation) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let controller = segue.destination as? FoodDetailViewController { controller.food = food } } }
mit
4a93cecb259f9a1a38b803cc64f98c29
30.2875
129
0.606472
5.501099
false
false
false
false
zerovagner/iOS-Studies
RainyShinyCloudy/RainyShinyCloudy/Weather.swift
1
3031
// // Weather.swift // RainyShinyCloudy // // Created by Vagner Oliveira on 5/15/17. // Copyright © 2017 Vagner Oliveira. All rights reserved. // import Foundation import Alamofire import CoreLocation class Weather { private(set) var cityName: String! private(set) var currentWeather: String! private var currentDate: String! private(set) var currentTemperature: String! private(set) var maxTemperature: String! private(set) var minTemperature: String! static let baseUrl = "http://api.openweathermap.org/data/2.5/" static let params = [ "lat":"\(lat)", "lon":"\(lon)", "appid":"42a1771a0b787bf12e734ada0cfc80cb" ] private static var lat = 0.0 private static var lon = 0.0 static let forecastUrl = baseUrl + "forecast/daily" var date: String! { get { if currentDate == "" { let df = DateFormatter() df.dateStyle = .long df.timeStyle = .none currentDate = df.string(from: Date()) } return currentDate } } init() { cityName = "" currentWeather = "" currentDate = "" currentTemperature = "" minTemperature = "" maxTemperature = "" } init(obj: [String:Any]) { if let temp = obj["temp"] as? [String:Any] { if let min = temp["min"] as? Double { minTemperature = "\(round(10 * (min - 273))/10)º" } if let max = temp["max"] as? Double { maxTemperature = "\(round(10 * (max - 273))/10)º" } } if let weather = obj["weather"] as? [[String:Any]] { if let main = weather[0]["main"] as? String { currentWeather = main.capitalized } } if let date = obj["dt"] as? Double { let convertedDate = Date(timeIntervalSince1970: date) let dateFormatter = DateFormatter() dateFormatter.dateStyle = .full dateFormatter.dateFormat = "EEEE" dateFormatter.timeStyle = .none let dateIndex = Calendar.current.component(.weekday, from: convertedDate) currentDate = dateFormatter.weekdaySymbols[dateIndex-1] } } func setUp (fromJSON dict: [String:Any]) { if let name = dict["name"] as? String { cityName = name.capitalized print(cityName) } if let weather = dict["weather"] as? [[String:Any]] { if let curWeather = weather[0]["main"] as? String { currentWeather = curWeather.capitalized print(currentWeather) } } if let main = dict["main"] as? [String:Any] { if let temp = main["temp"] as? Double { currentTemperature = "\(round(10 * (temp - 273))/10)º" print(currentTemperature) } } } func downloadCurrentWeatherData (completed: @escaping DownloadComplete) { let currentWeatherUrl = Weather.baseUrl + "weather" Alamofire.request(currentWeatherUrl, parameters: Weather.params).responseJSON { response in let result = response.result if let dict = result.value as? [String:Any] { self.setUp(fromJSON: dict) } completed() } } static func setCoordinates(fromLocation location: CLLocation) { lat = round(100 * location.coordinate.latitude)/100 lon = round(100 * location.coordinate.longitude)/100 print("lat: \(lat) lon: \(lon)") } }
gpl-3.0
a12d806b6fb075be16184cf3a6ad456e
25.787611
93
0.665676
3.352159
false
false
false
false
the-grid/Palette-iOS
Palette/UIView+ColorAtPoint.swift
1
1917
//The MIT License (MIT) // //Copyright (c) 2015 Carlos Simón // //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 public extension UIView{ //returns the color data of the pixel at the currently selected point func getPixelColorAtPoint(point:CGPoint)->UIColor { let pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(4) var colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue) let context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, bitmapInfo) CGContextTranslateCTM(context, -point.x, -point.y) layer.renderInContext(context) var color:UIColor = UIColor(red: CGFloat(pixel[0])/255.0, green: CGFloat(pixel[1])/255.0, blue: CGFloat(pixel[2])/255.0, alpha: CGFloat(pixel[3])/255.0) pixel.dealloc(4) return color } }
mit
d77b93acd85e1fd33fa0712d91159f69
44.642857
160
0.735386
4.487119
false
false
false
false
sxchong/TimePods
TimePods/ViewController.swift
1
2879
// // ViewController.swift // TimePods // // Created by Sean Chong on 9/8/16. // Copyright © 2016 Sean Chong. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { //MARK: Properties @IBOutlet weak var tableView: UITableView! var timer = Timer() var date = NSDate() var testPod = Pod(name: "jump rope", duration: 10) let textCellIdentifier = "TimePodTableViewCell" override func viewDidLoad() { super.viewDidLoad() self.tableView.dataSource = self self.tableView.delegate = self //tableView.register(TimePodTableViewCell.self, forCellReuseIdentifier: "TimePodTableViewCell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* Method that is called every second. This method performs the logic of deducting time from the the active TimePod and all necessary logic associated with it. */ /* @IBAction func buttonStartPressed(sender: UIButton) { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTick), userInfo: nil, repeats: true) }*/ // MARK: Protocol required methods // MARK: UITableViewSource functions func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath) return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } // UITextField Delegates func textFieldDidBeginEditing(_ textField: UITextField) { print("TextField did begin editing method called") } func textFieldDidEndEditing(_ textField: UITextField) { print("TextField did end editing method called") } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { print("TextField should begin editing method called") return true; } func textFieldShouldClear(_ textField: UITextField) -> Bool { print("TextField should clear method called") return true; } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { print("TextField should snd editing method called") return true; } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { print("While entering the characters this method gets called") return true; } func textFieldShouldReturn(_ textField: UITextField) -> Bool { print("TextField should return method called") return true; } }
gpl-3.0
0e85c56400c6b729a13495142511e2d2
31.337079
130
0.6713
5.32963
false
false
false
false
redlock/SwiftyDeepstream
SwiftyDeepstream/Classes/deepstream/utils/Reflection/Construct.swift
3
2605
/// Create a struct with a constructor method. Return a value of `property.type` for each property. public func construct<T>(_ type: T.Type = T.self, constructor: (Property.Description) throws -> Any) throws -> T { if Metadata(type: T.self)?.kind == .struct { return try constructValueType(constructor) } else { throw ReflectionError.notStruct(type: T.self) } } /// Create a struct with a constructor method. Return a value of `property.type` for each property. public func construct(_ type: Any.Type, constructor: (Property.Description) throws -> Any) throws -> Any { return try extensions(of: type).construct(constructor: constructor) } private func constructValueType<T>(_ constructor: (Property.Description) throws -> Any) throws -> T { guard Metadata(type: T.self)?.kind == .struct else { throw ReflectionError.notStruct(type: T.self) } let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1) defer { pointer.deallocate(capacity: 1) } var values: [Any] = [] try constructType(storage: UnsafeMutableRawPointer(pointer), values: &values, properties: properties(T.self), constructor: constructor) return pointer.move() } private func constructType(storage: UnsafeMutableRawPointer, values: inout [Any], properties: [Property.Description], constructor: (Property.Description) throws -> Any) throws { var errors = [Error]() for property in properties { do { let value = try constructor(property) values.append(value) try property.write(value, to: storage) } catch { errors.append(error) } } if errors.count > 0 { throw ConstructionErrors(errors: errors) } } /// Create a struct from a dictionary. public func construct<T>(_ type: T.Type = T.self, dictionary: [String: Any]) throws -> T { return try construct(constructor: constructorForDictionary(dictionary)) } /// Create a struct from a dictionary. public func construct(_ type: Any.Type, dictionary: [String: Any]) throws -> Any { return try extensions(of: type).construct(dictionary: dictionary) } private func constructorForDictionary(_ dictionary: [String: Any]) -> (Property.Description) throws -> Any { return { property in if let value = dictionary[property.key] { return value } else if let expressibleByNilLiteral = property.type as? ExpressibleByNilLiteral.Type { return expressibleByNilLiteral.init(nilLiteral: ()) } else { throw ReflectionError.requiredValueMissing(key: property.key) } } }
mit
b9309a09c0b95d58d97ba8e4e53cf7cb
42.416667
177
0.682917
4.270492
false
false
false
false
NijiDigital/NetworkStack
Example/MoyaComparison/MoyaComparison/Utils/MCLogger.swift
1
1064
// // Copyright 2017 niji // // 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 SwiftyBeaver struct MCLogger { static func setup() { let console = ConsoleDestination() console.format = "$D[HH:mm:ss]$d $L - $N.$F:$l > $M" console.levelString.verbose = "📔 -- VERBOSE" console.levelString.debug = "📗 -- DEBUG" console.levelString.info = "📘 -- INFO" console.levelString.warning = "📙 -- WARNING" console.levelString.error = "📕 -- ERROR" SwiftyBeaver.addDestination(console) } }
apache-2.0
7c30693c8236f826690d14a5e2ad7c51
30.787879
75
0.694948
3.885185
false
false
false
false
modocache/Gift
Gift/Signature/Signature.swift
1
1040
import Foundation /** A signature represents information about the creator of an object. For example, tags and commits have signatures that contain information about who created the tag or commit, and when they did so. */ public struct Signature { /** The name of the person associated with this signature. */ public let name: String /** The email of the person associated with this signature. */ public let email: String /** The date this signature was made. */ public let date: NSDate /** The time zone in which this signature was made. */ public let timeZone: NSTimeZone public init(name: String, email: String, date: NSDate = NSDate(timeIntervalSinceNow: 0), timeZone: NSTimeZone = NSTimeZone.defaultTimeZone()) { self.name = name self.email = email self.date = date self.timeZone = timeZone } } /** A signature used by Gift when updating the reflog and the user has not provided a signature of their own. */ internal let giftSignature = Signature(name: "com.libgit2.Gift", email: "")
mit
266efe1a1d3ca025fb6e86620fff9ba5
32.548387
145
0.720192
4.40678
false
false
false
false
stephentyrone/swift
stdlib/public/core/StringInterpolation.swift
1
10047
//===--- StringInterpolation.swift - String Interpolation -----------------===// // // 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 // //===----------------------------------------------------------------------===// /// Represents a string literal with interpolations while it is being built up. /// /// Do not create an instance of this type directly. It is used by the compiler /// when you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." /// /// When implementing an `ExpressibleByStringInterpolation` conformance, /// set the `StringInterpolation` associated type to /// `DefaultStringInterpolation` to get the same interpolation behavior as /// Swift's built-in `String` type and construct a `String` with the results. /// If you don't want the default behavior or don't want to construct a /// `String`, use a custom type conforming to `StringInterpolationProtocol` /// instead. /// /// Extending default string interpolation behavior /// =============================================== /// /// Code outside the standard library can extend string interpolation on /// `String` and many other common types by extending /// `DefaultStringInterpolation` and adding an `appendInterpolation(...)` /// method. For example: /// /// extension DefaultStringInterpolation { /// fileprivate mutating func appendInterpolation( /// escaped value: String, asASCII forceASCII: Bool = false) { /// for char in value.unicodeScalars { /// appendInterpolation(char.escaped(asASCII: forceASCII)) /// } /// } /// } /// /// print("Escaped string: \(escaped: string)") /// /// See `StringInterpolationProtocol` for details on `appendInterpolation` /// methods. /// /// `DefaultStringInterpolation` extensions should add only `mutating` members /// and should not copy `self` or capture it in an escaping closure. @frozen public struct DefaultStringInterpolation: StringInterpolationProtocol { /// The string contents accumulated by this instance. @usableFromInline internal var _storage: String /// Creates a string interpolation with storage pre-sized for a literal /// with the indicated attributes. /// /// Do not call this initializer directly. It is used by the compiler when /// interpreting string interpolations. @inlinable public init(literalCapacity: Int, interpolationCount: Int) { let capacityPerInterpolation = 2 let initialCapacity = literalCapacity + interpolationCount * capacityPerInterpolation _storage = String(_StringGuts(_initialCapacity: initialCapacity)) } /// Appends a literal segment of a string interpolation. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. @inlinable public mutating func appendLiteral(_ literal: String) { literal.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: TextOutputStreamable, T: CustomStringConvertible { value.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = "If one cookie costs \(price) dollars, " + /// "\(number) cookies cost \(price * number) dollars." /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: TextOutputStreamable { value.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: CustomStringConvertible { value.description.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) { _print_unlocked(value, &self) } @_alwaysEmitIntoClient public mutating func appendInterpolation(_ value: Any.Type) { _typeName(value, qualified: false).write(to: &self) } /// Creates a string from this instance, consuming the instance in the /// process. @inlinable internal __consuming func make() -> String { return _storage } } extension DefaultStringInterpolation: CustomStringConvertible { @inlinable public var description: String { return _storage } } extension DefaultStringInterpolation: TextOutputStream { @inlinable public mutating func write(_ string: String) { _storage.append(string) } public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) { _storage._guts.append(_StringGuts(buffer, isASCII: true)) } } // While not strictly necessary, declaring these is faster than using the // default implementation. extension String { /// Creates a new instance from an interpolated string literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable @_effects(readonly) public init(stringInterpolation: DefaultStringInterpolation) { self = stringInterpolation.make() } } extension Substring { /// Creates a new instance from an interpolated string literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable @_effects(readonly) public init(stringInterpolation: DefaultStringInterpolation) { self.init(stringInterpolation.make()) } }
apache-2.0
7c2e838277296f23ecda273cf20eded1
37.494253
80
0.638499
4.853623
false
false
false
false
conferencesapp/rubyconferences-ios
Reachability.swift
1
942
// // Reachability.swift // // // Created by Rashmi Yadav on 5/16/15. // // import Foundation import SystemConfiguration public class Reachability { public func connectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { return false } var flags : SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = flags.contains(.Reachable) let needsConnection = flags.contains(.ConnectionRequired) return (isReachable && !needsConnection) } }
mit
2071437ae8156496c34bc6d4dc4872cb
26.705882
78
0.631635
5.233333
false
false
false
false
1000copy/fin
View/LogoutTableViewCell.swift
2
1154
// // LogoutTableViewCell.swift // V2ex-Swift // // Created by huangfeng on 2/12/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit class LogoutTableViewCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier); self.setup(); } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup()->Void{ self.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor self.textLabel!.text = NSLocalizedString("logOut") self.textLabel!.textAlignment = .center self.textLabel!.textColor = V2EXColor.colors.v2_NoticePointColor let separator = UIImageView(image: createImageWithColor(V2EXColor.colors.v2_SeparatorColor)) self.contentView.addSubview(separator) separator.snp.makeConstraints{ (make) -> Void in make.left.equalTo(self.contentView) make.right.bottom.equalTo(self.contentView) make.height.equalTo(SEPARATOR_HEIGHT) } } }
mit
9e78b9ca519eb61bee5dd64489693e51
31.942857
100
0.674761
4.400763
false
false
false
false
alreadyRight/Swift-algorithm
私人通讯录/私人通讯录/DetailViewController.swift
1
3898
// // DetailViewController.swift // 私人通讯录 // // Created by 周冰烽 on 2017/12/9. // Copyright © 2017年 周冰烽. All rights reserved. // import UIKit class DetailViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var status: Int = 0 private let detailCellID = "detailCellID" var name: String? var phone: String? var address: String? override func viewDidLoad() { super.viewDidLoad() if status == 0 { title = "添加联系人" }else{ title = "编辑联系人" } view.backgroundColor = UIColor.white navigationItem.rightBarButtonItem = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(clickFinish)) setupTableView() } func setupTableView() -> Void { let tableView = UITableView(frame: CGRect(x: 0, y: 64, width: view.frame.size.width, height: view.frame.size.height - 64), style: .plain) tableView.delegate = self tableView.dataSource = self tableView.estimatedRowHeight = 0 tableView.estimatedSectionHeaderHeight = 0 tableView.estimatedSectionFooterHeight = 0 tableView.register(DetailTableViewCell.classForCoder(), forCellReuseIdentifier: detailCellID) view.addSubview(tableView) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: DetailTableViewCell = tableView.dequeueReusableCell(withIdentifier: detailCellID, for: indexPath) as! DetailTableViewCell switch indexPath.row { case 0: // cell.setNormalValue(titleText: "姓名", placeholder: "请填写姓名", dataText: name ?? "") cell.title = "姓名" cell.placeholder = "请填写姓名" cell.dataText = name ?? "" cell.changeText { [weak self](text) in self?.name = text } case 1: cell.title = "电话号码" cell.placeholder = "请填写电话号码" cell.dataText = phone ?? "" cell.changeText { [weak self](text) in self?.phone = text } default: cell.title = "地址" cell.placeholder = "请填写地址" cell.dataText = address ?? "" cell.changeText { [weak self](text) in self?.address = text } } return cell } @objc func clickFinish() -> Void { guard let name = name, let phone = phone, let address = address else { return } let dict = ["name":name,"phone":phone,"address":address] let ud = UserDefaults.standard var arr: Array<[String : String]> = ud.object(forKey: "addressBook") as? Array<[String:String]> ?? [] if arr.count == 0 { arr = Array<[String:String]>() } for i in 0 ..< arr.count { if dict["name"] == arr[i]["name"] { arr.remove(at: i) break }else if dict["phone"] == arr[i]["phone"]{ arr.remove(at: i) break }else if dict["address"] == arr[i]["address"]{ arr.remove(at: i) break } } arr.append(dict) ud.set(arr, forKey: "addressBook") navigationController?.popViewController(animated: true) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.becomeFirstResponder() } }
mit
b4b675a139c4ec420425116065875cb8
32.794643
145
0.560898
4.649877
false
false
false
false
larryhou/swift
CrashReport/CrashReport/ViewController.swift
1
2538
// // ViewController.swift // CrashReport // // Created by larryhou on 8/4/16. // Copyright © 2016 larryhou. All rights reserved. // import Foundation import UIKit import GameplayKit class ViewController: UIViewController { var method: TestMethod = .none var bartitle: String = "" override func viewDidLoad() { navigationItem.title = bartitle switch method { case .null: Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) {_ in let rect: CGRect? = nil print(rect!.width) } break case .memory: var list: [[UInt8]] = [] Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) {_ in let bytes = [UInt8](repeating: 10, count: 1024*1024) list.append(bytes) } break case .cpu: Timer.scheduledTimer(withTimeInterval: 0.0, repeats: false) {_ in self.ruineCPU() } break case .abort: Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) {_ in abort() } break case .none: break } } func ruineCPU() { let width: Int32 = 110, height: Int32 = 110 let graph = GKGridGraph(fromGridStartingAt: int2(0, 0), width: width, height: height, diagonalsAllowed: false) var obstacles: [GKGridGraphNode] = [] let random = GKRandomSource.sharedRandom() for x in 0..<width { for y in 0..<height { let densitiy = 5 if random.nextInt(upperBound: densitiy) % densitiy == 1 { let node = graph.node(atGridPosition: int2(x, y)) obstacles.append(node!) } } } graph.remove(obstacles) func get_random_node() -> GKGraphNode { let nodes = graph.nodes! return nodes[random.nextInt(upperBound: nodes.count)] } while true { let queue = DispatchQueue(label: Date().description, qos: DispatchQoS.default, attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.never, target: nil) queue.async { graph.findPath(from: get_random_node(), to: get_random_node()) } } } }
mit
f3c383de263c18c3804350579f05484a
29.202381
216
0.521876
4.655046
false
false
false
false
rodrigobell/twitter-clone
twitter-clone/AppDelegate.swift
1
3367
// // AppDelegate.swift // twitter-clone // // Created by Rodrigo Bell on 2/17/17. // Copyright © 2017 Rodrigo Bell. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let storyboard = UIStoryboard(name: "Main", bundle: nil) func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. if User.currentUser != nil { // Go to the logged in screen print("Current user exists: \((User.currentUser?.name)!)") let tweetsVC = storyboard.instantiateViewController(withIdentifier: "MainNavController") window?.rootViewController = tweetsVC } else { print("No current user") } NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: User.userDidLogoutNotification), object: nil, queue: OperationQueue.main, using: { (NSNotification) -> Void in let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateInitialViewController() self.window?.rootViewController = vc }) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active 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:. } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { // Called when twitter-clone switches from Safari back to twitter-clone. TwitterClient.sharedInstance.handleOpenUrl(url: url) return true } }
mit
5a7f0990e6eb306cb240b3953cdbab58
45.75
285
0.704397
5.666667
false
false
false
false
SHSRobotics/Estimote
Examples/nearables/TemperatureExample-Swift/TemperatureExample-Swift/MasterViewController.swift
1
2049
// // MasterViewController.swift // TemperatureExample-Swift // // Created by Grzegorz Krukiewicz-Gacek on 24.12.2014. // Copyright (c) 2014 Estimote Inc. All rights reserved. // import UIKit class MasterViewController: UITableViewController, ESTNearableManagerDelegate { var nearables:Array<ESTNearable>! var nearableManager:ESTNearableManager! override func viewDidLoad() { super.viewDidLoad() nearables = [] nearableManager = ESTNearableManager() nearableManager.delegate = self nearableManager .startRangingForType(ESTNearableType.All) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let selectedNearable = nearables[indexPath.row] as ESTNearable (segue.destinationViewController as DetailViewController).nearable = selectedNearable } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return nearables.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell let nearable = nearables[indexPath.row] as ESTNearable cell.textLabel!.text = nearable.nameForType(nearable.type) cell.detailTextLabel!.text = nearable.identifier return cell } // MARK: - ESTNearableManager delegate func nearableManager(manager: ESTNearableManager!, didRangeNearables nearables: [AnyObject]!, withType type: ESTNearableType) { self.nearables = nearables as Array<ESTNearable> tableView.reloadData() } }
mit
1575c9b17e4929cef6572ff2da32951c
31.52381
131
0.694485
5.322078
false
false
false
false
RamonGilabert/RamonGilabert
RamonGilabert/RamonGilabert/RGWebViewController.swift
1
2119
import UIKit class RGWebViewController: UIViewController, UIWebViewDelegate { let viewModel = ViewModel() let transitionManager = CustomVideoTransition() var webView = UIWebView() var loadURL = ContactWebs.Website! var backButton = UIButton() var forwardButton = UIButton() // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() self.transitioningDelegate = self.transitionManager let headerView = UIView(frame: CGRectMake(0, 0, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight/9)) headerView.backgroundColor = UIColor_WWDC.almostBlackColor() self.viewModel.setCrossButtonWebView(headerView, viewController: self) self.backButton = self.viewModel.setBackButton(headerView, viewController: self) self.forwardButton = self.viewModel.setForwardButton(headerView, viewController: self) self.webView = self.viewModel.setWebView(self.view, webViewDelegate: self) self.view.addSubview(headerView) let requestURL = NSURLRequest(URL: self.loadURL) self.webView.loadRequest(requestURL) } // MARK: WebView delegate methods func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { self.backButton.enabled = self.webView.canGoBack ? true : false self.forwardButton.enabled = self.webView.canGoForward ? true : false return true } func webViewDidFinishLoad(webView: UIWebView) { self.backButton.enabled = self.webView.canGoBack ? true : false self.forwardButton.enabled = self.webView.canGoForward ? true : false } // MARK: Button handlers func onCloseButtonPressed() { self.dismissViewControllerAnimated(true, completion: nil) } func onBackButtonPressed(sender: UIButton) { if self.webView.canGoBack { self.webView.goBack() } } func onForwardButtonPressed(sender: UIButton) { if self.webView.canGoForward { self.webView.goForward() } } }
mit
309e30e7d24bd560b5f2a2a2524db0cb
32.109375
137
0.697499
5.057279
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Playlist/PlaylistDetailViewController.swift
1
9821
// // PlaylistDetailViewController.swift // MusicApp // // Created by Hưng Đỗ on 6/18/17. // Copyright © 2017 HungDo. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources import Action import NSObject_Rx class PlaylistDetailViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var headerView: PlaylistDetailHeaderView! @IBOutlet weak var playButton: UIButton! fileprivate let headerCell = UITableViewCell(style: .default, reuseIdentifier: "HeaderCell") fileprivate var initialIndicatorView = DetailInitialActivityIndicatorView() fileprivate var loadingIndicatorView = LoadingActivityIndicatorView() var store: PlaylistDetailStore! var action: PlaylistDetailAction! // MARK: Properties var playlist: Playlist { get { return store.info.value } set { store.info.value = newValue } } var playlistDetailInfoInput: PlaylistDetailInfo? // MARK: Output Properties lazy var playlistDetailInfoOutput: Observable<PlaylistDetailInfo> = { return self.playlistDetailInfoSubject.asObservable() }() fileprivate var playlistDetailInfoSubject = PublishSubject<PlaylistDetailInfo>() // MARK: Target Actions @IBAction func backButonTapped(_ backButton: UIButton) { navigationController?.popViewController(animated: true) } // MARK: Life Cycles override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = [] tableView.delegate = self headerView.configureAnimation(with: tableView) bindStore() bindAction() } private var headerViewNeedsToUpdate = true override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() if headerViewNeedsToUpdate { headerView.frame.size.height = tableView.bounds.size.height / 3 headerViewNeedsToUpdate = false } } // MARK: Data Source fileprivate let HeaderRow = 0 fileprivate let MenuRow = 1 fileprivate lazy var dataSource: RxTableViewSectionedReloadDataSource<PlaylistDetailItemSection> = { let dataSource = RxTableViewSectionedReloadDataSource<PlaylistDetailItemSection>() dataSource.configureCell = { dataSource, tableView, indexPath, detailItem in if indexPath.row == self.HeaderRow { return self.headerCell } if indexPath.row == self.MenuRow { let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: PlaylistMenuCell.self), for: indexPath) if let cell = cell as? PlaylistMenuCell { cell.state = self.store.state.value cell.action = self.action.onPlaylistDetailStateChange() } return cell } switch detailItem { case let .song(song): let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: SongCell.self), for: indexPath) if let songCell = cell as? SongCell { let contextAction = CocoaAction { [weak self] _ in guard let this = self else { return .empty() } return this.action.onContextMenuOpen.execute((song, this)).map { _ in } } songCell.configure(name: song.name, singer: song.singer, contextAction: contextAction) } return cell case let .playlist(playlist): let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: PlaylistDetailCell.self), for: indexPath) if let playlistCell = cell as? PlaylistDetailCell { playlistCell.configure(name: playlist.name, singer: playlist.singer, image: playlist.avatar) } return cell } } return dataSource }() } // MARK: UITableViewDelegate extension PlaylistDetailViewController: UITableViewDelegate { private var headerHeight: CGFloat { return tableView.bounds.height / 3 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == self.HeaderRow { return headerHeight } if indexPath.row == self.MenuRow { return 44 } if self.store.state.value == .song { return 44 } else { return 60 } } } // MARK: Activity Indicator extension PlaylistDetailViewController { func beginInitialLoading() { initialIndicatorView.startAnimating(in: self.view) } func endInitialLoading() { initialIndicatorView.stopAnimating() } func beginLoading() { loadingIndicatorView.startAnimation(in: self.view) } func endLoading() { loadingIndicatorView.stopAnimation() } } // MARK: Store extension PlaylistDetailViewController { func bindStore() { store.info.asObservable() .subscribe(onNext: { [weak self] playlist in self?.headerView.setImage(playlist.avatar) self?.headerView.setPlaylist(playlist.name) self?.headerView.setSinger(playlist.singer) }) .addDisposableTo(rx_disposeBag) let state = store.state.asObservable() .filter { [weak self] _ in self != nil } .shareReplay(1) state .subscribe(onNext: { [weak self] state in let indexPath = IndexPath(row: 1, section: 0) let cell = self?.tableView.cellForRow(at: indexPath) as? PlaylistMenuCell cell?.state = state }) .addDisposableTo(rx_disposeBag) bindDataSource(state: state) store.loading.asObservable() .skip(1) .subscribe(onNext: { [weak self] loading in if loading { self?.beginLoading() } else { self?.endLoading() } }) .addDisposableTo(rx_disposeBag) } private func bindDataSource(state: Observable<PlaylistDetailState>) { let fakeSong = Song(id: "", name: "", singer: "") let fakeSongs = [fakeSong, fakeSong] let song = state .filter { $0 == .song } .map { [weak self] _ in fakeSongs + self!.store.songs.value } .shareReplay(1) let fakePlaylist = Playlist(id: "", name: "'", singer: "", avatar: "") let fakePlaylists = [fakePlaylist, fakePlaylist] let playlist = state .filter { $0 == .playlist } .map { [weak self] _ in fakePlaylists + self!.store.playlists.value } .shareReplay(1) let songDataSource = song .map { songs in songs.map { PlaylistDetailItem.song($0) } } .map { [SectionModel(model: "Song", items: $0)] } let playlistDataSource = playlist .map { playlists in playlists.map { PlaylistDetailItem.playlist($0) } } .map { [SectionModel(model: "Playlist", items: $0)] } Observable.from([songDataSource, playlistDataSource]) .merge() .bind(to: tableView.rx.items(dataSource: dataSource)) .addDisposableTo(rx_disposeBag) song .map { song in song.count } .filter { count in count == 2 } .take(1) .subscribe(onNext: { [weak self] _ in self?.beginInitialLoading() }) .addDisposableTo(rx_disposeBag) song .map { song in song.count } .filter { count in count > 2 } .take(1) .subscribe(onNext: { [weak self] _ in self?.endInitialLoading() }) .addDisposableTo(rx_disposeBag) } } // MARK: Action extension PlaylistDetailViewController { func bindAction() { if let detailInfo = playlistDetailInfoInput { store.tracks.value = detailInfo.tracks store.songs.value = detailInfo.songs store.playlists.value = detailInfo.playlists store.state.value = .song } else { action.onLoad.execute(()) .subscribe(playlistDetailInfoSubject) .addDisposableTo(rx_disposeBag) } let detailItem = tableView.rx.modelSelected(PlaylistDetailItem.self) .shareReplay(1) detailItem .map { item -> Playlist? in switch item { case .song(_): return nil case let .playlist(playlist): return playlist } } .filter { $0 != nil } .map { $0! } .filter { playlist in !playlist.id.isEmpty } .subscribe(action.onPlaylistDidSelect.inputs) .addDisposableTo(rx_disposeBag) detailItem .map { item -> Song? in switch item { case let .song(song): return song case .playlist(_): return nil } } .filter { $0 != nil } .map { $0! } .filter { song in !song.id.isEmpty } .subscribe(action.onSongDidSelect.inputs) .addDisposableTo(rx_disposeBag) playButton.rx.action = action.onPlayButtonPress() } }
mit
1f0022060e9c170d914c06f57dab9257
31.183607
133
0.57009
5.166316
false
false
false
false
codergaolf/DouYuTV
DouYuTV/DouYuTV/Classes/Main/View/PageTitleView.swift
1
6482
// // PageTitleView.swift // DouYuTV // // Created by 高立发 on 2016/11/12. // Copyright © 2016年 GG. All rights reserved. // import UIKit // MARK:- 定义协议 protocol PageTitleViewDelegate : class { func pageTitleView(titleView : PageTitleView, selected index : Int) } // MARK:- 定义常量 private let kScrollLineH : CGFloat = 2 private let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85, 85, 85) private let kSelectColor : (CGFloat,CGFloat,CGFloat) = (255, 128, 0) // MARK:- 定义PageTitleView类 class PageTitleView: UIView { // MARK:- 定义属性 fileprivate var currentIndex : Int = 0 fileprivate var titles : [String] weak var delegate : PageTitleViewDelegate? // MARK:- 懒加载属性 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() fileprivate lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() // MARK:- 自定义构造函数 init(frame: CGRect, titles : [String]) { self.titles = titles super.init(frame: frame) //设置UI界面 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI extension PageTitleView { fileprivate func setupUI() { //1,添加UIScrollView addSubview(scrollView) scrollView.frame = bounds //2,添加Title对应的label setTitleLabels() //3,设置底线和滚动的滑块 setupBottomMenuAndScrollLine() } fileprivate func setTitleLabels() { for (index, title) in titles.enumerated() { //0,确定label的一些frame值 let labelW : CGFloat = frame.width / CGFloat(titles.count) let labelH : CGFloat = frame.height - kScrollLineH let labelY : CGFloat = 0 //1,创建UILabel let label = UILabel() //2,设置label的属性 label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16.0) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .center //3,设置label的frame let labelX : CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) //4,将label添加到scrollView中 scrollView.addSubview(label) titleLabels.append(label) //5,给label添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:))) label.addGestureRecognizer(tapGes) } } fileprivate func setupBottomMenuAndScrollLine() { //1,添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) //2,添加scrollLine //2.1获取第一个label guard let firstLabel = titleLabels.first else { return } firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) //2.2设置scrollLine的属性 scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH) } } // MARK:- 监听label的点击 extension PageTitleView { @objc fileprivate func titleLabelClick(tapGes : UITapGestureRecognizer) { //0,获取当前label guard let currentLabel = tapGes.view as? UILabel else { return } //1,如果是重复点击同一个title,直接返回 if currentLabel.tag == currentIndex { return } //2,获取之前的label let oldLabel = titleLabels[currentIndex] //3,切换文字的颜色 currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) //4,保存最新label的下标值 currentIndex = currentLabel.tag //5,滚动条位置发生该表 let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width UIView.animate(withDuration: 0.15, animations: { self.scrollLine.frame.origin.x = scrollLineX }) //6,通知代理 delegate?.pageTitleView(titleView: self, selected: currentIndex) } } // MARK:- 对外暴露的方法 extension PageTitleView { func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int) { //1,取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] //2,处理滑块的逻辑 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX //3,处理颜色的渐变 //3.1取出变化的范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) //3.2变化sourceLabel sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress) //3.2变化targetLabel targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) //4,记录最新的index currentIndex = targetIndex } }
mit
21ef9dd0a687c7cccbf4f7f8dd99e5c8
31.790323
174
0.612395
4.69515
false
false
false
false
domenicosolazzo/practice-swift
BackgroundProcessing/SlowWorker/SlowWorker/ViewController.swift
1
2847
// // ViewController.swift // SlowWorker // // Created by Domenico on 29/04/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var startButton: UIButton! @IBOutlet weak var resultsTextView: UITextView! @IBOutlet weak var spinner: UIActivityIndicatorView! 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. } func fetchSomethingFromServer() -> String { NSThread.sleepForTimeInterval(1) return "Hi there" } func processData(data: String) -> String { NSThread.sleepForTimeInterval(2) return data.uppercaseString } func calculateFirstResult(data: String) -> String { NSThread.sleepForTimeInterval(3) return "Number of chars: \(data.characters.count)" } func calculateSecondResult(data: String) -> String { NSThread.sleepForTimeInterval(4) return data.stringByReplacingOccurrencesOfString("E", withString: "e") } @IBAction func doWork(sender: AnyObject) { let startTime = NSDate() self.resultsTextView.text = "" startButton.enabled = false spinner.startAnimating() let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_async(queue){ let fetchedData = self.fetchSomethingFromServer() let processedData = self.processData(fetchedData) var firstResult: String! var secondResult: String! let group = dispatch_group_create() dispatch_group_async(group, queue) { firstResult = self.calculateFirstResult(processedData) } dispatch_group_async(group, queue) { secondResult = self.calculateSecondResult(processedData) } dispatch_group_notify(group, queue){ let resultsSummary = "First: [\(firstResult)]\nSecond: [\(secondResult)]" dispatch_async(dispatch_get_main_queue()){ // Dispatch the result to the main queue self.resultsTextView.text = resultsSummary self.spinner.stopAnimating() self.startButton.enabled = false } let endTime = NSDate() print( "Completed in \(endTime.timeIntervalSinceDate(startTime)) seconds") } } } }
mit
dd4b79dfd3c5303b14a16017afa2290e
30.285714
87
0.583421
5.321495
false
false
false
false
vincentherrmann/multilinear-math
Sources/WaveletPlots.swift
1
3943
// // WaveletPlots.swift // MultilinearMath // // Created by Vincent Herrmann on 07.11.16. // Copyright © 2016 Vincent Herrmann. All rights reserved. // import Cocoa public struct FastWaveletPlot: CustomPlaygroundQuickLookable { public var waveletView: WaveletView public var customPlaygroundQuickLook: PlaygroundQuickLook { get { return PlaygroundQuickLook.view(waveletView) } } public init(packets: [WaveletPacket]) { waveletView = WaveletView(frame: NSRect(x: 0, y: 0, width: 300, height: 200)) var bounds: CGRect? = nil for i in 0..<packets.count { let thisPacket = packets[i] let plot = WaveletPacketPlot(packet: thisPacket) waveletView.addPlottable(plot) if bounds == nil { bounds = plot.plotBounds } else { bounds = bounds!.join(with: plot.plotBounds) } } waveletView.setPlottingBounds(bounds!) waveletView.updatePlotting() } } public class WaveletView: PlotView2D { override public var screenBounds: CGRect { get { return CGRect(origin: CGPoint(x: 0, y: 0), size: frame.size) } } var maxValue: CGFloat = CGFloat.leastNormalMagnitude public override init(frame frameRect: NSRect) { super.init(frame: frameRect) plottingBounds = NSRect(x: 0, y: 0, width: 32, height: 1) } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) for thisPlot in plots { thisPlot.draw() } } public func updatePlotting() { maxValue = CGFloat.leastNormalMagnitude for thisPlot in plots { if let w = thisPlot as? WaveletPacketPlot { if let m = w.packet.values.max() { if CGFloat(m) > maxValue {maxValue = CGFloat(m)} } } } super.updatePlotting() } } public class WaveletPacketPlot: PlottableIn2D { public var packet: WaveletPacket var tiles: [CGRect] = [] var maxValue: CGFloat = 1 public var plotBounds: CGRect { get { let yMinP = CGFloat(packet.position) / CGFloat(packet.length) let height = 1 / CGFloat(packet.length) let width = CGFloat(packet.length * packet.values.count) let bounds = CGRect(x: 0, y: yMinP, width: width, height: height) return bounds } } public init(packet: WaveletPacket) { self.packet = packet } public func draw() { for i in 0..<packet.values.count { if let color = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).blended(withFraction: CGFloat(packet.values[i]) / maxValue, of: #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)) { color.setFill() } else { #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).setFill() } let path = NSBezierPath(rect: tiles[i]) path.fill() } } public func fitTo(_ plotting: Plotting2D) { let t = plotting.transformFromPlotToScreen let yMin = (plotBounds.minY + t.translateY) * t.scaleY let height = plotBounds.height * t.scaleY let xStart = t.translateX * t.scaleX let width = CGFloat(packet.length) * t.scaleX var p = xStart tiles = [] for _ in 0..<packet.values.count { tiles.append(CGRect(x: p, y: yMin, width: width, height: height)) p += width } if let view = plotting as? WaveletView { maxValue = view.maxValue } else { maxValue = 1 } } }
apache-2.0
4017ee6e0f32f8faa761cc0462162083
29.091603
195
0.558092
4.220557
false
false
false
false
eladb/nodeswift
nodeswift-sample/events.swift
1
3240
// // events.swift // nodeswift-sample // // Created by Elad Ben-Israel on 7/28/15. // Copyright © 2015 Citylifeapps Inc. All rights reserved. // import Foundation class EventHandler: Hashable, Equatable { // allocate 1-byte and use it's hashValue (address) as the hashValue of the EventHandler let ptr = UnsafeMutablePointer<Int8>.alloc(1) var hashValue: Int { return ptr.hashValue } deinit { self.ptr.dealloc(1) } var callback: (([AnyObject]) -> ())? init(_ callback: (([AnyObject]) -> ())?) { self.callback = callback } } func ==(lhs: EventHandler, rhs: EventHandler) -> Bool { return lhs.hashValue == rhs.hashValue } class EventEmitter { private var handlers = Set<EventHandler>(); func emit(args: [AnyObject]) -> Int { var calls = 0 for handler in self.handlers { if let callback = handler.callback { callback(args) calls++ } } return calls } func addListener(listener: (([AnyObject]) -> ())?) -> EventHandler { let handler = EventHandler(listener) self.handlers.insert(handler) return handler } func removeListener(handler: EventHandler) { self.handlers.remove(handler) } func once(listener: ([AnyObject]) -> ()) -> EventHandler { let handler = self.addListener(nil) handler.callback = { args in listener(args) self.removeListener(handler) } return handler } func on(listener: ([AnyObject]) -> ()) -> EventHandler { return self.addListener(listener) } } class EventEmitter2<A: AnyObject, B: AnyObject> { private let emitter = EventEmitter() func emit(a: A, b: B) -> Int { return self.emitter.emit([ a, b ]) } func on(callback: (A, B) -> ()) -> EventHandler { return self.emitter.on { args in callback(args[0] as! A, args[1] as! B) } } func once(callback: (A, B) -> ()) -> EventHandler { return self.emitter.once { args in callback(args[0] as! A, args[1] as! B) } } func removeListener(handler: EventHandler) { self.emitter.removeListener(handler) } } class EventEmitter1<A: AnyObject> { private let emitter = EventEmitter() func emit(a: A) -> Int { return self.emitter.emit([a]) } func on(callback: (A) -> ()) -> EventHandler { return self.emitter.on { args in callback(args[0] as! A) } } func once(callback: (A) -> ()) -> EventHandler { return self.emitter.once { args in callback(args[0] as! A) } } func removeListener(handler: EventHandler) { self.emitter.removeListener(handler) } } class EventEmitter0 { private let emitter = EventEmitter() func emit() -> Int { return self.emitter.emit([]) } func on(callback: () -> ()) -> EventHandler { return self.emitter.on { _ in callback() } } func once(callback: () -> ()) -> EventHandler { return self.emitter.once { _ in callback() } } func removeListener(handler: EventHandler) { self.emitter.removeListener(handler) } } class ErrorEventEmitter: EventEmitter1<Error> { override func emit(error: Error) -> Int { let calls = super.emit(error) assert(calls > 0, "Unhandled 'error' event: \(error)") return calls } }
apache-2.0
93ab4a2e03969381fd2469458f59514f
35.404494
133
0.619944
3.959658
false
false
false
false
hhyyg/Miso.Gistan
Gistan/AppDelegate.swift
1
2496
// // AppDelegate.swift // Gistan // // Created by Hiroka Yago on 2017/09/30. // Copyright © 2017 miso. All rights reserved. // import UIKit import OAuthSwift import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil { // when test do nothing return true } FirebaseApp.configure() try! loadSettings() return true } func loadSettings() throws { //load settings.plist let settingURL: URL = URL(fileURLWithPath: Bundle.main.path(forResource: "settings", ofType: "plist")!) let data = try Data(contentsOf: settingURL) let decoder = PropertyListDecoder() SettingsContainer.settings = try decoder.decode(Settings.self, from: data) } func applicationWillResignActive(_ application: UIApplication) { // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // 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 active 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:. } } extension AppDelegate { func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { if (url.host == "oauth-callback") { OAuthSwift.handle(url: url) } return true } }
mit
83aa4d9567910e769d6ef22e109c5b0a
34.140845
194
0.696593
5.331197
false
false
false
false
onekiloparsec/SwiftAA
Sources/SwiftAA/Angles.swift
2
6794
// // Angles.swift // SwiftAA // // Created by Cédric Foellmi on 17/12/2016. // MIT Licence. See LICENCE file. // import Foundation import ObjCAA /// The Degree is a unit of angle. public struct Degree: NumericType, CustomStringConvertible { /// The Degree value public let value: Double /// Returns a new Degree object. /// /// - Parameter value: The value of Degree. public init(_ value: Double) { self.value = value } /// Creates a new Degree instance, from sexagesimal components. /// /// - Parameters: /// - sign: The sign of the final value. /// - degrees: The integral degree component of the value. Sign is ignored. /// - arcminutes: The integral arcminute component of the value. Sign is ignored. /// - arcseconds: The fractional arcsecond component of the value. Sign is ignored. public init(_ sign: FloatingPointSign = .plus, _ degrees: Int, _ arcminutes: Int, _ arcseconds: Double) { let absDegree = abs(Double(degrees)) let absMinutes = abs(Double(arcminutes))/60.0 let absSeconds = abs(arcseconds)/3600.0 self.init(Double(sign) * (absDegree + absMinutes + absSeconds)) } /// Transform the current Degree in ArcMinutes public var inArcMinutes: ArcMinute { return ArcMinute(value * 60.0) } /// Transform the current Degree in ArcSeconds public var inArcSeconds: ArcSecond { return ArcSecond(value * 3600.0) } /// Transform the current Degree in Radians public var inRadians: Radian { return Radian(value * deg2rad) } /// Transform the current Degree in Hours public var inHours: Hour { return Hour(value / 15.0) } /// The sexagesimal notation of the Degree. public var sexagesimal: SexagesimalNotation { get { let deg = abs(value.rounded(.towardZero)) let min = ((abs(value) - deg) * 60.0).rounded(.towardZero) let sec = ((abs(value) - deg) * 60.0 - min) * 60.0 return (value > 0.0 ? .plus : .minus, Int(deg), Int(min), Double(sec)) } } /// Returns `self` reduced to 0..<360 range public var reduced: Degree { return Degree(value.positiveTruncatingRemainder(dividingBy: 360.0)) } /// Returns `self` reduced to -180..<180 range (around 0) public var reduced0: Degree { return Degree(value.zeroCenteredTruncatingRemainder(dividingBy: 360.0)) } /// Returns true if self is within circular [from,to] interval. Interval is opened by default. All values reduced to 0..<360 range. public func isWithinCircularInterval(from: Degree, to: Degree, isIntervalOpen: Bool = true) -> Bool { let isIntervalIntersectsZero = from.reduced < to.reduced let isFromLessThenSelf = isIntervalOpen ? from.reduced < self.reduced : from.reduced <= self.reduced let isSelfLessThenTo = isIntervalOpen ? self.reduced < to.reduced : self.reduced <= to.reduced switch (isIntervalIntersectsZero, isFromLessThenSelf, isSelfLessThenTo) { case (true, true, true): return true case (false, true, false), (false, false, true): return true default: return false } } public var description: String { let (sign, deg, min, sec) = self.sexagesimal return sign.string + String(format: "%i°%i'%06.3f\"", deg, min, sec) } } // MARK: - /// The ArcMinute is a unit of angle. public struct ArcMinute: NumericType, CustomStringConvertible { /// The ArcMinute value public let value: Double /// Creates a new ArcMinute instance. /// /// - Parameter value: The value of ArcMinute. public init(_ value: Double) { self.value = value } /// Transform the current ArcMinute in Degree public var inDegrees: Degree { return Degree(value / 60.0) } /// Transform the current ArcMinute in ArcSeconds public var inArcSeconds: ArcSecond { return ArcSecond(value * 60.0) } /// Transform the current ArcMinute in Hours public var inHours: Hour { return inDegrees.inHours } public var description: String { return String(format: "%.2f arcmin", value) } } // MARK: - /// The ArcSecond is a unit of angle. public struct ArcSecond: NumericType, CustomStringConvertible { /// The ArcSecond value public let value: Double /// Creates a new ArcSecond instance. /// /// - Parameter value: The value of ArcSecond. public init(_ value: Double) { self.value = value } /// Transform the current ArcSecond in Degrees public var inDegrees: Degree { return Degree(value / 3600.0) } /// Transform the current ArcSecond in ArcMinutes public var inArcMinutes: ArcMinute { return ArcMinute(value / 60.0) } /// Transform the current ArcSecond in Hours public var inHours: Hour { return inDegrees.inHours } /// Returns a new distance in Astronomical Units, the arcsecond being understood as a /// geometrical parallax. /// /// - Returns: The distance of the object. public func distance() -> Parsec { guard self.value > 0 else { fatalError("Value most be positive and above 0") } return Parsec(1.0/value) } /// Returns a new distance in Astronomical Units, the arcsecond being understood as a /// equatorial horizontal parallax, that is the difference between the topocentric and /// the geocentric coordinates of a solar system body (Sun, planet or comets). /// /// - Returns: The distance of the object. public func distanceFromEquatorialHorizontalParallax() -> AstronomicalUnit { return AstronomicalUnit(KPCAAParallax_ParallaxToDistance(inDegrees.value)) } public var description: String { return String(format: "%.2f arcsec", value) } } // MARK: - /// The Radian is a unit of angle. public struct Radian: NumericType, CustomStringConvertible { /// The Radian value public let value: Double /// Creates a new Radian instance. /// /// - Parameter value: The value of Radian. public init(_ value: Double) { self.value = value } /// Transform the current Radian in Degrees public var inDegrees: Degree { return Degree(value * rad2deg) } /// Transform the current Radian in Hours public var inHours: Hour { return Hour(value * rad2hour) } /// Returns self reduced to 0..<2PI range public var reduced: Radian { return Radian(value.positiveTruncatingRemainder(dividingBy: 2*Double.pi)) } /// Returns self reduced to -pi..<pi range (around 0) public var reduced0: Radian { return Radian(value.zeroCenteredTruncatingRemainder(dividingBy: 2*Double.pi)) } public var description: String { return String(format: "%.3f rad", value) } }
mit
814054cbd03c4ec122aec94cf195b13d
37.372881
135
0.65798
4.195182
false
false
false
false
White-Label/Swift-SDK
Example/WhiteLabel/MixtapeTableViewController.swift
1
5362
// // MixtapeTableViewController.swift // // Created by Alex Givens http://alexgivens.com on 7/28/16 // Copyright © 2016 Noon Pacific LLC http://noonpacific.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 UIKit import CoreData import WhiteLabel class MixtapeTableViewController: UITableViewController { var collection: WLCollection! var fetchedResultsController: NSFetchedResultsController<WLMixtape>! let paging = PagingGenerator(startPage: 1) override func viewDidLoad() { super.viewDidLoad() title = collection.title refreshControl?.addTarget(self, action: #selector(handleRefresh), for: .valueChanged) // Setup fetched results controller let fetchRequest = WLMixtape.sortedFetchRequest(forCollection: self.collection) let managedObjectContext = CoreDataStack.shared.backgroundManagedObjectContext fetchedResultsController = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() } catch { fatalError("Failed to initialize FetchedResultsController: \(error)") } // Setup the paging generator with White Label paging.next = { page, completionMarker in if page == 1 { WLMixtape.deleteMixtapes(forCollection: self.collection) } WhiteLabel.ListMixtapes(inCollection: self.collection, page: page) { result, total, pageSize in switch result { case .success(let mixtapes): if mixtapes.count < pageSize { self.paging.reachedEnd() } completionMarker(true) case .failure(let error): debugPrint(error) completionMarker(false) } } } paging.getNext() // Initial load } @objc func handleRefresh(refreshControl: UIRefreshControl) { paging.reset() paging.getNext() { refreshControl.endRefreshing() } } // MARK: Data Source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fetchedResultsController.sections?[section].numberOfObjects ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.Mixtape, for: indexPath) let mixtape = fetchedResultsController.object(at: indexPath) cell.textLabel?.text = mixtape.title cell.detailTextLabel?.text = String(mixtape.trackCount) return cell } // MARK: Delegate override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if // Infinite scroll trigger let cellCount = tableView.dataSource?.tableView(tableView, numberOfRowsInSection: indexPath.section), indexPath.row == cellCount - 1, paging.isFetchingPage == false, paging.didReachEnd == false { paging.getNext() } } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard segue.identifier == SegueIdentifier.MixtapesToTracks, let trackTableViewController = segue.destination as? TrackTableViewController, let selectedIndexPath = tableView.indexPathsForSelectedRows?[0] else { return } let mixtape = fetchedResultsController.object(at: selectedIndexPath) trackTableViewController.mixtape = mixtape } } extension MixtapeTableViewController: NSFetchedResultsControllerDelegate { func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.reloadData() } }
mit
a88634921c7c3eb69fc1e06f7c191352
37.021277
121
0.65305
5.509764
false
false
false
false
WhisperSystems/Signal-iOS
SignalMessaging/attachments/OWSVideoPlayer.swift
1
2587
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import AVFoundation @objc public protocol OWSVideoPlayerDelegate: class { func videoPlayerDidPlayToCompletion(_ videoPlayer: OWSVideoPlayer) } @objc public class OWSVideoPlayer: NSObject { @objc public let avPlayer: AVPlayer let audioActivity: AudioActivity let shouldLoop: Bool @objc weak public var delegate: OWSVideoPlayerDelegate? @objc convenience public init(url: URL) { self.init(url: url, shouldLoop: false) } @objc public init(url: URL, shouldLoop: Bool) { self.avPlayer = AVPlayer(url: url) self.audioActivity = AudioActivity(audioDescription: "[OWSVideoPlayer] url:\(url)", behavior: .playback) self.shouldLoop = shouldLoop super.init() NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToCompletion(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: avPlayer.currentItem) } // MARK: Dependencies var audioSession: OWSAudioSession { return Environment.shared.audioSession } // MARK: Playback Controls @objc public func pause() { avPlayer.pause() audioSession.endAudioActivity(self.audioActivity) } @objc public func play() { let success = audioSession.startAudioActivity(self.audioActivity) assert(success) guard let item = avPlayer.currentItem else { owsFailDebug("video player item was unexpectedly nil") return } if item.currentTime() == item.duration { // Rewind for repeated plays, but only if it previously played to end. avPlayer.seek(to: CMTime.zero) } avPlayer.play() } @objc public func stop() { avPlayer.pause() avPlayer.seek(to: CMTime.zero) audioSession.endAudioActivity(self.audioActivity) } @objc(seekToTime:) public func seek(to time: CMTime) { avPlayer.seek(to: time) } // MARK: private @objc private func playerItemDidPlayToCompletion(_ notification: Notification) { self.delegate?.videoPlayerDidPlayToCompletion(self) if shouldLoop { avPlayer.seek(to: CMTime.zero) avPlayer.play() } else { audioSession.endAudioActivity(self.audioActivity) } } }
gpl-3.0
237f6128a5e15d792b0c10e53bd6a409
25.131313
112
0.615385
4.853659
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureQRCodeScanner/Sources/FeatureQRCodeScannerUI/QRCodeScanner/QRCodeScannerViewOverlay.swift
1
9547
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Localization import UIKit final class QRCodeScannerViewOverlay: UIView { private enum Images { case cameraRoll case connectedDapps case flashDisabled case flashEnabled case target private var name: String { switch self { case .cameraRoll: return "camera-roll-button" case .connectedDapps: return "connectedDappsIcon" case .flashDisabled: return "flashDisabled" case .flashEnabled: return "flashEnabled" case .target: return "target" } } var image: UIImage? { UIImage( named: name, in: .featureQRCodeScannerUI, with: nil ) } } /// The area that the QR code must be within. var scannableFrame: CGRect { // We want a 280x280 square. let halfAxis: CGFloat = 140 // We have the target coordinate space bounds. let targetBounds = targetCoordinateSpace.bounds // We create a rect representing a 280x280 square in the middle of target. let targetSquare = CGRect( x: targetBounds.midX - halfAxis, y: targetBounds.midY - halfAxis, width: 2 * halfAxis, height: 2 * halfAxis ) // We convert the rect from the target coordinate space into ours. return convert(targetSquare, from: targetCoordinateSpace) } private let viewModel: QRCodeScannerOverlayViewModel private let scanningViewFinder = UIView() private let flashButton = UIButton() private let cameraRollButton = UIButton() private let connectedDappsButton = UIButton() private let subtitleLabel = UILabel() private let titleLabel = UILabel() private var cancellables = [AnyCancellable]() private let targetCoordinateSpace: UICoordinateSpace private let cameraRollButtonSubject = PassthroughSubject<Void, Never>() private let flashButtonSubject = PassthroughSubject<Void, Never>() private let connectedDAppsButtonSubject = PassthroughSubject<Void, Never>() private let targetImageView = UIImageView(image: Images.target.image) init(viewModel: QRCodeScannerOverlayViewModel, targetCoordinateSpace: UICoordinateSpace) { self.viewModel = viewModel self.targetCoordinateSpace = targetCoordinateSpace super.init(frame: .zero) setupSubviews() viewModel.scanSuccess .receive(on: DispatchQueue.main) .sink { [weak self] result in switch result { case .success(let success): self?.setScanningBorder(color: success ? .successBorder : .idleBorder) case .failure: self?.setScanningBorder(color: .errorBorder) } } .store(in: &cancellables) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setScanningBorder(color: UIColor) { UIView.animate(withDuration: 0.3) { self.targetImageView.tintColor = color } } private func setupSubviews() { backgroundColor = UIColor.darkFadeBackground.withAlphaComponent(0.9) setupButtons() setupLabels() setupBorderView() } private func setupLabels() { viewModel.titleLabelContent .receive(on: DispatchQueue.main) .sink { [weak self] in self?.titleLabel.content = $0 } .store(in: &cancellables) addSubview(subtitleLabel) subtitleLabel.layoutToSuperview(.leading, offset: 24) subtitleLabel.layoutToSuperview(.trailing, offset: -24) subtitleLabel.layoutToSuperview(.top, offset: 16) subtitleLabel.numberOfLines = 0 viewModel.subtitleLabelContent .receive(on: DispatchQueue.main) .sink { [weak self] in self?.subtitleLabel.content = $0 } .store(in: &cancellables) } private func setupButtons() { addSubview(flashButton) addSubview(cameraRollButton) addSubview(targetImageView) addSubview(connectedDappsButton) cameraRollButton.addTarget(self, action: #selector(onCameraRollTap), for: .touchUpInside) cameraRollButton.layout(size: .edge(44)) cameraRollButton.layoutToSuperview(.trailing, offset: -44) cameraRollButton.layoutToSuperview(.bottom, offset: -64) flashButton.layout(size: .edge(44)) flashButton.layoutToSuperview(.centerX) flashButton.layout(edge: .top, to: .bottom, of: targetImageView, offset: 20) flashButton.addTarget(self, action: #selector(onFlashButtonTap), for: .touchUpInside) connectedDappsButton.layoutToSuperview(.bottom, offset: -50) connectedDappsButton.layoutToSuperview(.centerX) connectedDappsButton.layout(dimension: .height, to: 48) viewModel .cameraRollButtonVisibility .map(\.isHidden) .receive(on: RunLoop.main) .sink { [weak self] in self?.cameraRollButton.isHidden = $0 } .store(in: &cancellables) viewModel .dAppsButtonVisibility .map(\.isHidden) .receive(on: RunLoop.main) .sink { [weak self] in self?.connectedDappsButton.isHidden = $0 } .store(in: &cancellables) viewModel .dAppsButtonTitle .receive(on: RunLoop.main) .sink { [weak self] in self?.connectedDappsButton.setTitle($0, for: .normal) } .store(in: &cancellables) cameraRollButtonSubject .eraseToAnyPublisher() .throttle( for: .milliseconds(200), scheduler: DispatchQueue.global(qos: .background), latest: false ) .sink { [weak self] in self?.viewModel.cameraTapRelay.send($0) } .store(in: &cancellables) viewModel .flashEnabled .receive(on: RunLoop.main) .sink { [weak self] enabled in self?.flashButton.isSelected = enabled } .store(in: &cancellables) flashButtonSubject .eraseToAnyPublisher() .throttle( for: .milliseconds(200), scheduler: DispatchQueue.global(qos: .background), latest: false ) .sink { [weak self] in self?.viewModel.flashTapRelay.send($0) } .store(in: &cancellables) connectedDAppsButtonSubject .eraseToAnyPublisher() .throttle( for: .milliseconds(200), scheduler: DispatchQueue.global(qos: .background), latest: false ) .receive(on: DispatchQueue.main) .sink { [weak self] in self?.viewModel.connectedDAppsTapped?() } .store(in: &cancellables) cameraRollButton.setImage(Images.cameraRoll.image, for: .normal) connectedDappsButton.setImage(Images.connectedDapps.image, for: .normal) connectedDappsButton.titleLabel?.font = UIFont.main(.medium, 16) connectedDappsButton.setTitleColor(.tertiaryButton, for: .normal) connectedDappsButton.layer.cornerRadius = 24 connectedDappsButton.backgroundColor = .mediumBackground connectedDappsButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 24, bottom: 0, right: 34) connectedDappsButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: -10) connectedDappsButton.addTarget(self, action: #selector(onConnectedDAppsButtonTap), for: .touchUpInside) flashButton.setImage(Images.flashDisabled.image, for: .normal) flashButton.setImage(Images.flashEnabled.image, for: .selected) flashButton.setImage(Images.flashEnabled.image, for: .highlighted) } override func layoutSubviews() { super.layoutSubviews() let scannableFrame = scannableFrame setupLayerMask(frame: scannableFrame) targetImageView.frame.origin = scannableFrame.origin.applying(CGAffineTransform(translationX: -12, y: -12)) } /// Sets up layers mask given the frame provided. private func setupLayerMask(frame: CGRect) { let maskLayer = CAShapeLayer() maskLayer.frame = bounds let path = UIBezierPath(rect: bounds) path.append( .init( roundedRect: scannableFrame, byRoundingCorners: .allCorners, cornerRadii: .edge(8) ) ) maskLayer.fillRule = .evenOdd maskLayer.path = path.cgPath layer.mask = maskLayer } private func setupBorderView() { targetImageView.tintColor = .idleBorder targetImageView.frame.origin = scannableFrame.origin } @objc private func onCameraRollTap() { cameraRollButtonSubject.send() } @objc private func onFlashButtonTap() { flashButtonSubject.send() } @objc private func onConnectedDAppsButtonTap() { connectedDAppsButtonSubject.send() } }
lgpl-3.0
920dbefdd0d160f912df76f60f4717f3
34.225092
115
0.609575
4.940994
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Pods/Former/Former/Cells/FormSelectorDatePickerCell.swift
2
2894
// // FormSelectorDatePickerCell.swift // Former-Demo // // Created by Ryo Aoyama on 8/25/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit open class FormSelectorDatePickerCell: FormCell, SelectorDatePickerFormableRow { // MARK: Public open var selectorDatePicker: UIDatePicker? open var selectorAccessoryView: UIView? public private(set) weak var titleLabel: UILabel! public private(set) weak var displayLabel: UILabel! public func formTitleLabel() -> UILabel? { return titleLabel } public func formDisplayLabel() -> UILabel? { return displayLabel } open func formDefaultDisplayLabelText() -> String? { return "Not Set" } open func formDefaultDisplayDate() -> NSDate? { return NSDate() } open override func updateWithRowFormer(_ rowFormer: RowFormer) { super.updateWithRowFormer(rowFormer) rightConst.constant = (accessoryType == .none) ? -15 : 0 } open override func setup() { super.setup() let titleLabel = UILabel() titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal) titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.insertSubview(titleLabel, at: 0) self.titleLabel = titleLabel let displayLabel = UILabel() displayLabel.textColor = .lightGray displayLabel.textAlignment = .right displayLabel.translatesAutoresizingMaskIntoConstraints = false contentView.insertSubview(displayLabel, at: 0) self.displayLabel = displayLabel let constraints = [ NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[title]-0-|", options: [], metrics: nil, views: ["title": titleLabel] ), NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[display]-0-|", options: [], metrics: nil, views: ["display": displayLabel] ), NSLayoutConstraint.constraints( withVisualFormat: "H:|-15-[title]-10-[display(>=0)]", options: [], metrics: nil, views: ["title": titleLabel, "display": displayLabel] ) ].flatMap { $0 } let rightConst = NSLayoutConstraint( item: displayLabel, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: 0 ) contentView.addConstraints(constraints + [rightConst]) self.rightConst = rightConst } // MARK: Private private weak var rightConst: NSLayoutConstraint! }
mit
3d185328f39817dbfdb0f15e18a8f699
29.776596
95
0.589699
5.479167
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Extensions/Sources/SwiftExtensions/Scale.swift
1
1799
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import CoreGraphics public struct Scale<X: BinaryFloatingPoint> { public var domain: [X] { didSet { update() } } public var domainUsed: [X] { map.map(\.domain) } public var range: [X] { didSet { update() } } public var rangeUsed: [X] { map.map(\.range) } public private(set) var map: [(domain: X, range: X)] = [] public var inverse: Scale { Scale(domain: range, range: domain) } public init(domain: [X] = [0, 1], range: [X] = [0, 1]) { self.domain = domain self.range = range update() } mutating func update() { map = zip(domain, range).sorted(by: <) } public func scale(_ x: X, _ f: (X) -> X) -> X { switch map.count { case 0: return x case 1: return map[0].domain - x + map[0].range default: if x <= map[0].domain { return map[0].range } var from = map[0] for to in map[1..<map.count] { if x < to.domain { let y = f((x - from.domain) / (to.domain - from.domain)) let a = (1 - y) * from.range + y * to.range precondition(!a.isNaN) return a } from = to } return map[map.index(before: map.endIndex)].range } } } extension Scale { @inlinable public func linear(_ x: X) -> X { scale(x) { x in x } } } extension Scale where X: ExpressibleByFloatLiteral { @inlinable public func pow(_ x: X, exp: X = 2) -> X { scale(x) { x in pow(x, exp: exp) } } @inlinable public func sin(_ x: X) -> X { scale(x) { x in sin((x - 0.5) * .pi) * 0.5 + 0.5 } } }
lgpl-3.0
4564f5ba86a2b6804934ee7bfbe73465
25.441176
76
0.490545
3.546351
false
false
false
false
M2Mobi/Marky-Mark
Example/Tests/Rules/Inline/LinkRuleTests.swift
1
5268
// // Created by Maren Osnabrug on 10-05-16. // Copyright © 2016 M2mobi. All rights reserved. // import XCTest @testable import markymark class LinkRuleTests: XCTestCase { var sut: LinkRule! override func setUp() { super.setUp() sut = LinkRule() } func testRecognizesLines() { XCTAssertTrue(sut.recognizesLines(["[Alt text](image.png)"])) XCTAssertFalse((sut.recognizesLines(["![Alt text](image.png)"]))) XCTAssertTrue(sut.recognizesLines([#"[Alt text](image.png "some title")"#])) } func test_DoesNotRecognizeLines_When_PrefixedWithExclamationMark() { XCTAssertFalse((sut.recognizesLines(["![Alt text](image.png)"]))) XCTAssertFalse((sut.recognizesLines(["! [Alt text](image.png)"]))) XCTAssertFalse((sut.recognizesLines([#"![Alt text](image.png "some title")"#]))) } func test_GetAllMatchesReturnsZero_When_InvalidInput() { // Assert XCTAssert(sut.getAllMatches(["(https://www.google.com)"]).isEmpty) XCTAssert(sut.getAllMatches(["[Google]"]).isEmpty) XCTAssert(sut.getAllMatches(["![Google](https://www.google.com)"]).isEmpty) } func testCreateMarkDownItemWithLinesCreatesCorrectItem() { // Act let markDownItem = sut.createMarkDownItemWithLines(["[Google](http://www.google.com)"]) // Assert XCTAssert(markDownItem is LinkMarkDownItem) } func testCreateMarkDownItemContainsCorrectLink() { // Act let markDownItem = sut.createMarkDownItemWithLines(["[Google](http://www.google.com)"]) let markDownItem2 = sut.createMarkDownItemWithLines(["[Youtube](http://www.youtube.com)"]) // Assert XCTAssertEqual((markDownItem as! LinkMarkDownItem).content, "Google") XCTAssertEqual((markDownItem as! LinkMarkDownItem).url, "http://www.google.com") XCTAssertEqual((markDownItem2 as! LinkMarkDownItem).content, "Youtube") XCTAssertEqual((markDownItem2 as! LinkMarkDownItem).url, "http://www.youtube.com") } func testGetAllMatches() { // Arrange let expectedMatchesRange = NSRange(location: 0, length: 32) let expectedMatchesRange2 = NSRange(location: 38, length: 32) // Act + Assert XCTAssertEqual(sut.getAllMatches(["[Google]"]).count, 0) XCTAssertEqual(sut.getAllMatches(["(https://www.google.com)"]).count, 0) XCTAssertEqual(sut.getAllMatches(["[Google](https://www.google.com)"]), [expectedMatchesRange]) XCTAssertEqual(sut.getAllMatches(["![Google](https://www.google.com)"]).count, 0) XCTAssertEqual( sut.getAllMatches(["[Google](https://www.google.com) test [Google](https://www.google.com)"]), [expectedMatchesRange, expectedMatchesRange2] ) XCTAssertEqual( sut.getAllMatches([#"[Google](https://www.google.com) test [Google](https://www.google.com "a11y title")"#]), [ NSRange(location: 0, length: 32), NSRange(location: 38, length: 45) ] ) } func test_ParsesItem_When_InputMatches() throws { // Arrange let cases: [(String, String, String, UInt)] = [ ( #"[Google plain link](https://google.com)"#, "Google plain link", "https://google.com", #line ), ( #"[Google w/ title](http://www.google.com "with custom title")"#, "Google w/ title", "http://www.google.com", #line ), ( #"[Simple link](https://google.nl)"#, "Simple link", "https://google.nl", #line ), ( #"Inside [another link](http://m2mobi.com/) sentence"#, "another link", "http://m2mobi.com/", #line ), ( #"Inside [another link](http://m2mobi.com/ "with custom title") sentence"#, "another link", "http://m2mobi.com/", #line ), ( #"[Underscored link](https://google.nl/?param=a_b_c)"#, "Underscored link", "https://google.nl/?param=a_b_c", #line ), ( #"[Underscored link 2](https://google.nl/?param=a_b_c&d=e)"#, "Underscored link 2", "https://google.nl/?param=a_b_c&d=e", #line ), ( #"[Underscored link 4](https://google.nl/?param=a_b_c&d=e_f_g)"#, "Underscored link 4", "https://google.nl/?param=a_b_c&d=e_f_g", #line ) ] for (input, content, url, line) in cases { // Act let output = sut.createMarkDownItemWithLines([input]) // Assert let linkMarkDownItem = try XCTUnwrap(output as? LinkMarkDownItem) XCTAssertEqual(linkMarkDownItem.content, content, line: line) XCTAssertEqual(linkMarkDownItem.url, url, line: line) } } }
mit
cd66164a540aa1fde9df14f7b870fafa
35.576389
121
0.544522
4.342127
false
true
false
false
maxim-pervushin/HyperHabit
HyperHabit/TodayExtension/Src/Data/TodayDataSource.swift
1
1157
// // Created by Maxim Pervushin on 23/11/15. // Copyright (c) 2015 Maxim Pervushin. All rights reserved. // import Foundation class TodayDataSource: DataSource { var todayReports: [Report] { let habits = dataProvider.habits var reports = dataProvider.reportsForDate(NSDate()) for habit in habits { var createReport = true for report in reports { // TODO: Find better solution if report.habitName == habit.name { createReport = false break; } } if createReport { reports.append(Report(habit: habit, repeatsDone: 0, date: NSDate())) } } return reports.sort({ $0.habitName > $1.habitName }) } var completedReports: [Report] { return todayReports.filter { return $0.completed } } var incompletedReports: [Report] { return todayReports.filter { return !$0.completed } } func saveReport(report: Report) -> Bool { return dataProvider.saveReport(report) } }
mit
2fcddeae7d265e658c144022285ed2b7
25.295455
84
0.547105
4.703252
false
false
false
false
tutsplus/iOS-OnDemandResources-StarterProject
ODR Introduction/DetailViewController.swift
1
1764
// // DetailViewController.swift // ODR Introduction // // Created by Davis Allie on 26/09/2015. // Copyright © 2015 tutsplus. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var image1: UIImageView! @IBOutlet weak var image2: UIImageView! @IBOutlet weak var image3: UIImageView! @IBOutlet weak var image4: UIImageView! var tagToLoad: String! override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.displayImages() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func displayImages() { if colorTags.contains(tagToLoad) { image1.image = UIImage(named: tagToLoad + " Circle") image2.image = UIImage(named: tagToLoad + " Square") image3.image = UIImage(named: tagToLoad + " Star") image4.image = UIImage(named: tagToLoad + " Hexagon") } else if shapeTags.contains(tagToLoad) { image1.image = UIImage(named: "Red " + tagToLoad) image2.image = UIImage(named: "Blue " + tagToLoad) image3.image = UIImage(named: "Green " + tagToLoad) } } /* // 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. } */ }
bsd-2-clause
434b881e9f2e3658ff98647e6804c75b
29.396552
106
0.63755
4.508951
false
false
false
false
wikimedia/apps-ios-wikipedia
Wikipedia/Code/TextFormattingProvidingTableViewController.swift
1
4120
enum TextStyleType: Int { case paragraph case heading = 2 // Heading is 2 equals (we don't show a heading choice for 1 equals variant) case subheading1 = 3 case subheading2 = 4 case subheading3 = 5 case subheading4 = 6 var name: String { switch self { case .paragraph: return "Paragraph" case .heading: return "Heading" case .subheading1: return "Sub-heading 1" case .subheading2: return "Sub-heading 2" case .subheading3: return "Sub-heading 3" case .subheading4: return "Sub-heading 4" } } } enum TextSizeType: String { case normal case big case small var name: String { switch self { case .normal: return "Normal" case .big: return "Big" case .small: return "Small" } } } class TextFormattingProvidingTableViewController: UITableViewController, TextFormattingProviding { weak var delegate: TextFormattingDelegate? var theme = Theme.standard open var titleLabelText: String? { return nil } open var shouldSetCustomTitleLabel: Bool { return true } private lazy var titleLabel: UILabel = { let label = UILabel() label.text = titleLabelText label.sizeToFit() return label }() private lazy var closeButton: UIBarButtonItem = { let button = UIBarButtonItem(image: #imageLiteral(resourceName: "close"), style: .plain, target: self, action: #selector(close(_:))) return button }() final var selectedTextStyleType: TextStyleType = .paragraph { didSet { guard navigationController != nil else { return } tableView.reloadData() } } final var selectedTextSizeType: TextSizeType = .normal { didSet { guard navigationController != nil else { return } tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() if shouldSetCustomTitleLabel { leftAlignTitleItem() } setCloseButton() navigationItem.backBarButtonItem?.title = titleLabelText apply(theme: theme) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } private func leftAlignTitleItem() { navigationItem.leftBarButtonItem = UIBarButtonItem(customView: titleLabel) } private func setCloseButton() { navigationItem.rightBarButtonItem = closeButton } private func updateTitleLabel() { titleLabel.font = UIFont.wmf_font(.headline, compatibleWithTraitCollection: traitCollection) titleLabel.sizeToFit() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateTitleLabel() } @objc private func close(_ sender: UIBarButtonItem) { delegate?.textFormattingProvidingDidTapClose() } // MARK: Text & button selection messages open func textSelectionDidChange(isRangeSelected: Bool) { selectedTextStyleType = .paragraph selectedTextSizeType = .normal } open func buttonSelectionDidChange(button: SectionEditorButton) { switch button.kind { case .heading(let type): selectedTextStyleType = type case .textSize(let type): selectedTextSizeType = type default: break } } open func disableButton(button: SectionEditorButton) { } } extension TextFormattingProvidingTableViewController: Themeable { func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } tableView.backgroundColor = theme.colors.inputAccessoryBackground titleLabel.textColor = theme.colors.primaryText } }
mit
a2eaa96dc238567e3a5aa1d43c6e4509
25.410256
140
0.614806
5.322997
false
false
false
false
Mirmeca/Mirmeca
Mirmeca/CommentGateway.swift
1
1118
// // CommentGateway.swift // Mirmeca // // Created by solal on 2/08/2015. // Copyright (c) 2015 Mirmeca. All rights reserved. // import Alamofire import ObjectMapper public struct CommentGateway: GatewayProtocol { private var url: String? public init(endpoint: String, env: String?) { let env = MirmecaEnv.sharedInstance.getEnv(env) self.url = "\(env)/\(endpoint)" } public func request(completion: (value: AnyObject?, error: NSError?) -> Void) { Alamofire.request(.GET, self.url!).responseJSON { (_, _, JSON, _) in var value: Comment? var error: NSError? if (JSON != nil) { if let mappedObject = Mapper<Comment>().map(JSON) { value = mappedObject } else { error = NSError(domain: self.url!, code: 303, userInfo: nil) } } else { error = NSError(domain: self.url!, code: 302, userInfo: nil) } completion(value: value, error: error) } } }
mit
5f1ce443d3966fb7dbe3b11f804167c8
26.95
83
0.525939
4.418972
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/Pods/CHPageCardView/CHPageCardView/Classes/CHPageCardFlowLayout.swift
2
3849
// // CHPageCardFlowLayout.swift // Pods // // Created by Chance on 2017/2/27. // // import UIKit protocol CHPageCardFlowLayoutDelegate: class { func scrollToPageIndex(index: Int) } /// 卡片组内元素布局控制 /// 教程在http://llyblog.com/2016/09/01/iOS卡片控件的实现/ class CHPageCardFlowLayout: UICollectionViewFlowLayout { var previousOffsetX: CGFloat = 0 /// 当前页码 var pageNum: Int = 0 weak var delegate: CHPageCardFlowLayoutDelegate? /// 重载准备方法 override func prepare() { super.prepare() //滑动方向 self.scrollDirection = .horizontal //计算cell超出显示的宽度 let width = ((self.collectionView!.frame.size.width - self.itemSize.width) - (self.minimumLineSpacing * 2)) / 2 //每个section的间距 self.sectionInset = UIEdgeInsetsMake(0, self.minimumLineSpacing + width, 0, self.minimumLineSpacing + width) } /// 控制元素布局的属性的动态变化 /// /// - Parameter rect: /// - Returns: override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let attributes = super.layoutAttributesForElements(in: rect) let visibleRect = CGRect( x: self.collectionView!.contentOffset.x, y: self.collectionView!.contentOffset.y, width: self.collectionView!.frame.size.width, height: self.collectionView!.frame.size.height) let offset = visibleRect.midX for attribute in attributes! { let distance = offset - attribute.center.x // 越往中心移动,值越小,从而显示就越大 // 同样,超过中心后,越往左、右走,显示就越小 let scaleForDistance = distance / self.itemSize.width // 0.1可调整,值越大,显示就越小 let scaleForCell = 1 - 0.1 * fabs(scaleForDistance) //只在Y轴方向做缩放,这样中间的那个distance = 0,不进行缩放,非中心的缩小 attribute.transform3D = CATransform3DMakeScale(1, scaleForCell, 1) attribute.zIndex = 1 //渐变 let scaleForAlpha = 1 - fabsf(Float(scaleForDistance)) * 0.6 attribute.alpha = CGFloat(scaleForAlpha) } return attributes } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } /// 控制滑动元素目标落点的位置 /// /// - Parameters: /// - proposedContentOffset: /// - velocity: /// - Returns: override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { // 分页以1/3处 if proposedContentOffset.x > self.previousOffsetX + self.itemSize.width / 3.0 { self.previousOffsetX += self.itemSize.width + self.minimumLineSpacing self.pageNum = Int(self.previousOffsetX / (self.itemSize.width + self.minimumLineSpacing)) self.delegate?.scrollToPageIndex(index: self.pageNum) } else if proposedContentOffset.x < self.previousOffsetX - self.itemSize.width / 3.0 { self.previousOffsetX -= self.itemSize.width + self.minimumLineSpacing self.pageNum = Int(self.previousOffsetX / (self.itemSize.width + self.minimumLineSpacing)) self.delegate?.scrollToPageIndex(index: self.pageNum) } //将当前cell移动到屏幕中间位置 let newPoint = CGPoint(x: self.previousOffsetX, y: proposedContentOffset.y) return newPoint } }
mit
af7eae471236082948754701580cd6ba
30.827273
148
0.617823
4.381727
false
false
false
false
cwaffles/Soulcast
Soulcast/put.swift
1
7689
import UIKit let statusBarHeight = UIApplication.shared.statusBarFrame.size.height extension UIViewController { func addChildVC(_ vc: UIViewController) { addChildViewController(vc) view.addSubview(vc.view) vc.didMove(toParentViewController: vc) } func removeChildVC(_ vc: UIViewController) { vc.willMove(toParentViewController: nil) vc.view.removeFromSuperview() vc.removeFromParentViewController() } func name() -> String { return NSStringFromClass(type(of: self)).components(separatedBy: ".").last! } func navigationBarHeight() -> CGFloat { if let navController = navigationController { return navController.navigationBar.height } else { return 0 } } func put(_ aSubview:UIView, inside thisView:UIView, onThe position:Position, withPadding padding:CGFloat) { view.put(aSubview, inside: thisView, onThe: position, withPadding: padding) } func put(_ aView:UIView, besideAtThe position:Position, of relativeView:UIView, withSpacing spacing:CGFloat) { view.put(aView, atThe: position, of: relativeView, withSpacing: spacing) } } enum Position { case left case right case top case bottom case topLeft case topRight case bottomLeft case bottomRight } protocol PutAware { func wasPut() } extension UIView { //put convenience init(width theWidth:CGFloat, height theHeight: CGFloat) { self.init() self.frame = CGRect(x: 0, y: 0, width: theWidth, height: theHeight) } func put(_ aSubview:UIView, inside thisView:UIView, onThe position:Position, withPadding padding:CGFloat) { assert(aSubview.width <= thisView.width && aSubview.height <= thisView.height, "The subview is too large to fit inside this view!") if position == .left || position == .right { assert(aSubview.width + 2 * padding < thisView.width, "The padding is too wide!") } if position == .top || position == .bottom { assert(aSubview.height + 2 * padding < thisView.height, "The padding is too high!") } if let aLabel = aSubview as? UILabel { aLabel.sizeToFit() } var subRect: CGRect = CGRect.zero switch position { case .left: subRect = CGRect( x: padding, y: thisView.midHeight - aSubview.midHeight, width: aSubview.width, height: aSubview.height) case .right: subRect = CGRect( x: thisView.width - padding - aSubview.width, y: thisView.midHeight - aSubview.midHeight, width: aSubview.width, height: aSubview.height) case .top: subRect = CGRect( x: thisView.midWidth - aSubview.midWidth, y: padding, width: aSubview.width, height: aSubview.height) case .bottom: subRect = CGRect( x: thisView.midWidth - aSubview.midWidth, y: thisView.height - padding - aSubview.height, width: aSubview.width, height: aSubview.height) case .topLeft: subRect = CGRect( x: padding, y: padding, width: aSubview.width, height: aSubview.height) case .topRight: subRect = CGRect( x: thisView.width - padding - aSubview.width, y: padding, width: aSubview.width, height: aSubview.height) case .bottomLeft: subRect = CGRect( x: padding, y: thisView.height - padding - aSubview.height, width: aSubview.width, height: aSubview.height) case .bottomRight: subRect = CGRect( x: thisView.width - padding - aSubview.width, y: thisView.height - padding - aSubview.height, width: aSubview.width, height: aSubview.height) } aSubview.frame = subRect if aSubview.superview != thisView{ thisView.addSubview(aSubview) } (aSubview as? PutAware)?.wasPut() } func put(_ aView:UIView, atThe position:Position, of relativeView:UIView, withSpacing spacing:CGFloat) { let diagonalSpacing:CGFloat = spacing / sqrt(2.0) switch position { case .left: aView.center = CGPoint( x: relativeView.minX - aView.width/2 - spacing, y: relativeView.midY) case .right: aView.center = CGPoint( x: relativeView.maxX + aView.width/2 + spacing, y: relativeView.midY) case .top: aView.center = CGPoint( x: relativeView.midX, y: relativeView.minY - aView.height/2 - spacing) case .bottom: aView.center = CGPoint( x: relativeView.midX, y: relativeView.maxY + aView.height/2 + spacing) case .topLeft: aView.center = CGPoint( x: relativeView.minX - aView.width/2 - diagonalSpacing, y: relativeView.minY - aView.height/2 - diagonalSpacing) case .topRight: aView.center = CGPoint( x: relativeView.maxX + aView.width/2 + diagonalSpacing, y: relativeView.minY - aView.height/2 - diagonalSpacing) case .bottomLeft: aView.center = CGPoint( x: relativeView.minX - aView.width/2 - diagonalSpacing, y: relativeView.maxY + aView.height/2 + diagonalSpacing) case .bottomRight: aView.center = CGPoint( x: relativeView.maxX + aView.width/2 + diagonalSpacing, y: relativeView.maxY + aView.height/2 + diagonalSpacing) } if let relativeSuperview = relativeView.superview { relativeSuperview.addSubview(aView) } (aView as? PutAware)?.wasPut() } func resize(toWidth width:CGFloat, toHeight height:CGFloat) { frame = CGRect(x: minX, y: minY, width: width, height: height) (self as? PutAware)?.wasPut() } func reposition(toX newX:CGFloat, toY newY:CGFloat) { frame = CGRect(x: newX, y: newY, width: width, height: height) (self as? PutAware)?.wasPut() } func shift(toRight deltaX:CGFloat, toBottom deltaY:CGFloat) { frame = CGRect(x: minX + deltaX, y: minY + deltaY, width: width, height: height) (self as? PutAware)?.wasPut() } var width: CGFloat { return frame.width } var height: CGFloat { return frame.height } var minX: CGFloat { return frame.minX } var minY: CGFloat { return frame.minY } var midX: CGFloat { return frame.midX } var midY: CGFloat { return frame.midY } var midWidth: CGFloat { return frame.width/2 } var midHeight: CGFloat { return frame.height/2 } var maxX: CGFloat { return frame.maxX } var maxY: CGFloat { return frame.maxY } } enum FontStyle: String { case Regular = "Regular" case DemiBold = "DemiBold" case Medium = "Medium" } func brandFont(_ style: FontStyle? = .DemiBold, size:CGFloat? = 16) -> UIFont { return UIFont(name: "AvenirNext-" + style!.rawValue, size: size!)! } func delay(_ delay:Double, closure:@escaping ()->()) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) } func imageFromUrl(_ url:URL) -> UIImage { let data = try? Data(contentsOf: url) return UIImage(data: data!)! } extension UIView { func animate(to theFrame: CGRect, completion: @escaping () -> () = {}) { UIView.animate(withDuration: 0.3, animations: { () -> Void in self.frame = theFrame }, completion: { (finished:Bool) -> Void in completion() }) } func addShadow() { layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor layer.shadowOffset = CGSize.zero layer.shadowOpacity = 1 layer.shadowRadius = 7 } func addThinShadow() { layer.shadowColor = UIColor.black.withAlphaComponent(0.4).cgColor layer.shadowOffset = CGSize.zero layer.shadowOpacity = 1 layer.shadowRadius = 1 } }
mit
82ae9edf83715f82272777fad93b8899
29.879518
120
0.649629
3.901065
false
false
false
false
akane/Akane
Tests/Akane/Binding/Observation/DisplayObservationTests.swift
1
3803
// // DisplayObservationTests.swift // AkaneTests // // Created by pjechris on 15/01/2018. // Copyright © 2018 fr.akane. All rights reserved. // import Foundation import Nimble import Quick @testable import Akane class DisplayObservationTests : QuickSpec { override func spec() { var observation: DisplayObservationStub! var container: ContainerMock! var ctx: ContextMock! beforeEach { container = ContainerMock() ctx = ContextMock() let observer = ViewObserver(container: container, context: ctx) observation = DisplayObservationStub(view: ViewMock(frame: .zero), container: container, observer: observer) } describe("to(params:)") { it("binds on view") { observation.to(params: ()) expect(observation.view.bindCalled) == 1 } context("view is of type Wrapped") { it("asks container for component") { observation.to(params: ViewModelMock()) expect(container.componentForViewCalled) == 1 } } context("view model is injectable") { it("injects/resolves view model") { observation.to(params: ()) expect(ctx.resolvedCalledCount) == 1 } context("view model injected") { var viewModel: ViewModelMock! beforeEach { viewModel = ViewModelMock() observation.view.params = viewModel } it("binds with existing view model") { observation.view.bindChecker = { _, params in expect(params) === viewModel } observation.to(params: ()) } } } } } } extension DisplayObservationTests { class DisplayObservationStub : DisplayObservation<ViewMock> { } class ContextMock : Context { private(set) var resolvedCalledCount = 0 func resolve<T>(_ type: T.Type, parameters: T.InjectionParameters) -> T where T : ComponentViewModel, T : Injectable, T : Paramaterized { self.resolvedCalledCount += 1 return T.init(resolver: self, parameters: parameters) } } class ContainerMock : UIViewController, ComponentContainer { var componentForViewCalled = 0 func component<View: Wrapped>(for view: View) -> View.Wrapper { self.componentForViewCalled += 1 return View.Wrapper.init(coder: NSCoder.empty())! } } class ViewModelMock : ComponentViewModel, Injectable, Paramaterized { typealias Parameters = Void var params: Void required convenience init(resolver: DependencyResolver, parameters: Void) { self.init() } init() { self.params = () } } class ViewMock : UIView, ComponentDisplayable, Wrapped { typealias Wrapper = ComponentMock var bindCalled = 0 var bindChecker: ((ViewObserver, DisplayObservationTests.ViewModelMock) -> ())? = nil func bindings(_ observer: ViewObserver, params: ViewModelMock) { } func bind(_ observer: ViewObserver, params: DisplayObservationTests.ViewModelMock) { self.bindChecker?(observer, params) self.bindCalled += 1 } } class ComponentMock : UIViewController, ComponentController { typealias ViewType = ViewMock } }
mit
a9c4ce93519e23a359e8d8cdebd3e644
28.937008
145
0.544187
5.295265
false
true
false
false
CoderSLZeng/SLWeiBo
SLWeiBo/SLWeiBo/Classes/Home/Model/StatusViewModel.swift
1
2769
// // StatusViewModel.swift // SLWeiBo // // Created by Anthony on 17/3/14. // Copyright © 2017年 SLZeng. All rights reserved. // import UIKit class StatusViewModel { // MARK:- 定义属性 var status : Status? /// cell的高度 var cellHeight : CGFloat = 0 // MARK:- 对数据处理的属性 /// 处理过的微博来源 var sourceText : String? /// 处理过的微博创建时间 var createAtText : String? /// 处理过的用户认证图标 var verifiedImage : UIImage? /// 处理过的用户会员图标 var vipImage : UIImage? // 处理过的用户头像的地址 var profileURL : URL? /// 处理微博配图的数据 var picURLs : [URL] = [URL]() // MARK:- 自定义构造函数 init(status : Status) { self.status = status // 1.对来源处理 if let source = status.source, source != "" { // 1.1.获取起始位置和截取的长度 let startIndex = (source as NSString).range(of: ">").location + 1 let length = (source as NSString).range(of: "</").location - startIndex // 1.2.截取字符串 sourceText = (source as NSString).substring(with: NSRange(location: startIndex, length: length)) } // 2.处理时间 if let createAt = status.created_at { createAtText = Date.createDateString(createAt) } // 3.处理认证 let verifiedType = status.user?.verified_type ?? -1 switch verifiedType { case 0: verifiedImage = UIImage(named: "avatar_vip") case 2, 3, 5: verifiedImage = UIImage(named: "avatar_enterprise_vip") case 220: verifiedImage = UIImage(named: "avatar_grassroot") default: verifiedImage = nil } // 4.处理会员图标 let mbrank = status.user?.mbrank ?? 0 if mbrank > 0 && mbrank <= 6 { vipImage = UIImage(named: "common_icon_membership_level\(mbrank)") } // 5.用户头像的处理 let profileURLString = status.user?.profile_image_url ?? "" profileURL = URL(string: profileURLString) // 6.处理配图数据 // 6.1判断获取微博或转发配图 let picURLDicts = status.pic_urls!.count != 0 ? status.pic_urls : status.retweeted_status?.pic_urls if let picURLDicts = picURLDicts { for picURLDict in picURLDicts { guard let picURLString = picURLDict["thumbnail_pic"] else { continue } picURLs.append(URL(string: picURLString)!) } } } }
mit
8f778416557c9e851f3831879892c068
27.574713
108
0.538214
4.185185
false
false
false
false
mofneko/swift-layout
add-on/AutolayoutPullArea.swift
1
1925
// // AutolayoutPullArea.swift // swift-layout // // Created by grachro on 2014/09/15. // Copyright (c) 2014年 grachro. All rights reserved. // import UIKit class AutolayoutPullArea:ScrollViewPullArea { private var _minHeight:CGFloat private var _maxHeight:CGFloat var topConstraint:NSLayoutConstraint? var headerConstraint:NSLayoutConstraint? let view = UIView() private var _layout:Layout? var layout:Layout { get {return _layout!} } var pullCallback:((viewHeight:CGFloat, pullAreaHeight:CGFloat) -> Void)? = nil init(minHeight:CGFloat, maxHeight:CGFloat, superview:UIView) { self._minHeight = minHeight self._maxHeight = maxHeight _layout = Layout.addSubView(view, superview: superview) .horizontalCenterInSuperview() .leftIsSameSuperview() .rightIsSameSuperview() .top(-self._maxHeight).fromSuperviewTop().lastConstraint(&topConstraint) .height(self._maxHeight).lastConstraint(&headerConstraint) } } //implements ScrollViewPullArea extension AutolayoutPullArea { func minHeight() -> CGFloat { return _minHeight } func maxHeight() -> CGFloat { return _maxHeight } func animationSpeed() -> NSTimeInterval { return 0.4 } func show(viewHeight viewHeight:CGFloat, pullAreaHeight:CGFloat) { if viewHeight < pullAreaHeight { self.topConstraint?.constant = -((pullAreaHeight - viewHeight) / 2 + viewHeight) } else { self.topConstraint?.constant = -viewHeight } self.headerConstraint?.constant = viewHeight view.superview?.layoutIfNeeded() self.pullCallback?(viewHeight: viewHeight, pullAreaHeight:pullAreaHeight) view.layoutIfNeeded() } }
mit
60a972904bdf235d179a1a8bb2c9800f
24.986486
92
0.626625
4.968992
false
false
false
false
Sorix/CloudCore
Source/Classes/Save/ObjectToRecord/CoreDataRelationship.swift
1
2590
// // CoreDataRelationship.swift // CloudCore // // Created by Vasily Ulianov on 04.02.17. // Copyright © 2017 Vasily Ulianov. All rights reserved. // import CoreData import CloudKit class CoreDataRelationship { typealias Class = CoreDataRelationship let value: Any let description: NSRelationshipDescription /// Initialize Core Data Attribute with properties and value /// - Returns: `nil` if it is not an attribute (possible it is relationship?) init?(value: Any, relationshipName: String, entity: NSEntityDescription) { guard let description = Class.relationshipDescription(for: relationshipName, in: entity) else { // it is not a relationship return nil } self.description = description self.value = value } private static func relationshipDescription(for lookupName: String, in entity: NSEntityDescription) -> NSRelationshipDescription? { for (name, description) in entity.relationshipsByName { if lookupName == name { return description } } return nil } /// Make reference(s) for relationship /// /// - Returns: `CKReference` or `[CKReference]` func makeRecordValue() throws -> Any? { if self.description.isToMany { if value is NSOrderedSet { throw CloudCoreError.orderedSetRelationshipIsNotSupported(description) } guard let objectsSet = value as? NSSet else { return nil } var referenceList = [CKReference]() for (_, managedObject) in objectsSet.enumerated() { guard let managedObject = managedObject as? NSManagedObject, let reference = try makeReference(from: managedObject) else { continue } referenceList.append(reference) } if referenceList.isEmpty { return nil } return referenceList } else { guard let object = value as? NSManagedObject else { return nil } return try makeReference(from: object) } } private func makeReference(from managedObject: NSManagedObject) throws -> CKReference? { let action: CKReferenceAction if case .some(NSDeleteRule.cascadeDeleteRule) = description.inverseRelationship?.deleteRule { action = .deleteSelf } else { action = .none } guard let record = try managedObject.restoreRecordWithSystemFields() else { // That is possible if method is called before all managed object were filled with recordData // That may cause possible reference corruption (Core Data -> iCloud), but it is not critical assertionFailure("Managed Object doesn't have stored record information, should be reported as a framework bug") return nil } return CKReference(record: record, action: action) } }
mit
6fd851964d7c78f8f6e200127152c882
29.458824
132
0.730398
4.19611
false
false
false
false
brave/browser-ios
Providers/Profile.swift
2
11818
/* 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 Alamofire import Foundation import ReadingList import Shared import Storage import XCGLogger import SwiftKeychainWrapper import Deferred private let log = Logger.syncLogger public let NotificationProfileDidStartSyncing = NSNotification.Name(rawValue: "NotificationProfileDidStartSyncing") public let NotificationProfileDidFinishSyncing = NSNotification.Name(rawValue: "NotificationProfileDidFinishSyncing") public let ProfileRemoteTabsSyncDelay: TimeInterval = 0.1 typealias EngineIdentifier = String class ProfileFileAccessor: FileAccessor { convenience init(profile: Profile) { self.init(localName: profile.localName()) } init(localName: String) { let profileDirName = "profile.\(localName)" // Bug 1147262: First option is for device, second is for simulator. var rootPath: String let sharedContainerIdentifier = AppInfo.sharedContainerIdentifier if let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: sharedContainerIdentifier) { rootPath = url.path } else { log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.") rootPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]) } super.init(rootPath: URL(fileURLWithPath: rootPath).appendingPathComponent(profileDirName).path) } } /** * This exists because the Sync code is extension-safe, and thus doesn't get * direct access to UIApplication.sharedApplication, which it would need to * display a notification. * This will also likely be the extension point for wipes, resets, and * getting access to data sources during a sync. */ let TabSendURLKey = "TabSendURL" let TabSendTitleKey = "TabSendTitle" let TabSendCategory = "TabSendCategory" enum SentTabAction: String { case View = "TabSendViewAction" case Bookmark = "TabSendBookmarkAction" case ReadingList = "TabSendReadingListAction" } /** * A Profile manages access to the user's data. */ protocol Profile: class { var bookmarks: BookmarksModelFactorySource & ShareToDestination & SyncableBookmarks & LocalItemSource & MirrorItemSource { get } // var favicons: Favicons { get } var prefs: NSUserDefaultsPrefs { get } var queue: TabQueue { get } var searchEngines: SearchEngines { get } var files: FileAccessor { get } var history: BrowserHistory & SyncableHistory & ResettableSyncStorage { get } var favicons: Favicons { get } var readingList: ReadingListService? { get } var logins: BrowserLogins & SyncableLogins & ResettableSyncStorage { get } var certStore: CertStore { get } func shutdown() func reopen() // I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter. // Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>. func localName() -> String } open class BrowserProfile: Profile { fileprivate let name: String fileprivate let keychain: KeychainWrapper internal let files: FileAccessor weak fileprivate var app: UIApplication? /** * N.B., BrowserProfile is used from our extensions, often via a pattern like * * BrowserProfile(…).foo.saveSomething(…) * * This can break if BrowserProfile's initializer does async work that * subsequently — and asynchronously — expects the profile to stick around: * see Bug 1218833. Be sure to only perform synchronous actions here. */ init(localName: String, app: UIApplication?) { log.debug("Initing profile \(localName) on thread \(Thread.current).") self.name = localName self.files = ProfileFileAccessor(localName: localName) self.app = app let baseBundleIdentifier = AppInfo.baseBundleIdentifier if !baseBundleIdentifier.isEmpty { self.keychain = KeychainWrapper(serviceName: baseBundleIdentifier) } else { log.error("Unable to get the base bundle identifier. Keychain data will not be shared.") self.keychain = KeychainWrapper.standard } let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(BrowserProfile.onProfileDidFinishSyncing(_:)), name: NotificationProfileDidFinishSyncing, object: nil) notificationCenter.addObserver(self, selector: #selector(BrowserProfile.onPrivateDataClearedHistory(_:)), name: NotificationPrivateDataClearedHistory, object: nil) // If the profile dir doesn't exist yet, this is first run (for this profile). if !files.exists("") { log.info("New profile. Removing old account metadata.") self.removeAccountMetadata() self.removeExistingAuthenticationInfo() prefs.clearAll() } // Always start by needing invalidation. // This is the same as self.history.setTopSitesNeedsInvalidation, but without the // side-effect of instantiating SQLiteHistory (and thus BrowserDB) on the main thread. prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid) } // Extensions don't have a UIApplication. convenience init(localName: String) { self.init(localName: localName, app: nil) } func reopen() { log.debug("Reopening profile.") if dbCreated { db.reopenIfClosed() } if loginsDBCreated { loginsDB.reopenIfClosed() } } func shutdown() { log.debug("Shutting down profile.") if self.dbCreated { db.forceClose() } if self.loginsDBCreated { loginsDB.forceClose() } } func onLocationChange(_ info: [String : AnyObject]) { if let v = info["visitType"] as? Int, let visitType = VisitType(rawValue: v), let url = info["url"] as? URL, !isIgnoredURL(url), let title = info["title"] as? NSString { // Only record local vists if the change notification originated from a non-private tab if !(info["isPrivate"] as? Bool ?? false) { // We don't record a visit if no type was specified -- that means "ignore me". let site = Site(url: url.absoluteString, title: title as String) let visit = SiteVisit(site: site, date: Date.nowMicroseconds(), type: visitType) succeed().upon() { _ in // move off main thread self.history.addLocalVisit(visit) } } history.setTopSitesNeedsInvalidation() } else { log.debug("Ignoring navigation.") } } // These selectors run on which ever thread sent the notifications (not the main thread) @objc func onProfileDidFinishSyncing(_ notification: Notification) { history.setTopSitesNeedsInvalidation() } @objc func onPrivateDataClearedHistory(_ notification: Notification) { // Immediately invalidate the top sites cache // Brave does not use, profile sqlite store for sites // history.refreshTopSitesCache() } deinit { log.debug("Deiniting profile \(self.localName).") NotificationCenter.default.removeObserver(self, name: NotificationPrivateDataClearedHistory, object: nil) } func localName() -> String { return name } lazy var queue: TabQueue = { withExtendedLifetime(self.history) { return SQLiteQueue(db: self.db) } }() fileprivate var dbCreated = false lazy var db: BrowserDB = { let value = BrowserDB(filename: "browser.db", files: self.files) self.dbCreated = true return value }() /** * Favicons, history, and bookmarks are all stored in one intermeshed * collection of tables. * * Any other class that needs to access any one of these should ensure * that this is initialized first. */ fileprivate lazy var places: BrowserHistory & Favicons & SyncableHistory & ResettableSyncStorage = { return SQLiteHistory(db: self.db, prefs: self.prefs) }() var favicons: Favicons { return self.places } var history: BrowserHistory & SyncableHistory & ResettableSyncStorage { return self.places } lazy var bookmarks: BookmarksModelFactorySource & ShareToDestination & SyncableBookmarks & LocalItemSource & MirrorItemSource = { // Make sure the rest of our tables are initialized before we try to read them! // This expression is for side-effects only. withExtendedLifetime(self.places) { return MergedSQLiteBookmarks(db: self.db) } }() lazy var mirrorBookmarks: BookmarkBufferStorage & BufferItemSource = { // Yeah, this is lazy. Sorry. return self.bookmarks as! MergedSQLiteBookmarks }() lazy var searchEngines: SearchEngines = { return SearchEngines(prefs: self.prefs) }() func makePrefs() -> NSUserDefaultsPrefs { return NSUserDefaultsPrefs(prefix: self.localName()) } lazy var prefs: NSUserDefaultsPrefs = { return self.makePrefs() }() lazy var readingList: ReadingListService? = { return ReadingListService(profileStoragePath: self.files.rootPath as String) }() lazy var remoteClientsAndTabs: RemoteClientsAndTabs & ResettableSyncStorage & AccountRemovalDelegate = { return SQLiteRemoteClientsAndTabs(db: self.db) }() lazy var certStore: CertStore = { return CertStore() }() open func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return self.remoteClientsAndTabs.getClientsAndTabs() } @discardableResult func storeTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> { return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs) } lazy var logins: BrowserLogins & SyncableLogins & ResettableSyncStorage = { return SQLiteLogins(db: self.loginsDB) }() // This is currently only used within the dispatch_once block in loginsDB, so we don't // have to worry about races giving us two keys. But if this were ever to be used // elsewhere, it'd be unsafe, so we wrap this in a dispatch_once, too. fileprivate lazy var loginsKey: String? = { let key = "sqlcipher.key.logins.db" if self.keychain.hasValue(forKey: key) { return KeychainWrapper.standard.string(forKey: key) } let Length: UInt = 256 let secret = Bytes.generateRandomBytes(Length).base64EncodedString self.keychain.set(secret, forKey: key) return secret }() fileprivate var loginsDBCreated = false fileprivate lazy var loginsDB: BrowserDB = { struct Singleton { static var instance: BrowserDB! } Singleton.instance = BrowserDB(filename: "logins.db", secretKey: self.loginsKey, files: self.files) self.loginsDBCreated = true return Singleton.instance }() func removeAccountMetadata() { self.prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime) self.keychain.removeObject(forKey: self.name + ".account") } func removeExistingAuthenticationInfo() { self.keychain.setAuthenticationInfo(nil) } }
mpl-2.0
ac277836db0798f1b6293e44fd6f1565
34.787879
171
0.671634
5.121422
false
false
false
false
mattfenwick/TodoRx
TodoRx/TodoFlow/TodoFlowPresenter.swift
1
4479
// // TodoFlowPresenter.swift // TodoRx // // Created by Matt Fenwick on 7/19/17. // Copyright © 2017 mf. All rights reserved. // import Foundation import RxSwift import RxCocoa class TodoFlowPresenter: TodoListInteractor, CreateTodoInteractor, EditTodoInteractor { private let todoModel: Driver<TodoModel> private let commandSubject = PublishSubject<TodoCommand>() private let disposeBag = DisposeBag() private let accumulator: (TodoModel, TodoCommand) -> (TodoModel, Observable<TodoCommand>?) init(interactor: TodoFlowInteractor) { let commands = commandSubject .asDriver { error in assert(false, "this should never happen -- \(error)") return Driver.empty() } .startWith(.initialState) .startWith(.fetchSavedTodos) let accumulator = todoFlowAccumulator(interactor: interactor) let todoOutput: Driver<(TodoModel, Observable<TodoCommand>?)> = commands.scan( (TodoModel.empty, nil), accumulator: { old, command in accumulator(old.0, command) }) self.accumulator = accumulator todoModel = todoOutput.map { tuple in tuple.0 } let states: Driver<(TodoState, TodoState)> = todoModel .map { $0.state } .scan((TodoState.todoList, TodoState.todoList), accumulator: { previous, current in (previous.1, current) }) presentCreateItemView = states .map { (pair: (TodoState, TodoState)) -> Void? in switch pair { case (.todoList, .create): return () default: return nil } } .filterNil() dismissCreateItemView = states .map { (pair: (TodoState, TodoState)) -> Void? in switch pair { case (.create, .todoList): return () default: return nil } } .filterNil() presentEditItemView = states .map { (pair: (TodoState, TodoState)) -> EditTodoIntent? in switch pair { case let (.todoList, .edit(item)): return item.editTodo default: return nil } } .filterNil() dismissEditItemView = states .map { (pair: (TodoState, TodoState)) -> Void? in switch pair { case (.edit, .todoList): return () default: return nil } } .filterNil() // 2-part actions that need to get something dumped back into the command/scan loop let feedback: Driver<Observable<TodoCommand>> = todoOutput .map { tuple in tuple.1 } .filterNil() feedback .flatMap { $0.asDriver(onErrorRecover: { error in assert(false, "unexpected error: \(error)") return Driver.empty() }) } .drive(onNext: commandSubject.onNext) .disposed(by: disposeBag) } // MARK: - for the flow controller let presentCreateItemView: Driver<Void> let dismissCreateItemView: Driver<Void> let presentEditItemView: Driver<EditTodoIntent> let dismissEditItemView: Driver<Void> // MARK: - EditTodoInteractor func editTodoDidTapCancel() { commandSubject.onNext(.cancelEdit) } func editTodoDidTapSave(item: EditTodoIntent) { commandSubject.onNext(.updateItem(item)) } // MARK: - CreateTodoInteractor func createTodoCancel() { commandSubject.onNext(.cancelCreate) } func createTodoSave(item: CreateTodoIntent) { commandSubject.onNext(.createNewItem(item)) } // MARK: - TodoListInteractor func todoListDidTapItem(id: String) { commandSubject.onNext(.showUpdateView(id: id)) } func todoListShowCreate() { commandSubject.onNext(.showCreateView) } func todoListToggleItemIsFinished(id: String) { commandSubject.onNext(.toggleItemIsFinished(id: id)) } func todoListDeleteItem(id: String) { commandSubject.onNext(.deleteItem(id: id)) } lazy private (set) var todoListItems: Driver<[TodoListItem]> = self.todoModel .map { model in model.items.map { $0.todoListItem } } .distinctUntilChanged(==) }
mit
932c594d9ef622bf8bb8f6c900d5db84
28.655629
94
0.576597
4.703782
false
false
false
false
material-components/material-components-ios
components/Snackbar/tests/unit/SnackbarManagerSwiftTests.swift
2
2284
// Copyright 2017-present the Material Components for iOS 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 XCTest import MaterialComponents.MaterialSnackbar class SnackbarManagerSwiftTests: XCTestCase { override func tearDown() { MDCSnackbarManager.default.dismissAndCallCompletionBlocks(withCategory: nil) super.tearDown() } func testMessagesResumedWhenTokenIsDeallocated() { // Given let expectation = self.expectation(description: "completion") let suspendedMessage = MDCSnackbarMessage(text: "") suspendedMessage.duration = 0.05 suspendedMessage.completionHandler = { (userInitiated) -> Void in expectation.fulfill() } // Encourage the runtime to deallocate the token immediately autoreleasepool { var token = MDCSnackbarManager.default.suspendAllMessages() MDCSnackbarManager.default.show(suspendedMessage) token = nil // When XCTAssertNil(token, "Ensuring that the compiler knows we're reading this variable") } // Then // Swift unit tests are sometimes slower, need to wait a little longer self.waitForExpectations(timeout: 3.0, handler: nil) } func testHasMessagesShowingOrQueued() { let message = MDCSnackbarMessage(text: "foo1") message.duration = 10 MDCSnackbarManager.default.show(message) let expectation = self.expectation(description: "has_shown_message") // We need to dispatch_async in order to assure that the assertion happens after showMessage: // actually displays the message. DispatchQueue.main.async { XCTAssertTrue(MDCSnackbarManager.default.hasMessagesShowingOrQueued()) expectation.fulfill() } self.waitForExpectations(timeout: 3.0, handler: nil) } }
apache-2.0
34bafa6ebda13835efe2413a1ef8e574
33.606061
97
0.738616
4.604839
false
true
false
false
liuCodeBoy/Ant
Ant/Ant/LunTan/Detials/Model/RentOut/LunTanDetialModel.swift
1
3238
// // LunTanDetialModel.swift // Ant // // Created by Weslie on 2017/8/15. // Copyright © 2017年 LiuXinQiang. All rights reserved. // import UIKit import SDWebImage //import MJExtension class LunTanDetialModel: NSObject { var listCellType : Int? var id : NSNumber? var picture: [String]? var title: String? var house_type: String? var house_source: String? var price: String? var rent_way: String? var empty_time: Int? var area: String? var label: String? var content: String? var contact_name: String? var contact_phone: String? var weixin: String? var qq: String? var email: String? //MARK: - 求租 var type: Int? // MARK:- 求职 var education: String? var expect_wage: String? var experience: String? var industry_id: Int? var job_nature: String? var self_info: String? //同城交友 var time: Int? //同城交友 var visa: String? //汽车买卖 var company_address: String? var company_internet: String? var company_name: String? //同城交友 var age: String? var constellation: String? var felling_state: String? var friends_request: String? var height: String? var hometown: String? var job: String? var name: String? var sex: String? var weight: String? // MARK:- 处理完的数据 var labelItems: [String]? lazy var pictureArray: [URL] = [URL]() var checkinTime: String? lazy var connactDict: [[String : String]] = [[String : String]]() var industry: String? var want_job_creat: String? init(dict: [String: AnyObject]){ super.init() setValuesForKeys(dict) //处理模型的数据 // if let pictureArray = picture { // for urlItem in pictureArray { // let url = URL(string: urlItem) // self.pictureArray.append(url!) // } // } if let check = empty_time { checkinTime = Date.createDateString(String(check)) } if let labels = label { labelItems = labels.components(separatedBy: ",") } //联系人信息 if let name = self.contact_name { connactDict.append(["联系人" : name]) } if let phone = self.contact_phone { connactDict.append(["电话" : phone]) } if let weixin = self.weixin { connactDict.append(["微信" : weixin]) } if let qq = self.qq { connactDict.append(["QQ" : qq]) } if let email = self.email { connactDict.append(["邮箱" : email]) } //求职信息 if let industry = self.industry_id { switch industry { case 3: self.industry = "web攻城狮" default: self.industry = "sb" } } if let creat = self.time { want_job_creat = Date.createDateString(String(creat)) } } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
apache-2.0
23d7557746291802197fa83c168cc778
22.870229
74
0.537256
3.948232
false
false
false
false
EstefaniaGilVaquero/ciceIOS
APP_CompartirContacto/SYBContactosTableViewController.swift
1
2268
// // SYBContactosTableViewController.swift // APP_CompartirContacto // // Created by cice on 9/9/16. // Copyright © 2016 cice. All rights reserved. // import UIKit class SYBContactosTableViewController: UITableViewController { //MARK: - VARIABLES LOCALES GLOBALES override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return contactosArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! SYBTableViewCell // Configure the cell... contactosDiccionario = contactosArray.objectAtIndex(indexPath.row) as! NSDictionary let firstName = contactosDiccionario["firstName"] as! String let lastName = contactosDiccionario["lastName"] as! String let description = contactosDiccionario["description"] as! String let imageName = contactosDiccionario["imageName"] as! String let imageCustom = UIImage(named: imageName) cell.myNombreL.text = firstName cell.myApellidoLBL.text = lastName cell.myDescripcionLBL.text = description cell.myImageIV.image = imageCustom return cell } //MARK: - IBACTION }
apache-2.0
194514b8aa583287d38700af75c6133b
32.338235
118
0.679753
5.284382
false
false
false
false
miletliyusuf/VisionDetect
VisionDetect/VisionDetect.swift
1
16931
// // VisionDetect.swift // VisionDetect // // Created by Yusuf Miletli on 8/21/17. // Copyright © 2017 Miletli. All rights reserved. // import Foundation import UIKit import CoreImage import AVFoundation import ImageIO public protocol VisionDetectDelegate: AnyObject { func didNoFaceDetected() func didFaceDetected() func didSmile() func didNotSmile() func didBlinked() func didNotBlinked() func didWinked() func didNotWinked() func didLeftEyeClosed() func didLeftEyeOpened() func didRightEyeClosed() func didRightEyeOpened() } ///Makes every method is optional public extension VisionDetectDelegate { func didNoFaceDetected() { } func didFaceDetected() { } func didSmile() { } func didNotSmile() { } func didBlinked() { } func didNotBlinked() { } func didWinked() { } func didNotWinked() { } func didLeftEyeClosed() { } func didLeftEyeOpened() { } func didRightEyeClosed() { } func didRightEyeOpened() { } } public enum VisionDetectGestures { case face case noFace case smile case noSmile case blink case noBlink case wink case noWink case leftEyeClosed case noLeftEyeClosed case rightEyeClosed case noRightEyeClosed } open class VisionDetect: NSObject { public weak var delegate: VisionDetectDelegate? = nil public enum DetectorAccuracy { case BatterySaving case HigherPerformance } public enum CameraDevice { case ISightCamera case FaceTimeCamera } public typealias TakenImageStateHandler = ((UIImage) -> Void) public var onlyFireNotificatonOnStatusChange : Bool = true public var visageCameraView : UIView = UIView() //Private properties of the detected face that can be accessed (read-only) by other classes. private(set) var faceDetected : Bool? private(set) var faceBounds : CGRect? private(set) var faceAngle : CGFloat? private(set) var faceAngleDifference : CGFloat? private(set) var leftEyePosition : CGPoint? private(set) var rightEyePosition : CGPoint? private(set) var mouthPosition : CGPoint? private(set) var hasSmile : Bool? private(set) var isBlinking : Bool? private(set) var isWinking : Bool? private(set) var leftEyeClosed : Bool? private(set) var rightEyeClosed : Bool? //Private variables that cannot be accessed by other classes in any way. private var faceDetector : CIDetector? private var videoDataOutput : AVCaptureVideoDataOutput? private var videoDataOutputQueue : DispatchQueue? private var cameraPreviewLayer : AVCaptureVideoPreviewLayer? private var captureSession : AVCaptureSession = AVCaptureSession() private let notificationCenter : NotificationCenter = NotificationCenter.default private var currentOrientation : Int? private let stillImageOutput = AVCapturePhotoOutput() private var detectedGestures:[VisionDetectGestures] = [] private var takenImageHandler: TakenImageStateHandler? private var takenImage: UIImage? { didSet { if let image = self.takenImage { takenImageHandler?(image) } } } public init(cameraPosition: CameraDevice, optimizeFor: DetectorAccuracy) { super.init() currentOrientation = convertOrientation(deviceOrientation: UIDevice.current.orientation) switch cameraPosition { case .FaceTimeCamera : self.captureSetup(position: AVCaptureDevice.Position.front) case .ISightCamera : self.captureSetup(position: AVCaptureDevice.Position.back) } var faceDetectorOptions : [String : AnyObject]? switch optimizeFor { case .BatterySaving : faceDetectorOptions = [CIDetectorAccuracy : CIDetectorAccuracyLow as AnyObject] case .HigherPerformance : faceDetectorOptions = [CIDetectorAccuracy : CIDetectorAccuracyHigh as AnyObject] } self.faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: faceDetectorOptions) } public func addTakenImageChangeHandler(handler: TakenImageStateHandler?) { self.takenImageHandler = handler } //MARK: SETUP OF VIDEOCAPTURE public func beginFaceDetection() { self.captureSession.startRunning() setupSaveToCameraRoll() } public func endFaceDetection() { self.captureSession.stopRunning() } private func setupSaveToCameraRoll() { if captureSession.canAddOutput(stillImageOutput) { captureSession.addOutput(stillImageOutput) } } public func saveTakenImageToPhotos() { if let image = self.takenImage { UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) } } public func takeAPicture() { if self.stillImageOutput.connection(with: .video) != nil { let settings = AVCapturePhotoSettings() let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first ?? nil let previewFormat = [String(kCVPixelBufferPixelFormatTypeKey): previewPixelType, String(kCVPixelBufferWidthKey): 160, String(kCVPixelBufferHeightKey): 160] settings.previewPhotoFormat = previewFormat as [String : Any] self.stillImageOutput.capturePhoto(with: settings, delegate: self) } } private func captureSetup(position: AVCaptureDevice.Position) { var captureError: NSError? var captureDevice: AVCaptureDevice? let devices = AVCaptureDevice.DiscoverySession( deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: position ).devices for testedDevice in devices { if ((testedDevice as AnyObject).position == position) { captureDevice = testedDevice } } if (captureDevice == nil) { captureDevice = AVCaptureDevice.default(for: .video) } var deviceInput : AVCaptureDeviceInput? do { if let device = captureDevice { deviceInput = try AVCaptureDeviceInput(device: device) } } catch let error as NSError { captureError = error deviceInput = nil } captureSession.sessionPreset = .high if (captureError == nil) { if let input = deviceInput, captureSession.canAddInput(input) { captureSession.addInput(input) } self.videoDataOutput = AVCaptureVideoDataOutput() self.videoDataOutput?.videoSettings = [ String(kCVPixelBufferPixelFormatTypeKey): Int(kCVPixelFormatType_32BGRA) ] self.videoDataOutput?.alwaysDiscardsLateVideoFrames = true self.videoDataOutputQueue = DispatchQueue(label: "VideoDataOutputQueue") self.videoDataOutput?.setSampleBufferDelegate(self, queue: self.videoDataOutputQueue) if let output = self.videoDataOutput, captureSession.canAddOutput(output) { captureSession.addOutput(output) } } visageCameraView.frame = UIScreen.main.bounds let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.frame = UIScreen.main.bounds previewLayer.videoGravity = .resizeAspectFill visageCameraView.layer.addSublayer(previewLayer) } private func addItemToGestureArray(item:VisionDetectGestures) { if !self.detectedGestures.contains(item) { self.detectedGestures.append(item) } } var options : [String : AnyObject]? //TODO: 🚧 HELPER TO CONVERT BETWEEN UIDEVICEORIENTATION AND CIDETECTORORIENTATION 🚧 private func convertOrientation(deviceOrientation: UIDeviceOrientation) -> Int { var orientation: Int = 0 switch deviceOrientation { case .portrait: orientation = 6 case .portraitUpsideDown: orientation = 2 case .landscapeLeft: orientation = 3 case .landscapeRight: orientation = 4 default : orientation = 1 } return orientation } } // MARK: - AVCapturePhotoCaptureDelegate extension VisionDetect: AVCapturePhotoCaptureDelegate { public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) { if let imageData = photo.fileDataRepresentation(), let image = UIImage(data: imageData) { self.takenImage = image } } } // MARK: - AVCaptureVideoDataOutputSampleBufferDelegate extension VisionDetect: AVCaptureVideoDataOutputSampleBufferDelegate { public func captureOutput( _ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection ) { var sourceImage = CIImage() if takenImage == nil { let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) let opaqueBuffer = Unmanaged<CVImageBuffer>.passUnretained(imageBuffer!).toOpaque() let pixelBuffer = Unmanaged<CVPixelBuffer>.fromOpaque(opaqueBuffer).takeUnretainedValue() sourceImage = CIImage(cvPixelBuffer: pixelBuffer, options: nil) } else { if let ciImage = takenImage?.ciImage { sourceImage = ciImage } } options = [ CIDetectorSmile: true as AnyObject, CIDetectorEyeBlink: true as AnyObject, CIDetectorImageOrientation: 6 as AnyObject ] let features = self.faceDetector!.features(in: sourceImage, options: options) if (features.count != 0) { if (onlyFireNotificatonOnStatusChange == true) { if (self.faceDetected == false) { self.delegate?.didFaceDetected() self.addItemToGestureArray(item: .face) } } else { self.delegate?.didFaceDetected() self.addItemToGestureArray(item: .face) } self.faceDetected = true for feature in features as! [CIFaceFeature] { faceBounds = feature.bounds if (feature.hasFaceAngle) { if (faceAngle != nil) { faceAngleDifference = CGFloat(feature.faceAngle) - faceAngle! } else { faceAngleDifference = CGFloat(feature.faceAngle) } faceAngle = CGFloat(feature.faceAngle) } if (feature.hasLeftEyePosition) { leftEyePosition = feature.leftEyePosition } if (feature.hasRightEyePosition) { rightEyePosition = feature.rightEyePosition } if (feature.hasMouthPosition) { mouthPosition = feature.mouthPosition } if (feature.hasSmile) { if (onlyFireNotificatonOnStatusChange == true) { if (self.hasSmile == false) { self.delegate?.didSmile() self.addItemToGestureArray(item: .smile) } } else { self.delegate?.didSmile() self.addItemToGestureArray(item: .smile) } hasSmile = feature.hasSmile } else { if (onlyFireNotificatonOnStatusChange == true) { if (self.hasSmile == true) { self.delegate?.didNotSmile() self.addItemToGestureArray(item: .noSmile) } } else { self.delegate?.didNotSmile() self.addItemToGestureArray(item: .noSmile) } hasSmile = feature.hasSmile } if (feature.leftEyeClosed || feature.rightEyeClosed) { if (onlyFireNotificatonOnStatusChange == true) { if (self.isWinking == false) { self.delegate?.didWinked() self.addItemToGestureArray(item: .wink) } } else { self.delegate?.didWinked() self.addItemToGestureArray(item: .wink) } isWinking = true if (feature.leftEyeClosed) { if (onlyFireNotificatonOnStatusChange == true) { if (self.leftEyeClosed == false) { self.delegate?.didLeftEyeClosed() self.addItemToGestureArray(item: .leftEyeClosed) } } else { self.delegate?.didLeftEyeClosed() self.addItemToGestureArray(item: .leftEyeClosed) } leftEyeClosed = feature.leftEyeClosed } if (feature.rightEyeClosed) { if (onlyFireNotificatonOnStatusChange == true) { if (self.rightEyeClosed == false) { self.delegate?.didRightEyeClosed() self.addItemToGestureArray(item: .rightEyeClosed) } } else { self.delegate?.didRightEyeClosed() self.addItemToGestureArray(item: .rightEyeClosed) } rightEyeClosed = feature.rightEyeClosed } if (feature.leftEyeClosed && feature.rightEyeClosed) { if (onlyFireNotificatonOnStatusChange == true) { if (self.isBlinking == false) { self.delegate?.didBlinked() self.addItemToGestureArray(item: .blink) } } else { self.delegate?.didBlinked() self.addItemToGestureArray(item: .blink) } isBlinking = true } } else { if (onlyFireNotificatonOnStatusChange == true) { if (self.isBlinking == true) { self.delegate?.didNotBlinked() self.addItemToGestureArray(item: .noBlink) } if (self.isWinking == true) { self.delegate?.didNotWinked() self.addItemToGestureArray(item: .noWink) } if (self.leftEyeClosed == true) { self.delegate?.didLeftEyeOpened() self.addItemToGestureArray(item: .noLeftEyeClosed) } if (self.rightEyeClosed == true) { self.delegate?.didRightEyeOpened() self.addItemToGestureArray(item: .noRightEyeClosed) } } else { self.delegate?.didNotBlinked() self.addItemToGestureArray(item: .noBlink) self.delegate?.didNotWinked() self.addItemToGestureArray(item: .noWink) self.delegate?.didLeftEyeOpened() self.addItemToGestureArray(item: .noLeftEyeClosed) self.delegate?.didRightEyeOpened() self.addItemToGestureArray(item: .noRightEyeClosed) } isBlinking = false isWinking = false leftEyeClosed = feature.leftEyeClosed rightEyeClosed = feature.rightEyeClosed } } } else { if (onlyFireNotificatonOnStatusChange == true) { if (self.faceDetected == true) { self.delegate?.didNoFaceDetected() self.addItemToGestureArray(item: .noFace) } } else { self.delegate?.didNoFaceDetected() self.addItemToGestureArray(item: .noFace) } self.faceDetected = false } } }
mit
b80bfdfebb94868b8ecd10bcd0581505
34.704641
124
0.564287
5.475251
false
false
false
false
rnystrom/GitHawk
Classes/Issues/Labels/IssueLabelsSectionController.swift
1
3786
// // IssueLabelsSectionController.swift // Freetime // // Created by Ryan Nystrom on 5/20/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import IGListKit protocol IssueLabelTapSectionControllerDelegate: class { func didTapIssueLabel(owner: String, repo: String, label: String) } final class IssueLabelsSectionController: ListBindingSectionController<IssueLabelsModel>, ListBindingSectionControllerDataSource, ListBindingSectionControllerSelectionDelegate { private let issue: IssueDetailsModel private var sizeCache = [String: CGSize]() private let lockedModel = Constants.Strings.locked private weak var tapDelegate: IssueLabelTapSectionControllerDelegate? init(issue: IssueDetailsModel, tapDelegate: IssueLabelTapSectionControllerDelegate) { self.issue = issue self.tapDelegate = tapDelegate super.init() minimumInteritemSpacing = Styles.Sizes.labelSpacing minimumLineSpacing = Styles.Sizes.labelSpacing let row = Styles.Sizes.rowSpacing inset = UIEdgeInsets(top: row, left: 0, bottom: row/2, right: 0) dataSource = self selectionDelegate = self } // MARK: ListBindingSectionControllerDataSource func sectionController( _ sectionController: ListBindingSectionController<ListDiffable>, viewModelsFor object: Any ) -> [ListDiffable] { guard let object = self.object else { return [] } var viewModels: [ListDiffable] = [object.status] if object.locked { viewModels.append(lockedModel as ListDiffable) } viewModels += object.labels as [ListDiffable] return viewModels } func sectionController( _ sectionController: ListBindingSectionController<ListDiffable>, sizeForViewModel viewModel: Any, at index: Int ) -> CGSize { let key: String if let viewModel = viewModel as? RepositoryLabel { key = viewModel.name } else { if let viewModel = viewModel as? IssueLabelStatusModel { key = "status-\(viewModel.status.title)" } else { key = "locked-key" } } if let size = sizeCache[key] { return size } let size: CGSize if let viewModel = viewModel as? RepositoryLabel { size = LabelListCell.size(viewModel.name) } else { if let viewModel = viewModel as? IssueLabelStatusModel { size = IssueLabelStatusCell.size(viewModel.status.title) } else { size = IssueLabelStatusCell.size(lockedModel) } } sizeCache[key] = size return size } func sectionController( _ sectionController: ListBindingSectionController<ListDiffable>, cellForViewModel viewModel: Any, at index: Int ) -> UICollectionViewCell & ListBindable { let cellType: AnyClass switch viewModel { case is RepositoryLabel: cellType = LabelListCell.self default: cellType = IssueLabelStatusCell.self } guard let cell = collectionContext?.dequeueReusableCell(of: cellType, for: self, at: index) as? UICollectionViewCell & ListBindable else { fatalError("Missing context or wrong cell") } return cell } // MARK: ListBindingSectionControllerSelectionDelegate func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, didSelectItemAt index: Int, viewModel: Any) { guard let viewModel = viewModel as? RepositoryLabel else { return } tapDelegate?.didTapIssueLabel(owner: issue.owner, repo: issue.repo, label: viewModel.name) } }
mit
4e51cfa41db101e0de5c9ec3e8c29524
33.724771
139
0.660766
5.163711
false
false
false
false