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
yanniks/Robonect-iOS
Robonect/Views/Notifications/ShowMessage.swift
1
2300
// // Copyright (C) 2017 Yannik Ehlert. // // 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. // // // ShowMessage.swift // Robonect // // Created by Yannik Ehlert on 16.06.17. // import Foundation import RMessage public class ShowMessage { public enum NotificationMessageType: String { case mowerStarted = "Mower started" case mowerStopped = "Mower stopped" case actionFailed = "Action failed" case modeAccepted = "Mode accepted" case custom = "CUSTOM" var rmessageType: RMessageType { switch self { case .mowerStarted: return .success case .mowerStopped: return .success case .actionFailed: return .error case .modeAccepted: return .success default: return .normal } } } public static func showMessage(message: NotificationMessageType, customMessage: String? = nil) { let messageText : String? = message == .custom ? customMessage : message.rawValue RMessage.showNotification(withTitle: messageText, type: message.rmessageType, customTypeName: nil) { _ in } } }
mit
015de7da3ed19651f87035d99b59c965
36.704918
113
0.66087
4.545455
false
false
false
false
tad-iizuka/swift-sdk
Source/AlchemyLanguageV1/Models/DocumentAuthors.swift
3
1326
/** * Copyright IBM Corporation 2015 * * 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 RestKit /** **DocumentAuthors** Response object for Author related calls */ public struct DocumentAuthors: JSONDecodable { /** the url information was requested for */ public let url: String /** see **Authors** */ public let authors: Authors /// Used internally to initialize a DocumentAuthors object public init(json: JSON) throws { let status = try json.getString(at: "status") guard status == "OK" else { throw JSON.Error.valueNotConvertible(value: json, to: DocumentAuthors.self) } url = try json.getString(at: "url") authors = try json.decode(at: "authors", type: Authors.self) } }
apache-2.0
aabe2e40a3c7bd042f2cb7361c48c5ae
27.212766
87
0.677225
4.376238
false
false
false
false
Intercambio/CloudUI
CloudUI/CloudUI/FormViewController.swift
1
4115
// // FormViewController.swift // CloudUI // // Created by Tobias Kräntzer on 08.02.17. // Copyright © 2017 Tobias Kräntzer. All rights reserved. // import UIKit import Fountain class FormViewController: UITableViewController, UITableViewDelegateCellAction { var dataSource: FormDataSource? { didSet { tableViewAdapter?.dataSource = dataSource } } private var tableViewAdapter: FTTableViewAdapter? override func viewDidLoad() { super.viewDidLoad() tableView.allowsSelection = false tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 45 tableViewAdapter = FTTableViewAdapter(tableView: tableView) tableView.register(FormValueItemCell.self, forCellReuseIdentifier: "FormValueItemCell") tableViewAdapter?.forRowsMatching( FormValueItemCell.predicate, useCellWithReuseIdentifier: "FormValueItemCell" ) { view, item, _, _ in if let cell = view as? FormValueItemCell, let formItem = item as? FormValueItem { cell.item = formItem } } tableView.register(FormTextItemCell.self, forCellReuseIdentifier: "FormTextItemCell") tableViewAdapter?.forRowsMatching( FormTextItemCell.predicate, useCellWithReuseIdentifier: "FormTextItemCell" ) { view, item, _, _ in if let cell = view as? FormTextItemCell, let formItem = item as? FormTextItem { cell.item = formItem } } tableView.register(FormPasswordItemCell.self, forCellReuseIdentifier: "FormPasswordItemCell") tableViewAdapter?.forRowsMatching( FormPasswordItemCell.predicate, useCellWithReuseIdentifier: "FormPasswordItemCell" ) { view, item, _, _ in if let cell = view as? FormPasswordItemCell, let formItem = item as? FormPasswordItem { cell.item = formItem } } tableView.register(FormURLItemCell.self, forCellReuseIdentifier: "FormURLItemCell") tableViewAdapter?.forRowsMatching( FormURLItemCell.predicate, useCellWithReuseIdentifier: "FormURLItemCell" ) { view, item, _, _ in if let cell = view as? FormURLItemCell, let formItem = item as? FormURLItem { cell.item = formItem } } tableView.register(FormButtonItemCell.self, forCellReuseIdentifier: "FormButtonItemCell") tableViewAdapter?.forRowsMatching( FormButtonItemCell.predicate, useCellWithReuseIdentifier: "FormButtonItemCell" ) { view, item, _, _ in if let cell = view as? FormButtonItemCell, let formItem = item as? FormButtonItem { cell.item = formItem } } tableViewAdapter?.delegate = self tableViewAdapter?.dataSource = dataSource } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let sectionItem = dataSource?.sectionItem(forSection: UInt(section)) as? FormSection { return sectionItem.title } else { return nil } } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if let sectionItem = dataSource?.sectionItem(forSection: UInt(section)) as? FormSection { return sectionItem.instructions } else { return nil } } public func tableView(_: UITableView, setValue value: Any?, forRowAt indexPath: IndexPath) { dataSource?.setValue(value, forItemAt: indexPath) } public override func tableView(_: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender _: Any?) { dataSource?.performAction(action, forItemAt: indexPath) } }
gpl-3.0
f632d1089235eda4f58679f4c0ba4329
35.389381
135
0.620136
5.410526
false
false
false
false
PopovVadim/PVDSwiftAddOns
PVDSwiftAddOns/Classes/Extensions/UIKit/UIApplicationExtension.swift
1
884
// // UIApplicationExtension.swift // Pods-PVDSwiftAddOns_Tests // // Created by Вадим Попов on 10/24/17. // import Foundation /** * * */ public extension UIApplication { /** */ class func topVC(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let navigationController = controller as? UINavigationController { return topVC(controller: navigationController.visibleViewController) } if let tabController = controller as? UITabBarController { if let selected = tabController.selectedViewController { return topVC(controller: selected) } } if let presented = controller?.presentedViewController { return topVC(controller: presented) } return controller } }
mit
44af045e682a5b3699ba9824e0758a81
25.484848
127
0.643021
5.29697
false
false
false
false
boqian2000/swift-algorithm-club
Array2D/Array2D.playground/Contents.swift
2
1375
/* Two-dimensional array with a fixed number of rows and columns. This is mostly handy for games that are played on a grid, such as chess. Performance is always O(1). */ public struct Array2D<T> { public let columns: Int public let rows: Int fileprivate var array: [T] public init(columns: Int, rows: Int, initialValue: T) { self.columns = columns self.rows = rows array = .init(repeatElement(initialValue, count: rows*columns)) } public subscript(column: Int, row: Int) -> T { get { return array[row*columns + column] } set { array[row*columns + column] = newValue } } } // initialization var matrix = Array2D(columns: 3, rows: 5, initialValue: 0) // makes an array of rows * columns elements all filled with zero print(matrix.array) // setting numbers using subscript [x, y] matrix[0, 0] = 1 matrix[1, 0] = 2 matrix[0, 1] = 3 matrix[1, 1] = 4 matrix[0, 2] = 5 matrix[1, 2] = 6 matrix[0, 3] = 7 matrix[1, 3] = 8 matrix[2, 3] = 9 // now the numbers are set in the array print(matrix.array) // print out the 2D array with a reference around the grid for i in 0..<matrix.rows { print("[", terminator: "") for j in 0..<matrix.columns { if j == matrix.columns - 1 { print("\(matrix[j, i])", terminator: "") } else { print("\(matrix[j, i]) ", terminator: "") } } print("]") }
mit
f0a1074cd6baef3ef0d103eaf3e83dae
20.825397
74
0.627636
3.266033
false
false
false
false
Sajjon/ViewComposer
Source/Classes/ViewAttribute/AttributedValues/DataSourceOwner.swift
1
1525
// // DataSourceOwner.swift // ViewComposer // // Created by Alexander Cyon on 2017-06-11. // // import Foundation protocol DataSourceOwner: class { var dataSourceProxy: NSObjectProtocol? { get set } } internal extension DataSourceOwner { func apply(_ style: ViewStyle) { style.attributes.forEach { switch $0 { case .dataSource(let dataSource): dataSourceProxy = dataSource case .dataSourceDelegate(let dataSource): dataSourceProxy = dataSource default: break } } } } extension UITableView: DataSourceOwner { var dataSourceProxy: NSObjectProtocol? { get { return self.dataSource } set { guard let specificDataSource = newValue as? UITableViewDataSource else { return } self.dataSource = specificDataSource } } } extension UICollectionView: DataSourceOwner { var dataSourceProxy: NSObjectProtocol? { get { return self.dataSource } set { guard let specificDataSource = newValue as? UICollectionViewDataSource else { return } self.dataSource = specificDataSource } } } extension UIPickerView: DataSourceOwner { var dataSourceProxy: NSObjectProtocol? { get { return self.dataSource } set { guard let specificDataSource = newValue as? UIPickerViewDataSource else { return } self.dataSource = specificDataSource } } }
mit
abb3511d58297c6673d77e11b5c37529
25.293103
98
0.622951
5.295139
false
false
false
false
EBGToo/SBVariables
Sources/Variable.swift
1
4022
// // Variable.swift // SBVariables // // Created by Ed Gamble on 10/22/15. // Copyright © 2015 Edward B. Gamble Jr. All rights reserved. // // See the LICENSE file at the project root for license information. // See the CONTRIBUTORS file at the project root for a list of contributors. // import SBUnits public struct VariableDelegate<Value> { public var canAssign = { (variable: Variable<Value>, value:Value) -> Bool in return true } public var didAssign = { (variable: Variable<Value>, value:Value) -> Void in return } public var didNotAssign = { (variable: Variable<Value>, value:Value) -> Void in return } public init ( canAssign : ((_ variable: Variable<Value>, _ value:Value) -> Bool)?, didAssign : ((_ variable: Variable<Value>, _ value:Value) -> Void)? = nil, didNotAssign : ((_ variable: Variable<Value>, _ value:Value) -> Void)? = nil) { self.canAssign = canAssign ?? self.canAssign self.didAssign = didAssign ?? self.didAssign self.didNotAssign = didNotAssign ?? self.didNotAssign } public init () {} } /// /// A Variable is a Nameable, MonitoredObject that holds a time-series of values in a Domain. The /// variable's value is updated when assigned; if the assigned value is not in the domain then ...; /// if the variable's delegate returns `false` for `canAssign:variable:value` then ... If a /// `History<Value>` is associated with the variable then upon assignemet, the history is extended. /// public class Variable<Value> : MonitoredObject<Value>, Nameable { /// The variable name public let name : String /// The variable domain public let domain : Domain<Value> /// The variable value public internal(set) var value : Value /// The variable time of last assignment public internal(set) var time : Quantity<Time> /// The variable delegate public var delegate : VariableDelegate<Value> /// The optional variable history public internal(set) var history : History<Value>? /// Initialize an instance. This is `Optional` because the provided `value` must be in `domain` /// for the initialization to succeeed. /// /// - parameter name: /// - parameter time: /// - parameter value: /// - parameter domain: /// - parameter history: /// - parameter delegate /// public init? (name: String, time:Quantity<Time>, value: Value, domain: Domain<Value>, history : History<Value>? = nil, delegate : VariableDelegate<Value> = VariableDelegate<Value>()) { // Initialize everything - even though we've not checked domain.contains(value) yet self.name = name self.value = value self.time = time; self.domain = domain self.delegate = delegate self.history = history // Required after everything initialized and before anything more. super.init() // Ensure `domain` contains `value` guard domain.contains(value) else { return nil } // Formalize the assignment assign(value, time: time) } /// /// Assign `value`. /// /// - parameter value: /// - parameter time: /// public func assign (_ value: Value, time:Quantity<Time>) { guard domain.contains(value) && delegate.canAssign(self, value) else { delegate.didNotAssign(self, value) return } self.value = value history?.extend (time, value: value) updateMonitorsFor(value) delegate.didAssign(self, value) } } /// /// A QuantityVariable is a Variable with value of type Quantity<D> where D is an Dimension (such /// as Length, Time or Mass). /// public class QuantityVariable<D:SBUnits.Dimension> : Variable<Quantity<D>> { public override init? (name: String, time:Quantity<Time>, value: Quantity<D>, domain: Domain<Quantity<D>>, history : History<Quantity<D>>? = nil, delegate : VariableDelegate<Quantity<D>> = VariableDelegate<Quantity<D>>()) { super.init(name: name, time: time, value: value, domain: domain, history: history, delegate: delegate) } }
mit
a391789d60b75450805537ce0ac37b98
31.959016
108
0.665257
4.008973
false
false
false
false
sammy0025/SST-Announcer
SST Announcer/Custom Classes/DateExtensions.swift
1
2029
// // DateExtensions.swift // SST Announcer // // Created by Pan Ziyue on 29/11/16. // Copyright © 2016 FourierIndustries. All rights reserved. // import Foundation extension DateFormatter { /// Initialises a DateFormatter object with a `en_US_POSIX` locale /// - returns: A `DateFormatter` object with a "safe" locale public class func initWithSafeLocale() -> DateFormatter { let df = DateFormatter() let locale = Locale(identifier: "en_US_POSIX") df.locale = locale return df } } extension Date { /// Decodes a date to ___ mins ago or ___ hrs ago. If all else fails, /// this method will decode the date to a yyyy/MM/dd format (ISO 8601) /// - returns: An optional `String` that represents how much time passed public func decodeToTimeAgo() -> String { let calendar = Calendar(identifier: .gregorian) let dateToDecode = calendar.startOfDay(for: self) let currentDate = calendar.startOfDay(for: Date()) let components = calendar.dateComponents([.day], from: dateToDecode, to: currentDate) let difference = components.day! if difference < 1 { return "Today" } else if difference < 14 { switch difference { case 1: return "Yesterday" default: return "\(difference) days" } } else { let dateFormatter = DateFormatter.initWithSafeLocale() dateFormatter.dateFormat = "d.M.yy" return dateFormatter.string(from: dateToDecode) } } } func <= (lhs: NSDate, rhs: NSDate) -> Bool { return lhs.timeIntervalSince1970 <= rhs.timeIntervalSince1970 } func >= (lhs: NSDate, rhs: NSDate) -> Bool { return lhs.timeIntervalSince1970 >= rhs.timeIntervalSince1970 } func > (lhs: NSDate, rhs: NSDate) -> Bool { return lhs.timeIntervalSince1970 > rhs.timeIntervalSince1970 } func < (lhs: NSDate, rhs: NSDate) -> Bool { return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970 } func == (lhs: NSDate, rhs: NSDate) -> Bool { return lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970 }
gpl-2.0
5bdb1c5cbb32e31e813bc0a81b1e6ba5
27.166667
89
0.680473
4.047904
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/General/SwiftUI Views/FadingScrollView.swift
1
2979
// // FadingScrollView.swift // PennMobile // // Created by CHOI Jongmin on 5/7/2020. // Copyright © 2020 PennLabs. All rights reserved. // import SwiftUI struct FadingScrollView<Content: View>: View { let fadeDistance: CGFloat let axes: Axis.Set let showsIndicators: Bool let content: Content init( fadeDistance: CGFloat, _ axes: Axis.Set = .horizontal, showsIndicators: Bool = true, @ViewBuilder content: () -> Content ) { self.fadeDistance = fadeDistance self.axes = axes self.showsIndicators = showsIndicators self.content = content() } var body: some View { ZStack(alignment: .leading) { ScrollView(axes, showsIndicators: showsIndicators) { // Pad the content depending on the axes so that bottom or trailing // part of the content isn't faded when scrolling all the way to the end. if axes == .vertical { Spacer(minLength: fadeDistance) content Spacer(minLength: fadeDistance) } else if axes == .horizontal { HStack(spacing: 0) { Spacer(minLength: fadeDistance) content Spacer(minLength: fadeDistance) } } } if axes.contains(.vertical) { VStack { fadeGradient(for: .vertical, startPoint: .top, endPoint: .bottom) .frame(height: fadeDistance) // SwiftUI internally not working .allowsHitTesting(false) Spacer() fadeGradient(for: .vertical, startPoint: .bottom, endPoint: .top) .frame(height: fadeDistance) // SwiftUI internally not working .allowsHitTesting(false) } } if axes.contains(.horizontal) { HStack { fadeGradient(for: .horizontal, startPoint: .leading, endPoint: .trailing) .frame(width: fadeDistance) .allowsHitTesting(false) Spacer() fadeGradient(for: .horizontal, startPoint: .trailing, endPoint: .leading) .frame(width: fadeDistance) .allowsHitTesting(false) } } }.offset(x: -fadeDistance, y: 0) } private func fadeGradient(for axis: Axis, startPoint: UnitPoint, endPoint: UnitPoint) -> some View { return LinearGradient( gradient: Gradient(colors: [ Color(.systemBackground).opacity(1), Color(.systemBackground).opacity(0) ]), startPoint: startPoint, endPoint: endPoint ) } }
mit
a1b460b75bb488713efed35b8008293a
31.369565
104
0.508395
5.280142
false
false
false
false
vectorform/Texty
Source/TextAttribute.swift
1
6668
// Copyright (c) 2018 Vectorform, LLC // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may // be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. import Foundation import UIKit public enum TextAttribute: String { case attachment = "attachment" case backgroundColor = "backgroundColor" case baselineOffset = "baselineOffset" case expansion = "expansion" case font = "font" case foregroundColor = "foregroundColor" case kern = "kern" case ligature = "ligature" case link = "link" case obliqueness = "obliqueness" case paragraphStyle = "paragraphStyle" case shadow = "shadow" case strikethroughColor = "strikethroughColor" case strikethroughStyle = "strikethroughStyle" case strokeColor = "strokeColor" case strokeWidth = "strokeWidth" case textEffect = "textEffect" case underlineColor = "underlineColor" case underlineStyle = "underlineStyle" case verticalGlyphForm = "verticalGlyphForm" case writingDirection = "writingDirection" /** macOS **/ // case cursor // case markedClauseSegment // case spellingState // case superscript // case textAlternatives // case toolTip internal var NSAttribute: NSAttributedString.Key { switch(self) { case .attachment: return NSAttributedString.Key.attachment case .backgroundColor: return NSAttributedString.Key.backgroundColor case .baselineOffset: return NSAttributedString.Key.baselineOffset case .expansion: return NSAttributedString.Key.expansion case .font: return NSAttributedString.Key.font case .foregroundColor: return NSAttributedString.Key.foregroundColor case .kern: return NSAttributedString.Key.kern case .ligature: return NSAttributedString.Key.ligature case .link: return NSAttributedString.Key.link case .obliqueness: return NSAttributedString.Key.obliqueness case .paragraphStyle: return NSAttributedString.Key.paragraphStyle case .shadow: return NSAttributedString.Key.shadow case .strikethroughColor: return NSAttributedString.Key.strikethroughColor case .strikethroughStyle: return NSAttributedString.Key.strikethroughStyle case .strokeColor: return NSAttributedString.Key.strokeColor case .strokeWidth: return NSAttributedString.Key.strokeWidth case .textEffect: return NSAttributedString.Key.textEffect case .underlineColor: return NSAttributedString.Key.underlineColor case .underlineStyle: return NSAttributedString.Key.underlineStyle case .verticalGlyphForm: return NSAttributedString.Key.verticalGlyphForm case .writingDirection: return NSAttributedString.Key.writingDirection } } internal var properTypeString: String { switch(self) { case .attachment: return "NSTextAttachment" case .font: return "UIFont" case .link: return "NSURL or NSString" case .paragraphStyle: return "NSParagraphStyle" case .shadow: return "NSShadow" case .textEffect: return "NSString" case .writingDirection: return "Array<NSNumber>" case .backgroundColor, .foregroundColor, .strikethroughColor, .strokeColor, .underlineColor: return "UIColor" case .baselineOffset, .expansion, .kern, .ligature, .obliqueness, .strikethroughStyle, .strokeWidth, .underlineStyle, .verticalGlyphForm: return "NSNumber" } } internal static func convertToNative(_ attributes: [TextAttribute : Any]) -> [NSAttributedString.Key: Any] { var convertedAttributes: [NSAttributedString.Key : Any] = [:] attributes.forEach { (key, value) in assert(key.isProperType(object: value), "Texty: value for attribute \"\(key.rawValue)\" is \"\(String(describing: type(of: value)))\" - should be \"\(key.properTypeString)\"") convertedAttributes[key.NSAttribute] = value } return convertedAttributes } internal func isProperType(object: Any) -> Bool { switch(self) { case .attachment: return (object is NSTextAttachment) case .font: return (object is UIFont) case .paragraphStyle: return (object is NSParagraphStyle) case .shadow: return (object is NSShadow) case .textEffect: return (object is NSString) case .writingDirection: return (object is [NSNumber]) case .link: return ((object is NSURL) || (object is NSString)) case .backgroundColor, .foregroundColor, .strikethroughColor, .strokeColor, .underlineColor: return (object is UIColor) case .baselineOffset, .expansion, .kern, .ligature, .obliqueness, .strikethroughStyle, .strokeWidth, .underlineStyle, .verticalGlyphForm: return (object is NSNumber) } } }
bsd-3-clause
135858a37bc015d03e5348c7d790abb4
50.689922
187
0.671416
5.407948
false
false
false
false
billdonner/sheetcheats9
sc9/ArrangeThemeCollectionViewController.swift
1
3638
// // ArrangeThemeCollectionViewController.swift // sc9 // // Created by bill donner on 12/24/15. // Copyright © 2015 shovelreadyapps. All rights reserved. // import UIKit final class ThemeArrangerCell: UICollectionViewCell { @IBOutlet var alphabetLabel: UILabel! } final class ArrangeThemeCollectionViewController: UICollectionViewController { private var newColors : [UIColor] = [] override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let pvc = self.parent as? ThemeArrangerViewController { self.newColors = pvc.newColors } self.installsStandardGestureForInteractiveMovement = true } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return newColors.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ThemeArrangerCellIDx", for: indexPath) as! ThemeArrangerCell // Configure the cell cell.contentView.backgroundColor = newColors[(indexPath as NSIndexPath).item] return cell } override func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { return true } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("Did select item in childviewcontroller") } override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath,to destinationIndexPath: IndexPath) { let temp = newColors[(sourceIndexPath as NSIndexPath).item] // the character //shrink source array newColors.remove(at: (sourceIndexPath as NSIndexPath).item) //insert in dest array newColors.insert(temp, at: (destinationIndexPath as NSIndexPath).item) self.collectionView?.reloadData() } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return false } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { } */ }
apache-2.0
d0dc4c5faadd6eff1d1a8cf664a04934
33.311321
185
0.699753
5.923453
false
false
false
false
vazteam/ProperMediaView
Classes/Category/UIImage+Bundle.swift
1
877
// // UIImage+Bundle.swift // ProperMediaViewDemo // // Created by Murawaki on 2017/03/31. // Copyright © 2017年 Murawaki. All rights reserved. // import Foundation import UIKit public extension UIImage { public static func bundledImage(named: String) -> UIImage? { if let image = UIImage(named: named) { return image } let bundle = Bundle.init(for: self) if let image = UIImage(named: named, in: bundle, compatibleWith: nil){ return image } let frameworkBundle = Bundle(for: ProperMediaView.self) let bundleUrl = frameworkBundle.resourceURL?.appendingPathComponent("ProperMediaView.bundle") let resourceBundle = Bundle(url: bundleUrl!) let image = UIImage(named: named, in: resourceBundle, compatibleWith: nil) return image } }
mit
cedb61c8dba555159097f1dd0e94c050
27.193548
101
0.636156
4.459184
false
false
false
false
BruceFight/JHB_HUDView
JHB_HUDViewExample/ExampleTwoPart/ExampleDiyController.swift
1
4891
// // ExampleDiyController.swift // JHB_HUDViewExample // // Created by Leon_pan on 16/8/23. // Copyright © 2016年 bruce. All rights reserved. // import UIKit class ExampleDiyController: UITableViewController { var SCREEN_WIDTH = UIScreen.main.bounds.size.width var SCREEN_HEIGHT = UIScreen.main.bounds.size.height // 声明一个数组,用来储存cell var cellArr = NSMutableArray() // 标示 var ID = "cell" override func viewDidLoad() { super.viewDidLoad() self.title = "Diy-Type" self.setTableView() } func setTableView() { // 注册cell self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: ID) self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 4 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ID, for: indexPath) cell.textLabel?.numberOfLines = 0 if (indexPath as NSIndexPath).row == 0 { cell.textLabel?.text = "1⃣️JHB_HUDView 显示图片并有可选效果~" }else if (indexPath as NSIndexPath).row == 1{ cell.textLabel?.text = "2⃣️JHB_HUDView 显示图片数组动画~" }else if (indexPath as NSIndexPath).row == 2{ cell.textLabel?.text = "3⃣️JHB_HUDView 显示信息和图片并有可选效果~" }else if (indexPath as NSIndexPath).row == 3{ cell.textLabel?.text = "4⃣️JHB_HUDView 显示信息和图片数组动画~" } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if (indexPath as NSIndexPath).row == 0{ let secondVc = ExampleDiyDetailController() secondVc.diyimgtype = .diyImageTypeJustImage self.navigationController?.pushViewController(secondVc, animated: true) }else if (indexPath as NSIndexPath).row == 1{ let secondVc = ExampleDiyDetailController() secondVc.diyimgtype = .diyImageTypeImageArray self.navigationController?.pushViewController(secondVc, animated: true) }else if (indexPath as NSIndexPath).row == 2{ let secondVc = ExampleDiyDetailController() secondVc.diyimgtype = .diyImageTypeImageWithMsg self.navigationController?.pushViewController(secondVc, animated: true) }else if (indexPath as NSIndexPath).row == 3{ let secondVc = ExampleDiyDetailController() secondVc.diyimgtype = .diyImageTypeImageArrayWithMsg self.navigationController?.pushViewController(secondVc, animated: true) } } // 设置header 和 footer override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = UILabel.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 60)) header.text = "Diy-Type中暂有四种自定义展示类型哦~!😊" header.sizeToFit() header.numberOfLines = 0 header.textColor = UIColor.white header.font = UIFont.systemFont(ofSize: 18) header.textAlignment = NSTextAlignment.center header.backgroundColor = UIColor.orange return header } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let footer = UILabel.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 60)) footer.text = "是的,每种类型都非常的Cool~!❤️关键:支持屏幕旋转!!!😂" footer.sizeToFit() footer.numberOfLines = 0 footer.textColor = UIColor.white footer.font = UIFont.systemFont(ofSize: 18) footer.textAlignment = NSTextAlignment.center footer.backgroundColor = UIColor.orange return footer } // ❤️ 如果要展示header 或 footer 就必须要设置他们的高度值! override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 60 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 60 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 75 } }
mit
0b8ac67b763fff09a2a15377a5b476d7
37.363636
109
0.650797
4.52878
false
false
false
false
volodg/iAsync.utils
Sources/Errors/Error+WriteErrorToNSLog.swift
1
1927
// // NSError+WriteErrorToNSLog.swift // iAsync_utils // // Created by Vladimir Gorbenko on 06.06.14. // Copyright © 2014 EmbeddedSources. All rights reserved. // import Foundation private struct ErrorWithAction { let error : ErrorWithContext let action: (() -> ()) } final private class ActionsHolder { var queue = [ErrorWithAction]() } private var nsLogErrorsQueue = ActionsHolder() private var jLoggerErrorsQueue = ActionsHolder() //todo rename? private func delayedPerformAction(_ error: ErrorWithContext, action: @escaping (() -> ()), queue: ActionsHolder) { if queue.queue.index(where: { $0.error.error === error.error && $0.error.context == error.context }) != nil { return } queue.queue.append(ErrorWithAction(error: error, action: action)) if queue.queue.count == 1 { DispatchQueue.main.async(execute: { let tmpQueue = queue.queue queue.queue.removeAll(keepingCapacity: true) for info in tmpQueue { info.action() } }) } } public func debugOnlyPrint(_ str: String) { if _isDebugAssertConfiguration() { print(str) } } public extension ErrorWithContext { func postToLog() { switch error.logTarget { case .logger: let action = { () in var log = self.error.errorLog log["Context"] = self.context iAsync_utils_logger.logWith(level: .logError, log: log) } delayedPerformAction(self, action: action, queue: jLoggerErrorsQueue) case .console: let action = { () in let log = self.error.errorLog debugOnlyPrint("only log - \(log) context - \(self.context)") } delayedPerformAction(self, action: action, queue: nsLogErrorsQueue) case .nothing: break } } }
mit
7ccfcb1a53e529dedb687a55bb777f20
23.692308
114
0.594496
4.261062
false
false
false
false
Eonil/EditorLegacy
Modules/JSONDataSchemaInferencer/InternalTests/AppDelegate.swift
1
1412
// // AppDelegate.swift // InternalTests // // Created by Hoon H. on 11/16/14. // Copyright (c) 2014 Eonil. All rights reserved. // import Cocoa import Standards @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! func applicationDidFinishLaunching(aNotification: NSNotification) { let p1 = "/Users/Eonil/Workshop/Incubation/Editor/Project/Subprojects/JSONDataSchemaInferencer/InternalTests" // let u = NSURL(string: "file://\(p1)/events.json")! // let u = NSURL(string: "file://\(p1)/example3.json")! // let u = NSURL(string: "file://\(p1)/events2.json")! // let u = NSURL(string: "file://\(p1)/example4.json")! // let u = NSURL(string: "file://\(p1)/example5.json")! let u = NSURL(string: "file://\(p1)/example9.json")! let d = NSData(contentsOfURL: u) let v = JSON.deserialise(d!)! let d2 = inferJSONSchema(v) let ps1 = d2.queryAllPathsForDataType(DiscoveryDataType.Composite) println("Paths for discovered composite types:") for p1 in ps1 { println("# \(p1.pathByStrippingAwayArrayComponents)") let fs1 = d2.queryDirectChildrenOfPath(p1) for f1 in fs1 { println("- \(f1.lastComponent!.fieldName!) = \(d2.pathSampleMap[f1]!.allKeys)") } println("") } } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
mit
ad60c2cb61c40d0c5d4054c16b68c22e
25.641509
111
0.686261
3.036559
false
false
false
false
quire-io/SwiftyChrono
Sources/Parsers/DE/DECasualDateParser.swift
1
2085
// // DECasualDateParser.swift // SwiftyChrono // // Created by Jerry Chen on 2/7/17. // Copyright © 2017 Potix. All rights reserved. // import Foundation private let PATTERN = "(\\W|^)(jetzt|heute|letzte\\s*Nacht|(?:morgen|gestern)\\s*|morgen|gestern)(?=\\W|$)" public class DECasualDateParser: Parser { override var pattern: String { return PATTERN } override var language: Language { return .german } override public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? { let (matchText, index) = matchTextAndIndex(from: text, andMatchResult: match) var result = ParsedResult(ref: ref, index: index, text: matchText) let refMoment = ref var startMoment = refMoment let lowerText = matchText.lowercased() if NSRegularExpression.isMatch(forPattern: "^morgen", in: lowerText) { // Check not "Tomorrow" on late night if refMoment.hour > 1 { startMoment = startMoment.added(1, .day) } } else if NSRegularExpression.isMatch(forPattern: "^gestern", in: lowerText) { startMoment = startMoment.added(-1, .day) } else if NSRegularExpression.isMatch(forPattern: "letzte\\s*Nacht", in: lowerText) { result.start.imply(.hour, to: 0) if refMoment.hour > 6 { startMoment = startMoment.added(-1, .day) } } else if NSRegularExpression.isMatch(forPattern: "jetzt", in: lowerText) { result.start.imply(.hour, to: refMoment.hour) result.start.imply(.minute, to: refMoment.minute) result.start.imply(.second, to: refMoment.second) result.start.imply(.millisecond, to: refMoment.millisecond) } result.start.assign(.day, value: startMoment.day) result.start.assign(.month, value: startMoment.month) result.start.assign(.year, value: startMoment.year) result.tags[.deCasualDateParser] = true return result } }
mit
5f013ac3ec4e84ce096210815ece171e
39.862745
129
0.626679
4.03876
false
false
false
false
cheskapac/JSQMessagesViewController
SwiftExample/SwiftExample/DemoConversation.swift
8
2049
// // DemoConversation.swift // SwiftExample // // Created by Dan Leonard on 5/11/16. // Copyright © 2016 MacMeDan. All rights reserved. // import JSQMessagesViewController // Create Names to display let DisplayNameSquires = "Jesse Squires" let DisplayNameLeonard = "Dan Leonard" let DisplayNameCook = "Tim Cook" let DisplayNameJobs = "Steve Jobs" let DisplayNameWoz = "Steve Wazniak" // Create Unique IDs for avatars let AvatarIDLeonard = "053496-4509-288" let AvatarIDSquires = "053496-4509-289" let AvatarIdCook = "468-768355-23123" let AvatarIdJobs = "707-8956784-57" let AvatarIdWoz = "309-41802-93823" // INFO: Creating Static Demo Data. This is only for the exsample project to show the framework at work. var conversationsList = [Conversation]() var convo = Conversation(firstName: "Steave", lastName: "Jobs", preferredName: "Stevie", smsNumber: "(987)987-9879", id: "33", latestMessage: "Holy Guacamole, JSQ in swift", isRead: false) var conversation = [JSQMessage]() let message = JSQMessage(senderId: AvatarIdCook, displayName: DisplayNameCook, text: "What is this Black Majic?") let message2 = JSQMessage(senderId: AvatarIDSquires, displayName: DisplayNameSquires, text: "It is simple, elegant, and easy to use. There are super sweet default settings, but you can customize like crazy") let message3 = JSQMessage(senderId: AvatarIdWoz, displayName: DisplayNameWoz, text: "It even has data detectors. You can call me tonight. My cell number is 123-456-7890. My website is www.hexedbits.com.") let message4 = JSQMessage(senderId: AvatarIdJobs, displayName: DisplayNameJobs, text: "JSQMessagesViewController is nearly an exact replica of the iOS Messages App. And perhaps, better.") let message5 = JSQMessage(senderId: AvatarIDLeonard, displayName: DisplayNameLeonard, text: "It is unit-tested, free, open-source, and documented.") func makeConversation()->[JSQMessage]{ conversation = [message, message2,message3, message4, message5] return conversation } func getConversation()->[Conversation]{ return [convo] }
mit
c31f40cd53f87b620ab00a68a148837f
44.533333
207
0.76416
3.599297
false
false
false
false
EdenShapiro/tip-calculator-with-yelp-review
SuperCoolTipCalculator/ViewController.swift
1
11790
// // ViewController.swift // SuperCoolTipCalculator // // Created by Eden on 2/3/17. // Copyright © 2017 Eden Shapiro. All rights reserved. // import UIKit import Foundation import CoreLocation import Kanna import Alamofire class ViewController: UIViewController, CLLocationManagerDelegate, UITextFieldDelegate { @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var leaveYelpReviewButton: UIButton! @IBOutlet weak var incorrectLocationButton: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var locationManager: CLLocationManager! var userLocation: CLLocation? var currentBusiness: Business? var tipPercentages: [Double]! var defaultSegment: Int! var businesses: [Business]? var yelpBusinessReviewLink: String? let defaults = UserDefaults.standard let formatter = NumberFormatter() override func viewDidLoad() { super.viewDidLoad() setUpFormatterAndBillField() checkDefaultsForValue() activityIndicator.isHidden = true billField.addTarget(self, action: #selector(textFieldChanged(textField:)), for: .editingChanged) billField.addTarget(self, action: #selector(calculateTip), for: .editingChanged) billField.addTarget(self, action: #selector(textFieldChanged(textField:)), for: .valueChanged) tipControl.addTarget(self, action: #selector(calculateTip), for: .valueChanged) } func setUpFormatterAndBillField(){ billField.delegate = self billField.becomeFirstResponder() billField.keyboardType = .numberPad billField.textAlignment = .right formatter.numberStyle = .currency formatter.locale = Locale.current formatter.currencySymbol = Locale.current.currencySymbol! formatter.currencyCode = Locale.current.currencyCode! } func checkDefaultsForValue(){ let currentTime = NSDate() print("in checkDefaultsForValue") if let lastUsed = defaults.object(forKey: "lastUsed") { let timeSinceLastUsed = currentTime.timeIntervalSinceReferenceDate - (lastUsed as! NSDate).timeIntervalSinceReferenceDate print(timeSinceLastUsed) if timeSinceLastUsed > 600 { defaults.removeObject(forKey: "billField") defaults.synchronize() } } } override func viewWillAppear(_ animated: Bool) { // Set up segmentedcontrol setUpSegmentedControl() // Persist selected segment if let segment = defaults.value(forKey: "defaultSegment"){ defaultSegment = segment as! Int } else { defaultSegment = 1 } tipControl.selectedSegmentIndex = defaultSegment // Check billField for prior value if let billField = defaults.string(forKey: "billField"){ self.billField.text = billField textFieldChanged(textField: self.billField) } else { self.billField.text = formatter.currencySymbol! } calculateTip() // Determine current user location determineMyCurrentLocation() } override func viewWillDisappear(_ animated: Bool) { print("viewWillDisappear") let lastUsed = NSDate() defaults.set(lastUsed, forKey: "lastUsed") if let billField = self.billField.text { print(billField) defaults.set(billField, forKey: "billField") } defaults.synchronize() billField.resignFirstResponder() } func setUpSegmentedControl(){ if let defaultsArray = defaults.array(forKey: "tipPercentages"){ tipPercentages = defaultsArray as! [Double] print("app has run before") } else { tipPercentages = [0.15, 0.20, 0.25] defaults.set(tipPercentages, forKey: "tipPercentages") print("first app run ever") } let segment1 = String(Int(tipPercentages[0]*100)) + "%" let segment2 = String(Int(tipPercentages[1]*100)) + "%" let segment3 = String(Int(tipPercentages[2]*100)) + "%" tipControl.setTitle(segment1, forSegmentAt: 0) tipControl.setTitle(segment2, forSegmentAt: 1) tipControl.setTitle(segment3, forSegmentAt: 2) } func determineMyCurrentLocation() { locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.startUpdatingLocation() locationManager.startMonitoringSignificantLocationChanges() print("startUpdatingLocation") } } // Updated location callback func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { userLocation = locations[0] as CLLocation print("didUpdateLocations called") // TODO: Call stopUpdatingLocation() to stop listening for location updates, // other wise this function will be called every time when user location changes. // manager.stopUpdatingLocation() print("user latitude = \(userLocation!.coordinate.latitude)") print("user longitude = \(userLocation!.coordinate.longitude)") if let userLocation = userLocation { let lat = userLocation.coordinate.latitude let long = userLocation.coordinate.longitude Business.searchWithTerm("", userLocation: (lat, long), sort: YelpSortMode.distance, categories: nil, deals: nil, completion: { (businesses: [Business]?, error: Error?) -> Void in self.businesses = businesses if let businesses = businesses { self.currentBusiness = businesses[0] print(self.currentBusiness!.name!) // TODO: make button prettier. let titleString = NSAttributedString(string: "Leave Yelp review for \(self.currentBusiness.name!)" , attributes: [String : Any]?) self.setLeaveYelpReviewButton(business: self.currentBusiness!) } }) } else { print("Error: userLocation not found.") } } func setLeaveYelpReviewButton(business: Business){ self.leaveYelpReviewButton.setTitle("Leave Yelp review for \(business.name!)", for: .normal) } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Error \(error)") } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } // Called when segmentedcontrol value changes or when bill textfield changed func calculateTip() { let text = billField.text?.replacingOccurrences(of: formatter.currencySymbol, with: "").replacingOccurrences(of: formatter.groupingSeparator, with: "").replacingOccurrences(of: formatter.decimalSeparator, with: "") let double = Double(text!) ?? 0 let bill = Double(double/100.0) let tip = bill * tipPercentages[tipControl.selectedSegmentIndex] let total = bill + tip tipLabel.text = formatter.string(from: NSNumber(value: tip))! totalLabel.text = formatter.string(from: NSNumber(value: total))! defaults.set(tipControl.selectedSegmentIndex, forKey: "defaultSegment") //TODO: Maybe add animations later? It doesn't seem to add much to the app right now. // self.firstView.alpha = 0 // self.secondView.alpha = 1 // UIView.animateWithDuration(0.4, animations: { // // This causes first view to fade in and second view to fade out // self.firstView.alpha = 1 // self.secondView.alpha = 0 // }) } func textFieldChanged(textField: UITextField) { let text = textField.text?.stringOfNumbersOnly print("cleaned up text: \(text)") textField.text = formatter.string(from: NSNumber(value: (Double(text!) ?? 0)/100.0)) print("newly reformated text: \(textField.text)") } @IBAction func leaveYelpReviewButtonClicked(_ sender: Any) { activityIndicator.isHidden = false activityIndicator.startAnimating() let currentBusinessLink = Constants.YelpHost + Constants.YelpBizPath + "/" + self.currentBusiness!.id! print(currentBusinessLink) scrapeYelpPage(requestLink: currentBusinessLink) { () in let yelpReviewViewController = self.storyboard?.instantiateViewController(withIdentifier: "YelpReviewViewController") as! YelpReviewViewController print(self.yelpBusinessReviewLink!) self.yelpBusinessReviewLink!.remove(at: self.yelpBusinessReviewLink!.index(before: self.yelpBusinessReviewLink!.endIndex)) self.yelpBusinessReviewLink!.remove(at: self.yelpBusinessReviewLink!.index(before: self.yelpBusinessReviewLink!.endIndex)) yelpReviewViewController.yelpBusinessString = self.yelpBusinessReviewLink! self.navigationController?.pushViewController(yelpReviewViewController, animated: true) self.activityIndicator.stopAnimating() } } @IBAction func incorrectLocationButtonClicked(_ sender: Any) { let otherLocationsVC = self.storyboard?.instantiateViewController(withIdentifier: "OtherLocationsViewController") as! OtherLocationsViewController otherLocationsVC.parentVC = self if let otherLocs = self.businesses { otherLocationsVC.otherBusinessesArray = otherLocs print("Here is the list of other locations: \(otherLocs)") } else { otherLocationsVC.otherBusinessesArray = [Business]() //TODO: Create some label that displays when no nearby businesses are found print("There are no other businesses in the area or something went wrong.") } self.navigationController?.pushViewController(otherLocationsVC, animated: true) } func scrapeYelpPage(requestLink: String, completion: @escaping () -> Void ) { Alamofire.request(requestLink).responseString { response in print("\(response.result.isSuccess)") if let html = response.result.value { self.parseHTML(html) { () in completion() } } } } func parseHTML(_ html: String, completionHandler: () -> Void) { let regex = try! NSRegularExpression(pattern: "\\/writeareview\\/biz\\/.+\\?return_url.+", options: .caseInsensitive) guard let myMatch = regex.firstMatch(in: html, options: .withoutAnchoringBounds, range: NSRange(location: 0, length: html.characters.count)) else { print("Error in parseHTML") return } let tmp = (html as NSString).substring(with: myMatch.range) print("Match: \(tmp)") self.yelpBusinessReviewLink = Constants.YelpHost + tmp completionHandler() } } extension String { var stringOfNumbersOnly: String { return components(separatedBy: CharacterSet.decimalDigits.inverted) .joined() } }
mit
8a0b81ad26a276931bac071a84cb47f3
40.510563
222
0.638307
5.303194
false
false
false
false
Swinny1989/iOS-Swift-Popups
Popups.swift
1
2323
// // Popups.swift // // Created by Tom Swindell on 25/05/2015. // Copyright (c) 2015 Tom Swindell. All rights reserved. // import Foundation import UIKit class Popups: NSObject { class var SharedInstance: Popups { struct Static { static var onceToken: dispatch_once_t = 0 static var instance: Popups? = nil } dispatch_once(&Static.onceToken) { Static.instance = Popups() } return Static.instance! } var alertComletion : ((String) -> Void)! var alertButtons : [String]! func ShowAlert(sender: UIViewController, title: String, message: String, buttons : [String], completion: ((buttonPressed: String) -> Void)?) { let aboveIOS7 = floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1) if(aboveIOS7) { let alertView = UIAlertController(title: title, message: message, preferredStyle: .Alert) for b in buttons { alertView.addAction(UIAlertAction(title: b, style: UIAlertActionStyle.Default, handler: { (action : UIAlertAction) -> Void in completion!(buttonPressed: action.title!) })) } sender.presentViewController(alertView, animated: true, completion: nil) } else { self.alertComletion = completion self.alertButtons = buttons let alertView = UIAlertView() alertView.delegate = self alertView.title = title alertView.message = message for b in buttons { alertView.addButtonWithTitle(b) } alertView.show() } } func ShowPopup(title : String, message : String) { let alert: UIAlertView = UIAlertView() alert.title = title alert.message = message alert.addButtonWithTitle("Ok") alert.show() } } extension Popups: UIAlertViewDelegate { func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if(self.alertComletion != nil) { self.alertComletion!(self.alertButtons[buttonIndex]) } } }
mit
80fcd93704dce77eb8280545566be018
29.565789
146
0.565217
5.017279
false
false
false
false
aestesis/Aether
Sources/Aether/Linux/simd.swift
1
7346
// // simd.swift (linux) // Aether // // Created by renan jegouzo on 10/10/2017. // Copyright © 2016 aestesis. 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. // TODO: https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html #if os (Linux) public struct float2 { public var x:Float public var y:Float public init() { x=0 y=0 } public init(_ x:Float,_ y:Float) { self.x=x self.y=y } public init(x:Float,y:Float) { self.x=x self.y=y } public init(_ scalar:Float) { self.x=scalar self.y=scalar } public init(_ array:[Float]) { self.x=array[0] self.y=array[1] } public subscript(index:Int) -> Float { switch index { case 0: return x case 1: return y default: return 0 } } } public struct float3 { public var x:Float public var y:Float public var z:Float public init() { x=0 y=0 z=0 } public init(_ x:Float,_ y:Float,_ z:Float) { self.x=x self.y=y self.z=z } public init(x:Float,y:Float,z:Float) { self.x=x self.y=y self.z=z } public init(_ scalar:Float) { self.x=scalar self.y=scalar self.z=scalar } public init(_ array:[Float]) { self.x=array[0] self.y=array[1] self.z=array[2] } public subscript(index:Int) -> Float { switch index { case 0: return x case 1: return y case 2: return z default: return 0 } } } public struct float4 { public var x:Float public var y:Float public var z:Float public var w:Float public init() { x=0 y=0 z=0 w=0 } public init(_ x:Float,_ y:Float,_ z:Float,_ w:Float) { self.x=x self.y=y self.z=z self.w=w } public init(x:Float,y:Float,z:Float,w:Float) { self.x=x self.y=y self.z=z self.w=w } public init(_ scalar:Float) { self.x=scalar self.y=scalar self.z=scalar self.w=scalar } public init(_ array:[Float]) { self.x=array[0] self.y=array[1] self.z=array[2] self.w=array[3] } public subscript(index:Int) -> Float { switch index { case 0: return x case 1: return y case 2: return z case 3: return w default: return 0 } } } public struct float3x3 { public var columns=(float3(0),float3(0),float3(0)) public init(_ scalar:Float) { columns.0=float3(scalar) columns.1=float3(scalar) columns.2=float3(scalar) } public init(diagonal d:float3) { columns=(float3(d.x,0,0),float3(0,d.y,0),float3(0,0,d.z)) } public init(_ columns:[float3]) { self.columns.0=columns[0] self.columns.1=columns[1] self.columns.2=columns[2] } } public struct float4x4 { public var columns=(float4(0),float4(0),float4(0),float4(0)) public init(_ scalar:Float) { columns=(float4(scalar),float4(scalar),float4(scalar),float4(scalar)) } public init(diagonal d:float4) { columns=(float4(d.x,0,0,0),float4(0,d.y,0,0),float4(0,0,d.z,0),float4(0,0,0,d.w)) } public init(_ columns:[float4]) { self.columns.0=columns[0] self.columns.1=columns[1] self.columns.2=columns[2] self.columns.3=columns[3] } } public struct double4x4 { public var columns=(double4(0),double4(0),double4(0),double4(0)) public init(_ scalar:Double) { columns=(double4(scalar),double4(scalar),double4(scalar),double4(scalar)) } public init(diagonal d:double4) { columns=(double4(d.x,0,0,0),double4(0,d.y,0,0),double4(0,0,d.z,0),double4(0,0,0,d.w)) } public init(_ columns:[double4]) { self.columns.0=columns[0] self.columns.1=columns[1] self.columns.2=columns[2] self.columns.3=columns[3] } } public struct double2 { public var x:Double public var y:Double public init() { x=0 y=0 } public init(_ x:Double,_ y:Double) { self.x=x self.y=y } public init(x:Double,y:Double) { self.x=x self.y=y } public init(_ scalar:Double) { self.x=scalar self.y=scalar } public init(_ array:[Double]) { self.x=array[0] self.y=array[1] } public subscript(index:Int) -> Double { switch index { case 0: return x case 1: return y default: return 0 } } } public struct double3 { public var x:Double public var y:Double public var z:Double public init() { x=0 y=0 z=0 } public init(_ x:Double,_ y:Double,_ z:Double) { self.x=x self.y=y self.z=z } public init(x:Double,y:Double,z:Double) { self.x=x self.y=y self.z=z } public init(_ scalar:Double) { self.x=scalar self.y=scalar self.z=scalar } public init(_ array:[Double]) { self.x=array[0] self.y=array[1] self.z=array[2] } public subscript(index:Int) -> Double { switch index { case 0: return x case 1: return y case 2: return z default: return 0 } } } public struct double4 { public var x:Double public var y:Double public var z:Double public var w:Double public init() { x=0 y=0 z=0 w=0 } public init(_ x:Double,_ y:Double,_ z:Double,_ w:Double) { self.x=x self.y=y self.z=z self.w=w } public init(x:Double,y:Double,z:Double,w:Double) { self.x=x self.y=y self.z=z self.w=w } public init(_ scalar:Double) { self.x=scalar self.y=scalar self.z=scalar self.w=scalar } public init(_ array:[Double]) { self.x=array[0] self.y=array[1] self.z=array[2] self.w=array[3] } public subscript(index:Int) -> Double { switch index { case 0: return x case 1: return y case 2: return z case 3: return w default: return 0 } } } #endif
apache-2.0
f8ca50bc7d5f9e3426ffc72ab0f821f0
21.126506
93
0.510279
3.373909
false
false
false
false
UW-AppDEV/AUXWave
AUXWave/DJService.swift
1
4348
// // DJService.swift // AUXWave // // Created by Nico Cvitak on 2015-03-14. // Copyright (c) 2015 UW-AppDEV. All rights reserved. // import UIKit import MultipeerConnectivity protocol DJServiceDelegate { func service(service: DJService, didReceivePlaylistItem item: PlaylistItem, fromPeer peerID: MCPeerID) } class DJService: NSObject, MCNearbyServiceAdvertiserDelegate, MCSessionDelegate { private struct Singleton { static let instance = DJService() } class func localService() -> DJService { return Singleton.instance } private var peerID: MCPeerID? private var advertiser: MCNearbyServiceAdvertiser? private var session: MCSession? private (set) var isActive: Bool = false var delegate: DJServiceDelegate? private override init() { } func start(displayName: String, discoveryInfo: [NSObject : AnyObject]!) { if isActive { self.stop() } peerID = MCPeerID(displayName: displayName) session = MCSession(peer: peerID) session?.delegate = self advertiser = MCNearbyServiceAdvertiser(peer: peerID, discoveryInfo: discoveryInfo, serviceType: kServiceTypeAUXWave) advertiser?.delegate = self advertiser?.startAdvertisingPeer() isActive = true println("start") } func stop() { if isActive { isActive = false advertiser?.stopAdvertisingPeer() advertiser = nil session = nil peerID = nil } } /* // MARK: - MCNearbyServiceAdvertiserDelegate */ func advertiser(advertiser: MCNearbyServiceAdvertiser!, didReceiveInvitationFromPeer peerID: MCPeerID!, withContext context: NSData!, invitationHandler: ((Bool, MCSession!) -> Void)!) { invitationHandler(true, self.session) } /* // MARK: - MCSession */ func session(session: MCSession!, didReceiveData data: NSData!, fromPeer peerID: MCPeerID!) { } func session(session: MCSession!, didReceiveStream stream: NSInputStream!, withName streamName: String!, fromPeer peerID: MCPeerID!) { } func session(session: MCSession!, didStartReceivingResourceWithName resourceName: String!, fromPeer peerID: MCPeerID!, withProgress progress: NSProgress!) { println("incoming: \(resourceName!)") } func session(session: MCSession!, didFinishReceivingResourceWithName resourceName: String!, fromPeer peerID: MCPeerID!, atURL localURL: NSURL!, withError error: NSError!) { println("finished: \(resourceName!)") let fileManager = NSFileManager.defaultManager() if let cachePath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first as? String { let itemURL = NSURL(fileURLWithPath: cachePath.stringByAppendingPathComponent(resourceName)) fileManager.moveItemAtURL(localURL, toURL: itemURL!, error: nil) if let item = PlaylistItem(URL: itemURL) { println("received item: \(itemURL)") println("\(item.title)") println("\(item.artist)") println("\(item.albumName)") if let delegate = self.delegate { dispatch_async(dispatch_get_main_queue(), { delegate.service(self, didReceivePlaylistItem: item, fromPeer: peerID) }) } } else { fileManager.removeItemAtURL(itemURL!, error: nil) } } } func session(session: MCSession!, peer peerID: MCPeerID!, didChangeState state: MCSessionState) { if state == .Connected { println("connected!") } else if state == .Connecting { println("connecting...") } else if state == .NotConnected { println("not connected") } } func session(session: MCSession!, didReceiveCertificate certificate: [AnyObject]!, fromPeer peerID: MCPeerID!, certificateHandler: ((Bool) -> Void)!) { certificateHandler(true) } }
gpl-2.0
c719f0eca3423ae8f0528ce74fb9f89b
31.447761
189
0.600966
5.66884
false
false
false
false
stripe/stripe-ios
StripePaymentsUI/StripePaymentsUI/Helpers/STPPhoneNumberValidator.swift
1
3825
// // STPPhoneNumberValidator.swift // StripePaymentsUI // // Created by Jack Flintermann on 10/16/15. // Copyright © 2015 Stripe, Inc. All rights reserved. // import Foundation @_spi(STP) import StripePayments @_spi(STP) import StripeUICore @_spi(STP) public class STPPhoneNumberValidator: NSObject { class func stringIsValidPhoneNumber(_ string: String) -> Bool { if string == "" { return false } return self.stringIsValidPhoneNumber(string, forCountryCode: nil) } @_spi(STP) public class func stringIsValidPhoneNumber( _ string: String, forCountryCode nillableCode: String? ) -> Bool { let countryCode = self.countryCodeOrCurrentLocaleCountry(from: nillableCode) if let phoneNumber = PhoneNumber(number: string, countryCode: countryCode) { return phoneNumber.isComplete } else { return !string.isEmpty } } @objc(formattedSanitizedPhoneNumberForString:) class func formattedSanitizedPhoneNumber( for string: String ) -> String { return self.formattedSanitizedPhoneNumber( for: string, forCountryCode: nil ) } @objc(formattedSanitizedPhoneNumberForString:forCountryCode:) class func formattedSanitizedPhoneNumber( for string: String, forCountryCode nillableCode: String? ) -> String { let countryCode = self.countryCodeOrCurrentLocaleCountry(from: nillableCode) let sanitized = STPCardValidator.sanitizedNumericString(for: string) return self.formattedPhoneNumber( for: sanitized, forCountryCode: countryCode ) } @objc(formattedRedactedPhoneNumberForString:) class func formattedRedactedPhoneNumber( for string: String ) -> String { return self.formattedRedactedPhoneNumber( for: string, forCountryCode: nil ) } @objc(formattedRedactedPhoneNumberForString:forCountryCode:) class func formattedRedactedPhoneNumber( for string: String, forCountryCode nillableCode: String? ) -> String { let countryCode = self.countryCodeOrCurrentLocaleCountry(from: nillableCode) let scanner = Scanner(string: string) var prefix: NSString? = NSString() if #available(iOS 13.0, *) { prefix = scanner.scanUpToString("*") as NSString? } else { #if !TARGET_OS_MACCATALYST scanner.scanUpTo("*", into: &prefix) #endif } var number = (string as NSString).replacingOccurrences( of: (prefix ?? "") as String, with: "" ) number = number.replacingOccurrences(of: "*", with: "•") number = self.formattedPhoneNumber( for: number, forCountryCode: countryCode ) return "\(prefix ?? "") \(number)" } class func countryCodeOrCurrentLocaleCountry(from nillableCode: String?) -> String { var countryCode = nillableCode if countryCode == nil { countryCode = NSLocale.autoupdatingCurrent.regionCode } return countryCode ?? "" } class func formattedPhoneNumber( for string: String, forCountryCode countryCode: String ) -> String { if !(countryCode == "US") { return string } if string.count >= 6 { return "(\(string.stp_safeSubstring(to: 3))) \(string.stp_safeSubstring(to: 6).stp_safeSubstring(from: 3))-\(string.stp_safeSubstring(to: 10).stp_safeSubstring(from: 6))" } else if string.count >= 3 { return "(\(string.stp_safeSubstring(to: 3))) \(string.stp_safeSubstring(from: 3))" } return string } }
mit
a7f6fb0cca34ac35688f41e1128e7043
31.948276
179
0.618786
4.893726
false
false
false
false
ftiff/CasperSplash
SplashBuddy/Views/Main/MainViewController_Actions.swift
1
2562
// // Copyright © 2018 Amaris Technologies GmbH. All rights reserved. // import Foundation extension MainViewController { /// User pressed the continue (or restart, logout…) button @IBAction func pressedContinueButton(_ sender: AnyObject) { Preferences.sharedInstance.setupDone = true Preferences.sharedInstance.continueAction.pressed(sender) } /// Set the initial state of the view func setupInstalling() { indeterminateProgressIndicator.startAnimation(self) indeterminateProgressIndicator.isHidden = false statusLabel.isHidden = false statusLabel.stringValue = NSLocalizedString("actions.preparing_your_mac") sidebarView.isHidden = Preferences.sharedInstance.sidebar continueButton.isEnabled = false } /// reset the status label to "We are preparing your Mac…" @objc func resetStatusLabel() { statusLabel.stringValue = NSLocalizedString("actions.preparing_your_mac") } /// sets the status label to display an error @objc func errorWhileInstalling() { Preferences.sharedInstance.errorWhileInstalling = true guard let error = SoftwareArray.sharedInstance.localizedErrorStatus else { return } statusLabel.textColor = .red statusLabel.stringValue = error } /// all critical software is installed @objc func canContinue() { Preferences.sharedInstance.criticalDone = true self.continueButton.isEnabled = true } /// all software is installed (failed or success) @objc func doneInstalling() { Preferences.sharedInstance.allInstalled = true indeterminateProgressIndicator.stopAnimation(self) indeterminateProgressIndicator.isHidden = true if Preferences.sharedInstance.labMode { self.sidebarView.isHidden = true if let labComplete = Preferences.sharedInstance.labComplete { self.webView.loadFileURL(labComplete, allowingReadAccessTo: Preferences.sharedInstance.assetPath) } else { let errorMsg = NSLocalizedString("error.create_complete_html_file") self.webView.loadHTMLString(errorMsg, baseURL: nil) } } } /// all software is sucessfully installed @objc func allSuccess() { Preferences.sharedInstance.allSuccessfullyInstalled = true statusLabel.textColor = .labelColor statusLabel.stringValue = Preferences.sharedInstance.continueAction.localizedSuccessStatus } }
gpl-3.0
e08f10b48a5dd0b8abe0e569d26c2165
34.027397
113
0.690653
5.463675
false
false
false
false
AliSoftware/Dip
SampleApp/Tests/NetworkMock.swift
3
1066
// // NetworkMock.swift // Dip // // Created by Olivier Halligon on 11/10/2015. // Copyright © 2015 AliSoftware. All rights reserved. // import Foundation import Dip var wsDependencies = DependencyContainer() // MARK: - Mock object used for tests struct NetworkMock : NetworkLayer { let fakeData: Data? init(json: Any) { do { fakeData = try JSONSerialization.data(withJSONObject: json, options: []) } catch { fakeData = nil } } func request(path: String, completion: @escaping (NetworkResponse) -> Void) { let fakeURL = NSURL(string: "http://stub")?.appendingPathComponent(path) if let data = fakeData { let response = HTTPURLResponse(url: fakeURL!, statusCode: 200, httpVersion: "1.1", headerFields:nil)! completion(.Success(data, response)) } else { let response = HTTPURLResponse(url: fakeURL!, statusCode: 204, httpVersion: "1.1", headerFields:nil)! completion(.Success(Data(), response)) } } }
mit
846235641c4a01883d4eb3e484fe5cdc
27.783784
113
0.616901
4.26
false
false
false
false
abavisg/BarsAroundMe
BarsAroundMe/BarsAroundMeTests/CalloutViewSpec.swift
1
1495
// // CalloutViewSpec.swift // BarsAroundMe // // Created by Giorgos Ampavis on 20/03/2017. // Copyright © 2017 Giorgos Ampavis. All rights reserved. // import Quick import Nimble import CoreLocation @testable import BarsAroundMe class CalloutViewSpec: QuickSpec{ override func spec() { var view:CalloutView? let place = MockData.place let expectedLocation = CLLocation(latitude: 28.5388, longitude: -81.3756) let viewModel = CalloutViewViewModel() viewModel.update(with: place, and: expectedLocation.coordinate) beforeEach { view = self.makeCell() } describe("when configuring") { context("with a view model") { it("nameLabel text should be the same as nameString") { view?.update(with: viewModel) expect(view?.nameLabel.text).toEventually(equal(viewModel.nameString)) } it("distanceLabel text should be the same as distanceString") { view?.update(with: viewModel) expect(view?.nameLabel.text).toEventually(equal(viewModel.nameString)) } } } } private func makeCell() -> CalloutView { let views = Bundle.main.loadNibNamed("CalloutView", owner: nil, options: nil) let calloutView = views?[0] as! CalloutView return calloutView } }
mit
7c249b9b5582f4b32b5e9719ac1c5f0c
29.489796
90
0.580991
4.803859
false
false
false
false
leoneparise/iLog
iLog/LogManager.swift
1
5480
// // Logger.swift // StumpExample // // Created by Leone Parise Vieira da Silva on 05/05/17. // Copyright © 2017 com.leoneparise. All rights reserved. // import Foundation import UIKit /** Global log function. You should provide only `level` and `message` parameters. Leave the rest with it's default values - parameter file: file where this log was fired. - parameter line: line where this log was fired. - parameter function: function where this log was fired. - parameter level: this log level - parameter message: this log message */ public func log(file:String = #file, line:UInt = #line, function:String = #function, _ level:LogLevel, _ message:String) { LogManager.shared.log(file: file, line: line, function: function, level: level, message: message) } public extension Notification.Name { /// Fired when any manager's `log` method is called public static let LogManagerDidLog = Notification.Name("LogManagerDidLog") } /// Manager public class LogManager { private var storeBackgroundTask:UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid private let loggingQueue = DispatchQueue(label: "loggingQueue", qos: .background) private let queryQueue = DispatchQueue(label: "queryQueue", qos: .background) private static var sharedInstance: LogManager! // MARK: Public /// LogManager level public var level:LogLevel = .debug { didSet { didSetLevel() } } /// Log manager drivers public var drivers: [LogDriver] = [] /// First driver from drivers array public var mainDriver: LogDriver? { return drivers.first } /// Share instance. Used by log global function public static var shared: LogManager { assert(sharedInstance != nil, "Please, call setup method before using iLog") return sharedInstance } public static func setup(_ drivers: LogDriver...) { sharedInstance = LogManager(drivers: drivers) } /// Default initializer public init(drivers: [LogDriver]) { self.drivers = drivers } /// Get log history from the main Driver public func filter(level levelOrNil:LogLevel? = nil, text textOrNil:String? = nil, offset:Int = 0, completion: @escaping (([LogEntry]?) -> Void)) { queryQueue.async { [weak self] in self?.mainDriver?.filter(level: levelOrNil, text: textOrNil, offset: offset, completion: completion) } } /// Log public func log(file: String = #file, line: UInt = #line, function: String = #function, level: LogLevel = .debug, message: String) { let fileName = file.components(separatedBy: "/").last? .components(separatedBy: ".").first ?? "" let entry = LogEntry(createdAt: nil, order: nil, stored: nil, level: level, file: fileName, line: line, function: function, message: message) loggingQueue.async { [weak self] in guard let wself = self else { return } for driver in wself.drivers { driver.log(entry: entry) } } postDidLogNotification(entry: entry) } /** Store your log entries in a backend service. This method should be callend when you application is going to background state. It automatially starts a background task, call your save handler, saves the changes in the database and finish the background task. **In uses only the mainDriver.** - parameter: appliction UIAppliction instance - handler: Store handler. */ public func storeLogsInBackground(application: UIApplication, handler: @escaping StoreHandler) { // If there is a background task running, doesn't run again if storeBackgroundTask != UIBackgroundTaskIdentifier.invalid { return } storeBackgroundTask = application.beginBackgroundTask { [unowned self] in application.endBackgroundTask(self.storeBackgroundTask) // End background task after 180 seconds } do { try mainDriver?.store{ [unowned self] (entries, complete) in try handler(entries) { success in try complete(success) if self.storeBackgroundTask != UIBackgroundTaskIdentifier.invalid { application.endBackgroundTask(self.storeBackgroundTask) // End background task after save } } } } catch { if self.storeBackgroundTask != UIBackgroundTaskIdentifier.invalid { application.endBackgroundTask(self.storeBackgroundTask) // End background task if there is an error } } } /// Clear all drivers public func clear() { loggingQueue.async { [weak self] in guard let wself = self else { return } for driver in wself.drivers { driver.clear() } } } private func didSetLevel() { for driver in drivers { driver.level = self.level } } deinit { NotificationCenter.default.removeObserver(self) } } // MARK: - Notification extension LogManager { fileprivate func postDidLogNotification(entry: LogEntry) { NotificationCenter.default.post(name: Notification.Name.LogManagerDidLog, object: entry) } }
mit
3f51d0f48e53df24238733ec10436725
35.284768
151
0.632415
4.789336
false
false
false
false
YauheniYarotski/APOD
APOD/ApodVC.swift
1
25931
// // ViewController.swift // APOD // // Created by Yauheni Yarotski on 23.04.16. // Copyright © 2016 Yauheni_Yarotski. All rights reserved. // import UIKit import youtube_ios_player_helper import IDMPhotoBrowser import SnapKit class ApodVC: UIViewController, UICollectionViewDelegate { let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: InfinitLayout()) var infinitLayout: InfinitLayout? { return collectionView.collectionViewLayout as? InfinitLayout } let dateView = TopBar(frame: CGRect.zero) let titleView = ApodTitleView(frame: CGRect.zero) let kAmountRowsNoToCancel = 20 fileprivate let apodManager = ApodManager.sharedInstance fileprivate let datePicker = UIDatePicker() fileprivate let datePickerBar = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) fileprivate var curentCenteredCellRow = Int.max fileprivate let modalPresentAnimationController = ModalPresentAnimationController() fileprivate let modalDismissAnimationController = ModalDismissAnimationController() fileprivate let swipePresenter = SwipePresenter() fileprivate let swipeDismiser = SwipeDismiser() fileprivate var videoWasPausedByController = false fileprivate let connectingMessage = "Connecting with NASA..." fileprivate let errorImage = UIImage(named: "error")! fileprivate var isFirstLaunch = true //MARK: - UIViewController override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nil, bundle: nil) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { collectionView.delegate = self collectionView.dataSource = self collectionView.register(ApodCell.self, forCellWithReuseIdentifier: ApodCell.constants.reuseIdentifier) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) view.layoutIfNeeded() if isFirstLaunch { let initialRow = ApodVCRowAdapter.convertApodRowToCollectionViewRow(0) scrollToRow(initialRow) isFirstLaunch = false } } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(ApodVC.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ApodVC.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) setupApodDateView() setupCollectionView() setupDatePicker() setupApodTitleView() setupSwipeHandler() setupObserversForNotifications() apodManager.delegate = self } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { collectionView.collectionViewLayout.invalidateLayout() OperationQueue.main.addOperation { self.scrollToRow(self.curentCenteredCellRow) } } override var preferredStatusBarStyle : UIStatusBarStyle { return .lightContent } //MARK: - Setup func setupCollectionView() { collectionView.translatesAutoresizingMaskIntoConstraints = false infinitLayout?.scrollDirection = .horizontal view.addSubview(collectionView) collectionView.snp.makeConstraints { (make) in make.leading.trailing.equalToSuperview() make.top.equalTo(dateView.snp.bottom) make.bottom.equalToSuperview().offset(-60) } if #available(iOS 10.0, *) { collectionView.isPrefetchingEnabled = false//TODO: if on, the sthange happen: seting cell, than deque the same cell and than setting it again. Only on ios 10 with prefethc. } } func setupDatePicker() { datePicker.datePickerMode = .date datePicker.minimumDate = apodManager.firstApodDate() as Date datePicker.maximumDate = apodManager.lastApodDate() as Date datePicker.backgroundColor = UIColor.black datePicker.setValue(UIColor.white, forKey: "textColor") datePicker.addTarget(self, action: #selector(ApodVC.datePickerDidSelect(_:)), for: .valueChanged) } func setupApodDateView() { dateView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(dateView) dateView.snp.makeConstraints { (make) in make.leading.trailing.equalToSuperview() make.top.equalToSuperview().offset(20) make.height.equalTo(50) } dateView.inputView = datePicker dateView.delegate = self // dateView.title.isUserInteractionEnabled = true // let tap = UITapGestureRecognizer(target: self, action: #selector(ApodVC.apodDateLablePressed(_:))) // tap.numberOfTapsRequired = 1 // dateView.title.addGestureRecognizer(tap) } func setupApodTitleView() { titleView.delegate = self titleView.likesView.delegate = self titleView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(titleView) titleView.snp.makeConstraints { (make) in make.leading.trailing.bottom.equalToSuperview() make.height.equalTo(50) } } func setupSwipeHandler() { let pan = UIPanGestureRecognizer(target: self, action: #selector(ApodVC.didPan(_:))) view.addGestureRecognizer(pan) } //MARK: - ViewController Logic func scrollToRow(_ row: Int) { let indexPath = IndexPath(item: row, section: 0) collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) } func collectionViewCenter() -> CGPoint { let x = collectionView.bounds.origin.x + collectionView.bounds.width/2.0 let y = collectionView.center.y let centerPoint = CGPoint(x: x, y: y) return centerPoint } func indexPathOfCollectionViewCenterPoint () -> IndexPath? { return collectionView.indexPathForItem(at: collectionViewCenter()) } func centeredCell() -> ApodCell? { let indexPath = IndexPath(item: curentCenteredCellRow, section: 0) return collectionView.cellForItem(at: indexPath) as? ApodCell } func setBarTitle(_ title: String) { titleView.title.text = title datePickerBar.title = title } func setLikes(_ likesAmount: Int?, isSelfLiked: Bool?, forRow: Int, enableView: Bool) { if curentCenteredCellRow == forRow { self.titleView.likesView.setLikes(likesAmount, isSelfLiked: isSelfLiked) if self.titleView.likesView.enabled != enableView { self.titleView.likesView.enabled = enableView } } } //MARK: - Action Handlers func apodDateLablePressed (_ gesture: UITapGestureRecognizer) { if dateView.isFirstResponder { dateView.resignFirstResponder() } else { scrollToRow(curentCenteredCellRow) dateView.becomeFirstResponder() //workaround to keep datepciker date always up to date if datePicker.maximumDate?.compare(apodManager.lastApodDate()) != .orderedSame { datePicker.maximumDate = apodManager.lastApodDate() } } } func datePickerDidSelect(_ datePicker: UIDatePicker) { let date = datePicker.date apodManager.mediaForDate(date, completion: nil)//To start download imidiatly the needed apod and image. let row = ApodVCRowAdapter.collectionViewRowForDate(date) scrollToRow(row) } func textFieldAllEvents(_ textField: UITextField) { if textField.isFirstResponder { let date = ApodVCRowAdapter.apodDateForCollectionRow(curentCenteredCellRow) datePicker.date = date } } func didPan(_ pan: UIPanGestureRecognizer) { switch pan.state { case .began: scrollToRow(curentCenteredCellRow) if pan.velocity(in: view).y < 0.0 { swipePresenter.interactionInProgress = true presentApodDescriptionVCForRow(curentCenteredCellRow) } else { if dateView.isFirstResponder { dateView.resignFirstResponder() } else { dateView.becomeFirstResponder() } } default: if swipePresenter.interactionInProgress { swipePresenter.handlePan(pan) } } } //MARK: From ApodManager func nextDaysDidCome(_ amountOfDays: Int) { datePicker.maximumDate = apodManager.lastApodDate() as Date var newIndexes = [IndexPath]() for i in 1...abs(amountOfDays) { let newIndex = IndexPath(item: 1 + i, section: 0) newIndexes.append(newIndex) } if amountOfDays > 0 { collectionView.insertItems(at: newIndexes) } else { collectionView.deleteItems(at: newIndexes) } //TODO: check if needed collectionView.collectionViewLayout.invalidateLayout() let infinitLayout = collectionView.collectionViewLayout as! InfinitLayout infinitLayout.setupInfinitScroll() let initialRow = ApodVCRowAdapter.convertApodRowToCollectionViewRow(0) scrollToRow(initialRow) didScrollToCenterRow(initialRow) } func freeMinutesPassed() { if let _ = presentedViewController as? ApodDescriptionVC { apodDescriptionVCDidFinsh(nil) } else if let _ = presentedViewController as? InfoVC { return } presentInfoVC() } //MARK: - Navigation func presentApodImageVCFromImageView(_ apodImageView: UIImageView) { if let image = apodImageView.image { let photo = IDMPhoto(image: image) let browser = IDMPhotoBrowser(photos: [photo], animatedFrom: apodImageView) browser?.forceHideStatusBar = true browser?.displayDoneButton = false browser?.displayToolbar = false present(browser!, animated: true, completion: nil) } } func presentApodDescriptionVCForRow(_ row: Int, handleGesture: UIPanGestureRecognizer? = nil) { if dateView.isFirstResponder { dateView.resignFirstResponder() } let apodDate = ApodVCRowAdapter.apodDateForCollectionRow(row)//TODO: to offen using this method, maybe somehow able to simpyfy apodManager.apodForDate(apodDate) { (apod, error) in guard let apod = apod else {return} let apodDescriptionVC = ApodDescriptionVC(nibName: nil, bundle: nil) apodDescriptionVC.apodDateString = String.stringFromDate(apod.date) apodDescriptionVC.apodTitle = apod.title apodDescriptionVC.apodDescription = apod.explanation apodDescriptionVC.delegate = self apodDescriptionVC.swipeDismiser = self.swipeDismiser apodDescriptionVC.transitioningDelegate = self apodDescriptionVC.modalPresentationStyle = .custom if let cell = self.centeredCell(), !cell.playerView.isHidden && cell.playerView.playerState() == .playing { cell.playerView.pauseVideo() self.videoWasPausedByController = true } self.present(apodDescriptionVC, animated: true, completion: nil) } } func presentInfoVC() { let blackColor = UIColor.black // dateView.backgroundColor = blackColor dateView.shareButton.backgroundColor = blackColor dateView.infoButton.backgroundColor = blackColor view.backgroundColor = blackColor let infoVC = InfoVC(nibName: nil, bundle: nil) infoVC.delegate = self infoVC.modalTransitionStyle = .flipHorizontal infoVC.apodManager = apodManager let navigationVC = UINavigationController(navigationBarClass: TransluentNavigationBar.self, toolbarClass: nil) navigationVC.setViewControllers([infoVC], animated: false) present(navigationVC, animated: true, completion: nil) } //MARK: - Notifications func setupObserversForNotifications() { NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: TimerManager.NotificationKeys.kNextDayDidComeNotification), object: nil, queue: nil) { (notification) in if let daysAdded = (notification as NSNotification).userInfo?[TimerManager.NotificationKeys.kAddedDaysTitle] as? Int { self.nextDaysDidCome(daysAdded) } } NotificationCenter.default.addObserver(self, selector: #selector(ApodVC.freeMinutesPassed), name: NSNotification.Name(rawValue: TimerManager.NotificationKeys.kFreeMinutesPasedNotification), object: nil) } } //MARK: - UICollectionViewDataSource extension ApodVC: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return apodManager.totalAmountOfApods() + ApodVCRowAdapter.Settings.kAmountOfFakeAddedRowsToCreateInfiniteSroll } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ApodCell.constants.reuseIdentifier, for: indexPath) as! ApodCell let row = (indexPath as NSIndexPath).row cell.activityIndicator.startAnimating() cell.delegate = self cell.playerView.delegate = self cell.tag = row let apodDate = ApodVCRowAdapter.apodDateForCollectionRow(row) self.apodManager.mediaForDate(apodDate, completion: { (image, videoIdentifier, url, error) in if cell.tag == row { cell.activityIndicator.stopAnimating() if let image = image { cell.apodImageView.image = image } else if let videoIdentifier = videoIdentifier { cell.apodImageView.isHidden = true cell.playerView.isHidden = false cell.playerView.tag = row if cell.playerView.videoUrl() == nil { cell.playerView.load(withVideoId: videoIdentifier, playerVars: ["playsinline":1, "showinfo":0]) } else { cell.playerView.cueVideo(byId: videoIdentifier, startSeconds: 0.0, suggestedQuality: .auto) } } else if let url = url { cell.errorLabel.text = url.absoluteString } else if let error = error { if error._code != -999 { //we don't show cancel error cell.apodImageView.image = self.errorImage cell.errorLabel.text = "Houston, We Have a Problem..." } } else { print("xz, strange error") } } }) return cell } } //MARK: - UIScrollViewDelegate extension ApodVC: UIScrollViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { dateView.resignFirstResponder() } func scrollViewDidScroll(_ scrollView: UIScrollView) { if let indexPath = indexPathOfCollectionViewCenterPoint(), (indexPath as NSIndexPath).row != curentCenteredCellRow { //to sceep equal requests didScrollToCenterRow((indexPath as NSIndexPath).row) } } func didScrollToCenterRow(_ row: Int) { curentCenteredCellRow = row let apodDate = ApodVCRowAdapter.apodDateForCollectionRow(row) dateView.title.text = String.stringFromDate(apodDate) setBarTitle(connectingMessage) setLikes(0, isSelfLiked: false, forRow: row, enableView: false) apodManager.updateApodLikesForDate(apodDate) apodManager.apodForDate(apodDate, completion: { (apod, error) in if row == self.curentCenteredCellRow { if let apod = apod { self.setBarTitle(apod.title) if apod.mediaType == MediaType.video { if let cell = self.centeredCell(), !cell.playerView.isHidden && cell.playerView.tag == row { cell.playerView.playVideo() } } } else { self.setBarTitle(error?.localizedDescription ?? "no error description") } } }) if let cellBefore = collectionView.cellForItem(at: IndexPath(item: row - 1, section: 0)) as? ApodCell { if !cellBefore.playerView.isHidden { cellBefore.playerView.pauseVideo() } } if let cellAfter = collectionView.cellForItem(at: IndexPath(item: row + 1, section: 0)) as? ApodCell { if !cellAfter.playerView.isHidden { cellAfter.playerView.pauseVideo() } } } } //MARK: - YTPlayerViewDelegate extension ApodVC: YTPlayerViewDelegate { func playerViewDidBecomeReady(_ playerView: YTPlayerView) { if curentCenteredCellRow == playerView.tag { if let cell = self.centeredCell(), !cell.playerView.isHidden && playerView.playerState() != .paused { playerView.playVideo() } else { playerView.pauseVideo() } } else { playerView.pauseVideo() } } func playerView(_ playerView: YTPlayerView, receivedError error: YTPlayerError) { if titleView.title.text == connectingMessage && curentCenteredCellRow == playerView.tag { setBarTitle("Video error") } } } //MARK: - ApodCellDelegate extension ApodVC: ApodCellDelegate { func prepareCellForReuse(_ row: NSInteger, cell: ApodCell) {//we don't cancel start cells if row >= kAmountRowsNoToCancel/2 && row <= apodManager.totalAmountOfApods() - kAmountRowsNoToCancel/2 { let apodDate = ApodVCRowAdapter.apodDateForCollectionRow(row) apodManager.cancelOperationForDate(apodDate) } } func apodImageTaped(_ tap: UITapGestureRecognizer, cell: ApodCell) { if dateView.isFirstResponder { dateView.resignFirstResponder() } else { if cell.tag == curentCenteredCellRow && cell.apodImageView.image != nil { presentApodImageVCFromImageView(cell.apodImageView) } else if cell.apodImageView.image != nil { scrollToRow(cell.tag) } else if let urlString = cell.errorLabel.text, let url = URL(string: urlString) { UIApplication.shared.openURL(url) } } } } //MARK: - LikesViewDelegate extension ApodVC: LikesViewDelegate { func likeTaped(_ likesVC: LikesView, tap: UITapGestureRecognizer) { let apodDate = ApodVCRowAdapter.apodDateForCollectionRow(curentCenteredCellRow) apodManager.likeApodForDate(apodDate) } } //MARK: - ApodDescriptionVCDelegate extension ApodVC: ApodDescriptionVCDelegate { func apodDescriptionVCDidFinsh(_ apodDescriptionVC: ApodDescriptionVC?) { dismiss(animated: true, completion: { if self.videoWasPausedByController { if let cell = self.centeredCell(), !cell.playerView.isHidden && cell.playerView.playerState() == .paused { cell.playerView.playVideo() self.videoWasPausedByController = false } } }) } func apodDescriptionVCDidFinshByDateBarPressed(_ apodDescriptionVC: ApodDescriptionVC) { dismiss(animated: true, completion: nil) self.dateView.becomeFirstResponder() } } //MARK: - InfoVCDelegate extension ApodVC: InfoVCDelegate { func infoVCDidFinish(_ infoVC: InfoVC?) { dismiss(animated: true, completion: { let clearColor = UIColor.clear // self.dateView.backgroundColor = clearColor self.dateView.shareButton.backgroundColor = clearColor self.dateView.infoButton.backgroundColor = clearColor }) } } //MARK: - UIViewControllerTransitioningDelegate extension ApodVC: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return modalPresentAnimationController } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return modalDismissAnimationController } func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return swipePresenter.interactionInProgress ? swipePresenter : nil } func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return swipeDismiser.interactionInProgress ? swipeDismiser : nil } } //MARK: - ModalPresenting extension ApodVC: ModalPresenting { func presentationWasCancelled(_ modalPresentAnimationController: ModalPresentAnimationController) { if videoWasPausedByController { if let cell = self.centeredCell(), !cell.playerView.isHidden && cell.playerView.playerState() == .paused { cell.playerView.playVideo() self.videoWasPausedByController = false } } } } //MARK: - ApodManagerDelegate extension ApodVC: ApodManagerDelegate { func apodLikesAmountDidChangeForDate(_ apodManager: ApodManager, date: Date, likesAmount: Int) { let row = ApodVCRowAdapter.collectionViewRowForDate(date) self.setLikes(likesAmount, isSelfLiked: nil, forRow: row, enableView: true) } func apodIsSelfLikedDidChangeForDate(_ apodManager: ApodManager, date: Date, isSelfLiked: Bool) { let row = ApodVCRowAdapter.collectionViewRowForDate(date) self.setLikes(nil, isSelfLiked: isSelfLiked, forRow: row, enableView: true) } } typealias ApodVC_TopBarDelegate = ApodVC extension ApodVC_TopBarDelegate: TopBarDelegate { func topBarWasTaped(topBar: TopBar) { // if isFirstResponder { // resignFirstResponder() // view.addSubview(bottomBar) // bottomBar.snp.makeConstraints { (make) in // make.height.equalTo(60) // make.leading.trailing.equalToSuperview() // make.bottom.equalToSuperview() // } // } else { // bottomBar.removeFromSuperview() // let status = becomeFirstResponder() // print(status) // } } func shareTaped(topBar: TopBar) { let apodDate = ApodVCRowAdapter.apodDateForCollectionRow(curentCenteredCellRow) apodManager.apodForDate(apodDate) { (apod, error) in if let apod = apod { let title = "APOD: \(apod.title) (\(String.shortStringFromDate(apod.date)))" self.apodManager.mediaForDate(apodDate, completion: { (image, videoIdentifier, url, error) in if let image = image { let activityViewController = UIActivityViewController(activityItems: [title, image], applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.dateView.shareButton activityViewController.popoverPresentationController?.sourceRect = self.dateView.shareButton.bounds self.present(activityViewController, animated: true) { // ... } } else if let _ = videoIdentifier, let videoUrl = URL(string: apod.url) { let activityViewController = UIActivityViewController(activityItems: [title, videoUrl], applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.dateView.shareButton activityViewController.popoverPresentationController?.sourceRect = self.dateView.shareButton.bounds self.present(activityViewController, animated: true) { // ... } } }) } } } func infoTaped(topBar: TopBar) { presentInfoVC() } } typealias ApodVC_ApodTitleViewDelegate = ApodVC extension ApodVC_ApodTitleViewDelegate: ApodTitleViewDelegate { func apodTitlePressed(apodTitleView: ApodTitleView) { scrollToRow(curentCenteredCellRow) presentApodDescriptionVCForRow(curentCenteredCellRow) } func apodTitlePan(apodTitleView: ApodTitleView, pan: UIPanGestureRecognizer) { didPan(pan) } } typealias ApodVCKeyBoard = ApodVC extension ApodVCKeyBoard { @objc func keyboardWillShow(notification: NSNotification) { if let info = notification.userInfo, let kbHeight = (info[UIKeyboardFrameBeginUserInfoKey] as AnyObject).cgRectValue?.size.height, let duration = info[UIKeyboardAnimationDurationUserInfoKey] as? Double { updateTitleViewYPosition(bottomOffset: -kbHeight, animationDuration: duration) } } @objc func keyboardWillHide(notification: NSNotification) { if let info = notification.userInfo, let duration = info[UIKeyboardAnimationDurationUserInfoKey] as? Double { updateTitleViewYPosition(bottomOffset: 0, animationDuration: duration) } } func updateTitleViewYPosition(bottomOffset: CGFloat, animationDuration: Double) { titleView.snp.updateConstraints({ (make) in make.bottom.equalToSuperview().offset(bottomOffset) }) UIView.animate(withDuration: animationDuration, animations: { self.view.layoutIfNeeded() }) } }
mit
816c49912f4c361c8f57439adce50711
35.88478
210
0.663903
4.773564
false
false
false
false
apple/swift
test/DebugInfo/async-lifetime-extension.swift
9
1288
// RUN: %target-swift-frontend %s -emit-ir -g -o - \ // RUN: -module-name a -disable-availability-checking \ // RUN: | %FileCheck %s --check-prefix=CHECK // REQUIRES: concurrency // Test that lifetime extension preserves a dbg.declare for "n" in the resume // funclet. // CHECK-LABEL: define {{.*}} void @"$s1a4fiboyS2iYaFTY0_" // CHECK-NEXT: entryresume.0: // CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[R:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[N:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LHS:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[RHS:[0-9]+]], {{.*}}!DIExpression(DW_OP // CHECK-NOT: {{ ret }} // CHECK: call void asm sideeffect "" // CHECK: ![[N]] = !DILocalVariable(name: "n" // CHECK: ![[R]] = !DILocalVariable(name: "retval" // CHECK: ![[LHS]] = !DILocalVariable(name: "lhs" // CHECK: ![[RHS]] = !DILocalVariable(name: "rhs" public func fibo(_ n: Int) async -> Int { var retval = n if retval < 2 { return 1 } retval = retval - 1 let lhs = await fibo(retval - 1) let rhs = await fibo(retval - 2) return lhs + rhs + retval }
apache-2.0
b83ad5026d6e146881c469fa9bb5c01c
45
113
0.620342
3.149144
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Content Display Logic/Model/Sample.swift
1
1929
// // Copyright © 2018 Esri. // // 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 struct Sample: Hashable { var name: String var description: String var storyboardName: String var dependencies: [String] } extension Sample: Decodable { enum CodingKeys: String, CodingKey { case name = "displayName" case description = "descriptionText" case storyboardName = "storyboardName" case dependencies = "dependency" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) name = try values.decode(String.self, forKey: .name) description = try values.decode(String.self, forKey: .description) storyboardName = try values.decode(String.self, forKey: .storyboardName) dependencies = try values.decodeIfPresent([String].self, forKey: .dependencies) ?? [] } } extension Sample { var readmeURL: URL? { return Bundle.main.url(forResource: "README", withExtension: "md", subdirectory: name) } var isFavorite: Bool { get { UserDefaults.standard.favoriteSamples.contains(name) } nonmutating set { if newValue { UserDefaults.standard.favoriteSamples.insert(name) } else { UserDefaults.standard.favoriteSamples.remove(name) } } } }
apache-2.0
b465da0bba3cd25e2f03763830686990
31.677966
94
0.6639
4.536471
false
false
false
false
baiyidjp/SwiftWB
SwiftWeibo/SwiftWeibo/Classes/Tools(工具)/Emoticon/EmoticonView/JPEmoticonToolView.swift
1
3601
// // JPEmoticonToolView.swift // SwiftWeibo // // Created by tztddong on 2016/12/13. // Copyright © 2016年 dongjiangpeng. All rights reserved. // import UIKit /// 代理/协议 @objc protocol JPEmoticonToolViewDelegate: NSObjectProtocol { func emoticonToolBarItemDidSelectIndex(toolView: JPEmoticonToolView,index: Int) } /// 表情键盘底部的工具栏 class JPEmoticonToolView: UIView { override func awakeFromNib() { setupUI() } weak var delegate: JPEmoticonToolViewDelegate? /// 滚动时 调整按钮的点击状态 var selectIndex: Int = 0 { didSet { for btn in subviews as! [UIButton] { setButton(isSelect: btn.tag == selectIndex, btn: btn) } } } /// 点击底部的item /// /// - Parameter button: 按钮 @objc fileprivate func clickItem(button: UIButton) { for btn in subviews as! [UIButton] { setButton(isSelect: btn == button, btn: btn) } delegate?.emoticonToolBarItemDidSelectIndex(toolView: self, index: button.tag) } fileprivate func setButton(isSelect: Bool,btn: UIButton) { btn.isSelected = isSelect } } fileprivate extension JPEmoticonToolView { /// 设置视图 func setupUI() { //从表情管理类中拿到分组名 let manager = JPEmoticonManager.shared //按钮的宽度 let btnW = ScreenWidth / CGFloat(manager.packagesModels.count) for (i,page) in manager.packagesModels.enumerated() { let btn = UIButton() btn.setTitle(page.groupName, for: .normal) btn.titleLabel?.font = UIFont.systemFont(ofSize: 14) btn.setTitleColor(UIColor.white, for: .normal) btn.setTitleColor(UIColor.darkGray, for: .highlighted) btn.setTitleColor(UIColor.darkGray, for: .selected) //设置按钮图片 compose_emotion_table_left_normal compose_emotion_table_mid_selected var imageNormal = UIImage(named: "compose_emotion_table_\(page.bgImageName ?? "")_normal") var imageSelected = UIImage(named: "compose_emotion_table_\(page.bgImageName ?? "")_selected") //图片的大小 let imageSize = imageNormal?.size ?? CGSize() let inset = UIEdgeInsets(top: imageSize.height*0.5, left: imageSize.width*0.5, bottom: imageSize.width*0.5, right: imageSize.height*0.5) imageNormal = imageNormal?.resizableImage(withCapInsets: inset, resizingMode: .stretch) imageSelected = imageSelected?.resizableImage(withCapInsets: inset, resizingMode: .stretch) btn.setBackgroundImage(imageNormal, for: .normal) btn.setBackgroundImage(imageSelected, for: .highlighted) btn.setBackgroundImage(imageSelected, for: .selected) addSubview(btn) btn.snp.makeConstraints({ (make) in make.top.bottom.equalTo(0) make.width.equalTo(btnW) make.left.equalTo(CGFloat(i)*btnW) }) //设置tag值 btn.tag = i //添加点击方法 btn.addTarget(self, action: #selector(clickItem), for: .touchUpInside) } //第一个按钮默认点击 (subviews[0] as! UIButton).isSelected = true } }
mit
11261b3d61434b22a0fc98de4d0c414f
29.371681
148
0.575758
4.56383
false
false
false
false
zhaobin19918183/zhaobinCode
HTK/HTK/Common/PDChart/PDChartComponent/PDChartAxesComponent.swift
1
11689
// // PDChartAxesComponent.swift // PDChart // // Created by Pandara on 14-7-11. // Copyright (c) 2014年 Pandara. All rights reserved. // import UIKit class PDChartAxesComponentDataItem: NSObject { //required var targetView: UIView! var featureH: CGFloat! var featureW: CGFloat! var xMax: CGFloat! var xInterval: CGFloat! var yMax: CGFloat! var yInterval: CGFloat! var xAxesDegreeTexts: [String]? var yAxesDegreeTexts: [String]? //optional default var showAxes: Bool = true var showXDegree: Bool = true var showYDegree: Bool = true var axesColor: UIColor = UIColor(red: 80.0 / 255, green: 80.0 / 255, blue: 80.0 / 255, alpha: 1.0)//坐标轴颜色 var axesTipColor: UIColor = UIColor(red: 80.0 / 255, green: 80.0 / 255, blue: 80.0 / 255, alpha: 1.0)//坐标轴刻度值颜色 var xAxesLeftMargin: CGFloat = 40 //坐标系左边margin var xAxesRightMargin: CGFloat = 40 //坐标系右边margin var yAxesBottomMargin: CGFloat = 40 //坐标系下面margin var yAxesTopMargin: CGFloat = 40 //坐标系上方marign var axesWidth: CGFloat = 1.0 //坐标轴的粗细 var arrowHeight: CGFloat = 5.0 var arrowWidth: CGFloat = 5.0 var arrowBodyLength: CGFloat = 10.0 var degreeLength: CGFloat = 5.0 //坐标轴刻度直线的长度 var degreeTipFontSize: CGFloat = 10.0 var degreeTipMarginHorizon: CGFloat = 5.0 var degreeTipMarginVertical: CGFloat = 5.0 override init() { } } class PDChartAxesComponent: NSObject { var dataItem: PDChartAxesComponentDataItem! init(dataItem: PDChartAxesComponentDataItem) { self.dataItem = dataItem } func getYAxesHeight() -> CGFloat {//heigth between 0~yMax let basePoint: CGPoint = self.getBasePoint() let yAxesHeight = basePoint.y - dataItem.arrowHeight - dataItem.yAxesTopMargin - dataItem.arrowBodyLength return yAxesHeight } func getXAxesWidth() -> CGFloat {//width between 0~xMax let basePoint: CGPoint = self.getBasePoint() let xAxesWidth = dataItem.featureW - basePoint.x - dataItem.arrowHeight - dataItem.xAxesRightMargin - dataItem.arrowBodyLength return xAxesWidth } func getBasePoint() -> CGPoint { var neededAxesWidth: CGFloat! if dataItem.showAxes { neededAxesWidth = CGFloat(dataItem.axesWidth) } else { neededAxesWidth = 0 } let basePoint: CGPoint = CGPoint(x: dataItem.xAxesLeftMargin + neededAxesWidth / 2.0, y: dataItem.featureH - (dataItem.yAxesBottomMargin + neededAxesWidth / 2.0)) return basePoint } func getXDegreeInterval() -> CGFloat { let xAxesWidth: CGFloat = self.getXAxesWidth() let xDegreeInterval: CGFloat = dataItem.xInterval / dataItem.xMax * xAxesWidth return xDegreeInterval } func getYDegreeInterval() -> CGFloat { let yAxesHeight: CGFloat = self.getYAxesHeight() let yDegreeInterval: CGFloat = dataItem.yInterval / dataItem.yMax * yAxesHeight return yDegreeInterval } func getAxesDegreeTipLabel(_ tipText: String, center: CGPoint, size: CGSize, fontSize: CGFloat, textAlignment: NSTextAlignment, textColor: UIColor) -> UILabel { let label: UILabel = UILabel(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: size)) label.text = tipText label.center = center label.textAlignment = textAlignment label.textColor = textColor label.backgroundColor = UIColor.clear label.adjustsFontSizeToFitWidth = true label.font = UIFont.systemFont(ofSize: fontSize) return label } func getXAxesDegreeTipLabel(_ tipText: String, center: CGPoint, size: CGSize, fontSize: CGFloat) -> UILabel { return self.getAxesDegreeTipLabel(tipText, center: center, size: size, fontSize: fontSize, textAlignment: NSTextAlignment.center, textColor: dataItem.axesTipColor) } func getYAxesDegreeTipLabel(_ tipText: String, center: CGPoint, size: CGSize, fontSize: CGFloat) -> UILabel { return self.getAxesDegreeTipLabel(tipText, center: center, size: size, fontSize: fontSize, textAlignment: NSTextAlignment.right, textColor: dataItem.axesTipColor) } func strokeAxes(_ context: CGContext?) { let xAxesWidth: CGFloat = self.getXAxesWidth() let yAxesHeight: CGFloat = self.getYAxesHeight() let basePoint: CGPoint = self.getBasePoint() if dataItem.showAxes { context?.setStrokeColor(dataItem.axesColor.cgColor) context?.setFillColor(dataItem.axesColor.cgColor) let axesPath: UIBezierPath = UIBezierPath() axesPath.lineWidth = dataItem.axesWidth axesPath.lineCapStyle = CGLineCap.round axesPath.lineJoinStyle = CGLineJoin.round //x axes-------------------------------------- axesPath.move(to: CGPoint(x: basePoint.x, y: basePoint.y)) axesPath.addLine(to: CGPoint(x: basePoint.x + xAxesWidth, y: basePoint.y)) //degrees in x axes let xDegreeNum: Int = Int((dataItem.xMax - (dataItem.xMax.truncatingRemainder(dividingBy: dataItem.xInterval))) / dataItem.xInterval) let xDegreeInterval: CGFloat = self.getXDegreeInterval() if dataItem.showXDegree { for i in 0 ..< xDegreeNum { let degreeX: CGFloat = basePoint.x + xDegreeInterval * CGFloat(i + 1) axesPath.move(to: CGPoint(x: degreeX, y: basePoint.y)) axesPath.addLine(to: CGPoint(x: degreeX, y: basePoint.y - dataItem.degreeLength)) } } //x axes arrow //arrow body axesPath.move(to: CGPoint(x: basePoint.x + xAxesWidth, y: basePoint.y)) axesPath.addLine(to: CGPoint(x: basePoint.x + xAxesWidth + dataItem.arrowBodyLength, y: basePoint.y)) //arrow head let arrowPath: UIBezierPath = UIBezierPath() arrowPath.lineWidth = dataItem.axesWidth arrowPath.lineCapStyle = CGLineCap.round arrowPath.lineJoinStyle = CGLineJoin.round let xArrowTopPoint: CGPoint = CGPoint(x: basePoint.x + xAxesWidth + dataItem.arrowBodyLength + dataItem.arrowHeight, y: basePoint.y) arrowPath.move(to: xArrowTopPoint) arrowPath.addLine(to: CGPoint(x: basePoint.x + xAxesWidth + dataItem.arrowBodyLength, y: basePoint.y - dataItem.arrowWidth / 2)) arrowPath.addLine(to: CGPoint(x: basePoint.x + xAxesWidth + dataItem.arrowBodyLength, y: basePoint.y + dataItem.arrowWidth / 2)) arrowPath.addLine(to: xArrowTopPoint) //y axes-------------------------------------- axesPath.move(to: CGPoint(x: basePoint.x, y: basePoint.y)) axesPath.addLine(to: CGPoint(x: basePoint.x, y: basePoint.y - yAxesHeight)) //degrees in y axes let yDegreesNum: Int = Int((dataItem.yMax - (dataItem.yMax.truncatingRemainder(dividingBy: dataItem.yInterval))) / dataItem.yInterval) let yDegreeInterval: CGFloat = self.getYDegreeInterval() if dataItem.showYDegree { for i in 0 ..< yDegreesNum { let degreeY: CGFloat = basePoint.y - yDegreeInterval * CGFloat(i + 1) axesPath.move(to: CGPoint(x: basePoint.x, y: degreeY)) axesPath.addLine(to: CGPoint(x: basePoint.x + dataItem.degreeLength, y: degreeY)) } } //y axes arrow //arrow body axesPath.move(to: CGPoint(x: basePoint.x, y: basePoint.y - yAxesHeight)) axesPath.addLine(to: CGPoint(x: basePoint.x, y: basePoint.y - yAxesHeight - dataItem.arrowBodyLength)) //arrow head let yArrowTopPoint: CGPoint = CGPoint(x: basePoint.x, y: basePoint.y - yAxesHeight - dataItem.arrowBodyLength - dataItem.arrowHeight) arrowPath.move(to: yArrowTopPoint) arrowPath.addLine(to: CGPoint(x: basePoint.x - dataItem.arrowWidth / 2, y: basePoint.y - yAxesHeight - dataItem.arrowBodyLength)) arrowPath.addLine(to: CGPoint(x: basePoint.x + dataItem.arrowWidth / 2, y: basePoint.y - yAxesHeight - dataItem.arrowBodyLength)) arrowPath.addLine(to: yArrowTopPoint) axesPath.stroke() arrowPath.stroke() //axes tips------------------------------------ //func getXAxesDegreeTipLabel(tipText: String, frame: CGRect, fontSize: CGFloat) -> UILabel { //MARK: - X 轴 下标 if (dataItem.xAxesDegreeTexts != nil) { for i in 0 ..< dataItem.xAxesDegreeTexts!.count { let size: CGSize = CGSize(width: xDegreeInterval - dataItem.degreeTipMarginHorizon * 2, height: dataItem.degreeTipFontSize) let center: CGPoint = CGPoint(x: basePoint.x + xDegreeInterval * CGFloat(i + 1), y: basePoint.y + dataItem.degreeTipMarginVertical + size.height / 2 ) let label: UILabel = self.getXAxesDegreeTipLabel(dataItem.xAxesDegreeTexts![i], center: center, size: size, fontSize: dataItem.degreeTipFontSize) label.backgroundColor = UIColor.red dataItem.targetView.addSubview(label) } } else { for i in 0 ..< xDegreeNum { let size: CGSize = CGSize(width: xDegreeInterval - dataItem.degreeTipMarginHorizon * 2, height: dataItem.degreeTipFontSize) let center: CGPoint = CGPoint(x: basePoint.x + xDegreeInterval * CGFloat(i + 1), y: basePoint.y + dataItem.degreeTipMarginVertical + size.height / 2) let label: UILabel = self.getXAxesDegreeTipLabel("\(CGFloat(i + 1) * dataItem.xInterval)", center: center, size: size, fontSize: dataItem.degreeTipFontSize) dataItem.targetView.addSubview(label) } } if (dataItem.yAxesDegreeTexts != nil) { for i in 0 ..< dataItem.yAxesDegreeTexts!.count { let size: CGSize = CGSize(width: dataItem.xAxesLeftMargin - dataItem.degreeTipMarginHorizon * 2, height: dataItem.degreeTipFontSize) let center: CGPoint = CGPoint(x: dataItem.xAxesLeftMargin / 2, y: basePoint.y - yDegreeInterval * CGFloat(i + 1)) let label: UILabel = self.getYAxesDegreeTipLabel(dataItem.yAxesDegreeTexts![i], center: center, size: size, fontSize: dataItem.degreeTipFontSize) dataItem.targetView.addSubview(label) } } else { for i in 0 ..< yDegreesNum { let size: CGSize = CGSize(width: dataItem.xAxesLeftMargin - dataItem.degreeTipMarginHorizon * 2, height: dataItem.degreeTipFontSize) let center: CGPoint = CGPoint(x: dataItem.xAxesLeftMargin / 2, y: basePoint.y - yDegreeInterval * CGFloat(i + 1)) let label: UILabel = self.getYAxesDegreeTipLabel("\(CGFloat(i + 1) * dataItem.yInterval/2)", center: center, size: size, fontSize: dataItem.degreeTipFontSize) dataItem.targetView.addSubview(label) } } } } }
gpl-3.0
9b695dbeb407fe47e84bbadc9e1bdcf6
44.070039
178
0.613485
4.392491
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Source/RatingContainerView.swift
2
6007
// // RatingContainerView.swift // edX // // Created by Danial Zahid on 1/23/17. // Copyright © 2017 edX. All rights reserved. // import UIKit protocol RatingContainerDelegate { func didSubmitRating(rating: Int) func closeButtonPressed() } class RatingContainerView: UIView { typealias Environment = protocol<DataManagerProvider, OEXInterfaceProvider, OEXStylesProvider> let environment : Environment private let viewHorizontalMargin = 50 private let contentView = UIView() private let descriptionLabel = UILabel() private let ratingView = RatingView() private let closeButton = UIButton() private let submitButton = UIButton() var delegate : RatingContainerDelegate? private var standardTextStyle : OEXTextStyle { let style = OEXMutableTextStyle(weight: OEXTextWeight.SemiBold, size: .Base, color: environment.styles.neutralXDark()) style.alignment = NSTextAlignment.Center descriptionLabel.lineBreakMode = .ByWordWrapping return style } private var disabledButtonStyle : ButtonStyle { return ButtonStyle(textStyle: OEXTextStyle(weight: OEXTextWeight.SemiBold, size: .Base, color: environment.styles.neutralWhite()), backgroundColor: environment.styles.neutralBase(), borderStyle: BorderStyle(cornerRadius: .Size(0), width: .Size(0), color: nil), contentInsets: nil, shadow: nil) } private var enabledButtonStyle : ButtonStyle { return ButtonStyle(textStyle: OEXTextStyle(weight: OEXTextWeight.SemiBold, size: .Base, color: environment.styles.neutralWhite()), backgroundColor: environment.styles.primaryBaseColor(), borderStyle: BorderStyle(cornerRadius: .Size(0), width: .Size(0), color: nil), contentInsets: nil, shadow: nil) } private var closeButtonTextStyle : OEXTextStyle { return OEXTextStyle(weight: .Normal, size: .XLarge, color: environment.styles.neutralDark()) } init(environment : Environment) { self.environment = environment super.init(frame: CGRectZero) //Setup view properties contentView.applyStandardContainerViewStyle() self.applyStandardContainerViewShadow() //Setup label properties descriptionLabel.numberOfLines = 0 descriptionLabel.attributedText = standardTextStyle.attributedStringWithText(Strings.AppReview.rateTheAppQuestion) //Setup Submit button toggleSubmitButton(false) submitButton.oex_addAction({[weak self] (action) in self?.delegate?.didSubmitRating(self!.ratingView.value) }, forEvents: UIControlEvents.TouchUpInside) //Setup close button closeButton.layer.cornerRadius = 15 closeButton.layer.borderColor = environment.styles.neutralDark().CGColor closeButton.layer.borderWidth = 1.0 closeButton.layer.masksToBounds = true closeButton.setAttributedTitle(Icon.Close.attributedTextWithStyle(closeButtonTextStyle), forState: UIControlState.Normal) closeButton.backgroundColor = UIColor.whiteColor() closeButton.accessibilityLabel = Strings.close closeButton.accessibilityHint = Strings.Accessibility.closeHint closeButton.oex_addAction({[weak self] (action) in self?.delegate?.closeButtonPressed() }, forEvents: UIControlEvents.TouchUpInside) //Setup ratingView action ratingView.oex_addAction({[weak self] (action) in self?.toggleSubmitButton(self?.ratingView.value > 0) }, forEvents: UIControlEvents.ValueChanged) addSubview(contentView) addSubview(closeButton) contentView.addSubview(descriptionLabel) contentView.addSubview(ratingView) contentView.addSubview(submitButton) setupConstraints() UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, descriptionLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupConstraints() { contentView.snp_remakeConstraints { (make) in make.edges.equalTo(snp_edges) } descriptionLabel.snp_remakeConstraints { (make) in make.top.equalTo(contentView.snp_top).offset(30) make.left.equalTo(contentView.snp_left).offset(viewHorizontalMargin) make.right.equalTo(contentView.snp_right).inset(viewHorizontalMargin) } ratingView.snp_remakeConstraints { (make) in make.top.equalTo(descriptionLabel.snp_bottom).offset(StandardVerticalMargin*2) make.left.greaterThanOrEqualTo(contentView.snp_left).offset(viewHorizontalMargin) make.right.greaterThanOrEqualTo(contentView.snp_right).inset(viewHorizontalMargin) make.centerX.equalTo(contentView.snp_centerX) } submitButton.snp_remakeConstraints { (make) in make.left.equalTo(contentView.snp_left) make.right.equalTo(contentView.snp_right) make.bottom.equalTo(contentView.snp_bottom) make.height.equalTo(40) make.top.equalTo(ratingView.snp_bottom).offset(StandardVerticalMargin*2) } closeButton.snp_remakeConstraints { (make) in make.height.equalTo(30) make.width.equalTo(30) make.right.equalTo(contentView.snp_right).offset(8) make.top.equalTo(contentView.snp_top).offset(-StandardVerticalMargin) } } private func toggleSubmitButton(enabled: Bool) { let style = enabled ? enabledButtonStyle : disabledButtonStyle submitButton.applyButtonStyle(style, withTitle: Strings.AppReview.submit) submitButton.userInteractionEnabled = enabled } func setRating(rating: Int) { ratingView.setRatingValue(rating) } }
apache-2.0
60a507caea917d06c45495507aab0bc1
40.42069
306
0.685315
5.218071
false
false
false
false
xeo-it/contacts-sample
totvs-contacts-test/ViewControllers/ContactsViewController.swift
1
7308
// // ViewController.swift // totvs-contacts-test // // Created by Francesco Pretelli on 30/01/16. // Copyright © 2016 Francesco Pretelli. All rights reserved. // import UIKit import ExpandingMenu import MessageUI class ContactsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, MFMailComposeViewControllerDelegate { @IBOutlet weak var tableview: UITableView! var pullToRefresh = UIRefreshControl() var completeList:[User] = [User]() var users:[User] = [User]() @IBOutlet weak var searchBar: UISearchBar! override func viewDidLoad() { super.viewDidLoad() title = "Contacts" tableview.delegate = self tableview.dataSource = self tableview.tableFooterView = UIView() searchBar.delegate = self let textFieldInsideSearchBar = searchBar.valueForKey("searchField") as? UITextField textFieldInsideSearchBar?.textColor = UIColor.whiteColor() setupPullToRefresh() setupMenuButton() navigationItem.hidesBackButton = true //startup update if Reachability.isConnectedToNetwork(){ pullToRefresh.beginRefreshing() tableview.setContentOffset(CGPoint(x: 0, y: -pullToRefresh.frame.size.height), animated: true) updateContacts(nil) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } //MARK: Setup Functions func setupMenuButton(){ let menuButtonSize: CGSize = CGSize(width: 64.0, height: 64.0) let menuButton = ExpandingMenuButton(frame: CGRect(origin: CGPointZero, size: menuButtonSize), centerImage: UIImage(named: "menu")!, centerHighlightedImage: UIImage(named: "menu-highlighted")!) menuButton.center = CGPointMake(self.view.bounds.width - 32.0, self.view.bounds.height - 48.0) view.addSubview(menuButton) let item1 = ExpandingMenuItem(size: menuButtonSize, title: "Logout", image: UIImage(named: "logout")!, highlightedImage: UIImage(named: "logout-highlighted")!, backgroundImage: UIImage(named: "chooser-moment-button"), backgroundHighlightedImage: UIImage(named: "chooser-moment-button-highlighted")) { () -> Void in self.navigationController?.popViewControllerAnimated(false) } let item2 = ExpandingMenuItem(size: menuButtonSize, title: "Hire Me :-)", image: UIImage(named: "hire")!, highlightedImage: UIImage(named: "hire-highlighted")!, backgroundImage: UIImage(named: "chooser-moment-button"), backgroundHighlightedImage: UIImage(named: "chooser-moment-button-highlighted")) { () -> Void in self.sendEmail() } menuButton.addMenuItems([item1, item2]) } func setupPullToRefresh(){ pullToRefresh.attributedTitle = NSAttributedString(string: NSLocalizedString("Downloading Contacts", comment: "")) pullToRefresh.addTarget(self, action: "updateContacts:", forControlEvents: UIControlEvents.ValueChanged) tableview.addSubview(pullToRefresh) } func sendEmail(){ let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self mailComposerVC.setToRecipients(["[email protected]"]) mailComposerVC.setSubject("We want to hire you!") mailComposerVC.setMessageBody("Great news! Your app is awesome and we want you to join the best team in the world!", isHTML: false) if MFMailComposeViewController.canSendMail() { self.presentViewController(mailComposerVC, animated: true, completion: nil) } else { let alertController = UIAlertController(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", preferredStyle: .Alert) let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(defaultAction) presentViewController(alertController, animated: true, completion: nil) } } func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { controller.dismissViewControllerAnimated(true, completion: nil) } //MARK: data handling func updateContacts(sender:AnyObject?){ if !Reachability.isConnectedToNetwork(){ pullToRefresh.endRefreshing() return } APIservice.sharedInstance.getUsers(){ (result:[User]) in self.users = result self.completeList = result self.tableview.reloadData() self.pullToRefresh.endRefreshing() } } func searchUser(text:String){ users = completeList.filter( { ($0.name?.containsString(text))!}) tableview.reloadData() } //MARK: Search Bar Delegate functions func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if searchText != "" { searchUser(searchText) } else { users = completeList tableview.reloadData() } } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } func searchBarCancelButtonClicked(searchBar: UISearchBar) { users = completeList tableview.reloadData() } //MARK: TableView Delegate Functions func scrollViewDidScroll(scrollView: UIScrollView) { searchBar.resignFirstResponder() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier("ContactCell", forIndexPath: indexPath) as! ContactCell let user = users[indexPath.row] cell.updateData(user) cell.layer.shouldRasterize = true cell.layer.rasterizationScale = UIScreen.mainScreen().scale indexPath.row % 2 == 0 ? (cell.backgroundColor = UIColor(hex: 0x0066C2)) : (cell.backgroundColor = UIColor(hex: 0x267AC7)) return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ tableView.deselectRowAtIndexPath(indexPath, animated: true) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowContactSegue" { if let destination = segue.destinationViewController as? ContactDetailViewController { if let indx = tableview.indexPathForSelectedRow?.row { destination.currentUser = users[indx] } } } } }
mit
b5ba938339b09198ddb738906b36aa9f
38.284946
323
0.663884
5.523054
false
false
false
false
tardieu/swift
validation-test/Reflection/reflect_multiple_types.swift
10
13430
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_multiple_types // RUN: %target-run %target-swift-reflection-test %t/reflect_multiple_types 2>&1 | %FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop // REQUIRES: executable_test // FIXME: https://bugs.swift.org/browse/SR-2808 // XFAIL: resilient_stdlib import SwiftReflectionTest import Foundation class TestClass { var t00: Array<Int> var t01: Bool var t02: Character var t03: Dictionary<Int, Int> var t04: Double var t05: Float var t06: Int var t07: Int16 var t08: Int32 var t09: Int64 var t10: Int8 var t11: NSArray var t12: NSNumber var t13: NSSet var t14: NSString var t15: Set<Int> var t16: String var t17: UInt var t18: UInt16 var t19: UInt32 var t20: UInt64 var t21: UInt8 init( t00: Array<Int>, t01: Bool, t02: Character, t03: Dictionary<Int, Int>, t04: Double, t05: Float, t06: Int, t07: Int16, t08: Int32, t09: Int64, t10: Int8, t11: NSArray, t12: NSNumber, t13: NSSet, t14: NSString, t15: Set<Int>, t16: String, t17: UInt, t18: UInt16, t19: UInt32, t20: UInt64, t21: UInt8 ) { self.t00 = t00 self.t01 = t01 self.t02 = t02 self.t03 = t03 self.t04 = t04 self.t05 = t05 self.t06 = t06 self.t07 = t07 self.t08 = t08 self.t09 = t09 self.t10 = t10 self.t11 = t11 self.t12 = t12 self.t13 = t13 self.t14 = t14 self.t15 = t15 self.t16 = t16 self.t17 = t17 self.t18 = t18 self.t19 = t19 self.t20 = t20 self.t21 = t21 } } var obj = TestClass( t00: [1, 2, 3], t01: true, t02: "A", t03: [1: 3, 2: 2, 3: 1], t04: 123.45, t05: 123.45, t06: 123, t07: 123, t08: 123, t09: 123, t10: 123, t11: [1, 2, 3], t12: 123, t13: [1, 2, 3, 3, 2, 1], t14: "Hello, NSString!", t15: [1, 2, 3, 3, 2, 1], t16: "Hello, Reflection!", t17: 123, t18: 123, t19: 123, t20: 123, t21: 123 ) reflect(object: obj) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_multiple_types.TestClass) // CHECK-64: Type info: // CHECK-64: (class_instance size=193 alignment=8 stride=200 num_extra_inhabitants=0 // CHECK-64: (field name=t00 offset=16 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=1 // (unstable implementation details omitted) // CHECK-64: (field name=t01 offset=24 // CHECK-64: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254)))) // CHECK-64: (field name=t02 offset=32 // CHECK-64: (struct size=9 alignment=8 stride=16 num_extra_inhabitants=0 // CHECK-64: (field name=_representation offset=0 // CHECK-64: (multi_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 // CHECK-64: (field name=large offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=2147483646 // CHECK-64: (field name=_storage offset=0 // CHECK-64: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=2147483646 // CHECK-64: (field name=some offset=0 // CHECK-64: (reference kind=strong refcounting=native)))))) // CHECK-64: (field name=small offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647)))))) // CHECK-64: (field name=t03 offset=48 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // (unstable implementation details omitted) // CHECK-64: (field name=t04 offset=56 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))) // CHECK-64: (field name=t05 offset=64 // CHECK-64: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))) // CHECK-64: (field name=t06 offset=72 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))) // CHECK-64: (field name=t07 offset=80 // CHECK-64: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0)))) // CHECK-64: (field name=t08 offset=84 // CHECK-64: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))) // CHECK-64: (field name=t09 offset=88 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))) // CHECK-64: (field name=t10 offset=96 // CHECK-64: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0)))) // CHECK-64: (field name=t11 offset=104 // CHECK-64: (reference kind=strong refcounting=unknown)) // CHECK-64: (field name=t12 offset=112 // CHECK-64: (reference kind=strong refcounting=unknown)) // CHECK-64: (field name=t13 offset=120 // CHECK-64: (reference kind=strong refcounting=unknown)) // CHECK-64: (field name=t14 offset=128 // CHECK-64: (reference kind=strong refcounting=unknown)) // CHECK-64: (field name=t15 offset=136 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // (unstable implementation details omitted) // CHECK-64: (field name=t16 offset=144 // CHECK-64: (struct size=24 alignment=8 stride=24 num_extra_inhabitants=0 // (unstable implementation details omitted) // CHECK-64: (field name=t17 offset=168 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))) // CHECK-64: (field name=t18 offset=176 // CHECK-64: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0)))) // CHECK-64: (field name=t19 offset=180 // CHECK-64: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))) // CHECK-64: (field name=t20 offset=184 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))) // CHECK-64: (field name=t21 offset=192 // CHECK-64: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))) // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_multiple_types.TestClass) // CHECK-32: Type info: // CHECK-32: (class_instance size=129 alignment=8 stride=136 num_extra_inhabitants=0 // CHECK-32: (field name=t00 offset=12 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=1 // (unstable implementation details omitted) // CHECK-32: (field name=t01 offset=16 // CHECK-32: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254)))) // CHECK-32: (field name=t02 offset=24 // CHECK-32: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-32: (field name=_representation offset=0 // CHECK-32: (multi_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-32: (field name=large offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=4095 // CHECK-32: (field name=_storage offset=0 // CHECK-32: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095 // CHECK-32: (field name=some offset=0 // CHECK-32: (reference kind=strong refcounting=native)))))) // CHECK-32: (field name=small offset=0 // CHECK-32: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647)))))) // CHECK-32: (field name=t03 offset=32 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // (unstable implementation details omitted) // CHECK-32: (field name=t04 offset=40 // CHECK-32: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))) // CHECK-32: (field name=t05 offset=48 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))) // CHECK-32: (field name=t06 offset=52 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))) // CHECK-32: (field name=t07 offset=56 // CHECK-32: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0)))) // CHECK-32: (field name=t08 offset=60 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))) // CHECK-32: (field name=t09 offset=64 // CHECK-32: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))) // CHECK-32: (field name=t10 offset=72 // CHECK-32: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0)))) // CHECK-32: (field name=t11 offset=76 // CHECK-32: (reference kind=strong refcounting=unknown)) // CHECK-32: (field name=t12 offset=80 // CHECK-32: (reference kind=strong refcounting=unknown)) // CHECK-32: (field name=t13 offset=84 // CHECK-32: (reference kind=strong refcounting=unknown)) // CHECK-32: (field name=t14 offset=88 // CHECK-32: (reference kind=strong refcounting=unknown)) // CHECK-32: (field name=t15 offset=92 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // (unstable implementation details omitted) // CHECK-32: (field name=t16 offset=96 // CHECK-32: (struct size=12 alignment=4 stride=12 num_extra_inhabitants=0 // (unstable implementation details omitted) // CHECK-32: (field name=t17 offset=108 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))) // CHECK-32: (field name=t18 offset=112 // CHECK-32: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0)))) // CHECK-32: (field name=t19 offset=116 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))) // CHECK-32: (field name=t20 offset=120 // CHECK-32: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))) // CHECK-32: (field name=t21 offset=128 // CHECK-32: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
apache-2.0
e810b02da771ae33bcf79a9d0ce9013e
43.766667
133
0.642293
3.125436
false
false
false
false
filestack/filestack-ios
Sources/Filestack/UI/Internal/PhotoEditor/EditionController/Layers/CropLayer.swift
1
4070
// // CropLayer.swift // EditImage // // Created by Mihály Papp on 12/07/2018. // Copyright © 2018 Mihály Papp. All rights reserved. // import UIKit class CropLayer: CALayer { var imageFrame = CGRect.zero { didSet { updateSublayers() } } var cropRect = CGRect.zero { didSet { updateSublayers() } } override init() { super.init() addSublayer(outsideLayer) addSublayer(gridLayer) addSublayer(cornersLayer) } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var outsideLayer: CAShapeLayer = { let layer = CAShapeLayer() layer.path = outsidePath layer.fillRule = .evenOdd layer.backgroundColor = UIColor.black.cgColor layer.opacity = 0.5 return layer }() private lazy var gridLayer: CAShapeLayer = { let layer = CAShapeLayer() layer.path = gridPath layer.lineWidth = 0.5 layer.strokeColor = UIColor.white.cgColor layer.backgroundColor = UIColor.clear.cgColor layer.fillColor = UIColor.clear.cgColor return layer }() private lazy var cornersLayer: CAShapeLayer = { let layer = CAShapeLayer() layer.path = cornersPath layer.lineWidth = 2 layer.strokeColor = UIColor.white.cgColor layer.backgroundColor = UIColor.clear.cgColor layer.fillColor = UIColor.clear.cgColor return layer }() } /// :nodoc: private extension CropLayer { func updateSublayers() { outsideLayer.path = outsidePath gridLayer.path = gridPath cornersLayer.path = cornersPath } var outsidePath: CGPath { let path = UIBezierPath(rect: cropRect) path.append(UIBezierPath(rect: imageFrame)) return path.cgPath } var gridPath: CGPath { let gridWidth = cropRect.size.width / 3 let gridHeight = cropRect.size.height / 3 let path = UIBezierPath(rect: cropRect) path.move(to: cropRect.origin.movedBy(x: gridWidth)) path.addLine(to: path.currentPoint.movedBy(y: gridHeight * 3)) path.move(to: cropRect.origin.movedBy(x: gridWidth * 2)) path.addLine(to: path.currentPoint.movedBy(y: gridHeight * 3)) path.move(to: cropRect.origin.movedBy(y: gridHeight)) path.addLine(to: path.currentPoint.movedBy(x: gridWidth * 3)) path.move(to: cropRect.origin.movedBy(y: gridHeight * 2)) path.addLine(to: path.currentPoint.movedBy(x: gridWidth * 3)) return path.cgPath } var cornersPath: CGPath { let thickness: CGFloat = 2 let lenght: CGFloat = 20 let horizontalWidth = min(lenght, cropRect.size.width) + thickness let verticalWidth = min(lenght, cropRect.size.height) let margin = UIEdgeInsets(top: -thickness / 2, left: -thickness / 2, bottom: -thickness / 2, right: -thickness / 2) let outerRect = cropRect.inset(by: margin) let path = UIBezierPath() path.move(to: outerRect.origin.movedBy(y: verticalWidth)) path.addLine(to: path.currentPoint.movedBy(y: -verticalWidth)) path.addLine(to: path.currentPoint.movedBy(x: horizontalWidth)) path.move(to: outerRect.origin.movedBy(x: outerRect.size.width - horizontalWidth)) path.addLine(to: path.currentPoint.movedBy(x: horizontalWidth)) path.addLine(to: path.currentPoint.movedBy(y: verticalWidth)) path.move(to: outerRect.origin.movedBy(x: outerRect.size.width, y: outerRect.size.height - verticalWidth)) path.addLine(to: path.currentPoint.movedBy(y: verticalWidth)) path.addLine(to: path.currentPoint.movedBy(x: -horizontalWidth)) path.move(to: outerRect.origin.movedBy(y: outerRect.size.height - verticalWidth)) path.addLine(to: path.currentPoint.movedBy(y: verticalWidth)) path.addLine(to: path.currentPoint.movedBy(x: horizontalWidth)) return path.cgPath } }
mit
4991ab916e252293a84e1cde95792997
34.060345
123
0.644455
4.128934
false
false
false
false
franklinsch/marylouios
MarylouiOS/MarylouiOS/HomeViewController.swift
1
5127
// // ViewController.swift // MarylouiOS // // Created by Franklin Schrans on 07/02/2015. // Copyright (c) 2015 Franklin Schrans. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var safetyField: UITextField! @IBOutlet weak var priceField: UITextField! @IBOutlet weak var weatherField: UITextField! @IBOutlet weak var safetyView: UIView! @IBOutlet weak var resultLabel: UILabel! var resultCities : Array<String!> = [] var resultGeoLocs : Array<String!> = [] @IBAction func search(sender: AnyObject) { getResultsFromServer() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } @IBOutlet weak var tableview: UITableView! func doHTTPPost() { var request = NSMutableURLRequest(URL: NSURL(string: "http://www.freddielindsey.me:3000/getcities")!) var session = NSURLSession.sharedSession() request.HTTPMethod = "POST" var params = ["slevel":"I", "plevel" : "like", "wlevel" : "pie"] as Dictionary<String, String> var err: NSError? request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in var strData = NSString(data: data, encoding: NSUTF8StringEncoding) var err: NSError? var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary if(err != nil) { println(err!.localizedDescription) let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding) } else { if let parseJSON = json { var success = parseJSON["success"] as? Int println("Succes: \(success)") } else { let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding) println("Error could not parse JSON: \(jsonStr)") } } }) task.resume() } func getResultsFromServer() { DataManager.getDataFromServerWithSuccess { (ServerData) -> Void in let json = JSON(data: ServerData) println("json \(json)") for (key: String, subJson: JSON) in json { if let appName = json[key.toInt()!]["name"].stringValue as String? { self.resultCities.append(appName) } if let appName = json[key.toInt()!]["geo"].stringValue as String? { self.resultGeoLocs.append(appName) } } println("Got cities : \(self.resultCities)") println("Got geolocs : \(self.resultGeoLocs)") NSUserDefaults.standardUserDefaults().setObject(self.resultCities, forKey:"cities") NSUserDefaults.standardUserDefaults().setObject(self.resultGeoLocs, forKey:"geolocs") NSUserDefaults.standardUserDefaults().synchronize() } } func getResultsFromFileWithValues(NSArray) { DataManager.getTopAppsDataFromFileWithSuccess { (FileData) -> Void in //≈ sleep(10); let json = JSON(data: FileData) // println(json) for (key: String, subJson: JSON) in json { if let appName = json[key.toInt()!]["name"].stringValue as String? { self.resultCities.append(appName) } if let appName = json[key.toInt()!]["geo"].stringValue as String? { self.resultGeoLocs.append(appName) } } println("Got cities : \(self.resultCities)") println("Got geolocs : \(self.resultGeoLocs)") NSUserDefaults.standardUserDefaults().setObject(self.resultCities, forKey:"cities") NSUserDefaults.standardUserDefaults().setObject(self.resultGeoLocs, forKey:"geolocs") NSUserDefaults.standardUserDefaults().synchronize() } } 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. } }
apache-2.0
52130706597553f7745992563dfa8257
36.137681
122
0.545951
5.440552
false
false
false
false
weibo3721/ZeroTier-iOS
ZeroTier One/ZeroTier One/NetworkInfoViewController.swift
1
4974
// // NetworkInfoViewController.swift // ZeroTier One // // Created by Grant Limberg on 12/31/15. // Copyright © 2015 Zero Tier, Inc. All rights reserved. // import UIKit import NetworkExtension class NetworkInfoViewController: UIViewController, ConnectedNetworkMonitorDelegate { var manager: ZTVPN! @IBOutlet var networkIdLabel: UILabel! @IBOutlet var networkNameLabel: UILabel! @IBOutlet var statusLabel: UILabel! @IBOutlet var typeLabel: UILabel! @IBOutlet var macLabel: UILabel! @IBOutlet var mtuLabel: UILabel! @IBOutlet var broadcastLabel: UILabel! @IBOutlet var bridgingLabel: UILabel! @IBOutlet var managedIPsLabel: UILabel! @IBOutlet var routeViaZTSwitch: UISwitch! @IBOutlet var restartRequiredLabel: UILabel! var _deviceId: String? = nil var _networkMonitor: ConnectedNetworkMonitor? override func viewDidLoad() { super.viewDidLoad() _networkMonitor = ConnectedNetworkMonitor(delegate: self) loadViewInformation() restartRequiredLabel.isHidden = true let defaults = UserDefaults.standard if var deviceId = defaults.string(forKey: "com.zerotier.one.deviceId") { while deviceId.characters.count < 10 { deviceId = "0\(deviceId)" } _deviceId = deviceId let idButton = UIBarButtonItem(title: deviceId, style: .plain, target: self, action: #selector(NetworkInfoViewController.copyId(_:))) idButton.tintColor = UIColor.white self.setToolbarItems([idButton], animated: true) } if let mgr = manager as? ZTVPN_Device { let proto = mgr.mgr.protocolConfiguration as! NETunnelProviderProtocol if let allowDefault = proto.providerConfiguration?["allowDefault"] as? NSNumber { routeViaZTSwitch.isOn = allowDefault.boolValue } else { routeViaZTSwitch.isOn = false } } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !_networkMonitor!.refreshRunning { loadViewInformation() } //PiwikTracker.sharedInstance().sendView("Network Info"); } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) _networkMonitor!.stopMonitor() } func loadViewInformation() { _networkMonitor!.startMonitor(manager) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func copyId(_ sender: AnyObject) { if let id = _deviceId { //DDLogDebug("id \(id) copied!") let pb = UIPasteboard.general pb.string = id } } func onNetworkStatusReceived(_ networkInfo: NetworkInfo) { self.networkIdLabel.text = networkInfo.networkId self.networkNameLabel.text = networkInfo.networkName self.statusLabel.text = networkInfo.status self.typeLabel.text = networkInfo.type self.macLabel.text = networkInfo.macAddress self.mtuLabel.text = networkInfo.mtu self.broadcastLabel.text = networkInfo.broadcast self.bridgingLabel.text = networkInfo.bridging var ipString = "" let constrainedWidth = self.managedIPsLabel.frame.width let fontName = self.managedIPsLabel.font.fontName var fontSize = self.managedIPsLabel.font.pointSize var labelFont = UIFont(name: fontName, size: fontSize)! var maxAdjustedWidth : CGFloat = 0.0 if let managedIPs = networkInfo.managedIPs { for (index,ip) in managedIPs.enumerated() { let nsIp = ip as NSString var outputSize = nsIp.size(attributes: [NSFontAttributeName: labelFont]) if outputSize.width > maxAdjustedWidth { while outputSize.width > constrainedWidth { fontSize -= 1.0 labelFont = UIFont(name: fontName, size: fontSize)! outputSize = nsIp.size(attributes: [NSFontAttributeName: labelFont]) } maxAdjustedWidth = outputSize.width managedIPsLabel.font = labelFont } ipString += ip if index < (managedIPs.count - 1) { ipString += "\n" } } } self.managedIPsLabel.text = ipString } @IBAction func onRoutingSwitchChanged(_ sender: AnyObject) { if let mgr = manager as? ZTVPN_Device { let proto = mgr.mgr.protocolConfiguration as! NETunnelProviderProtocol proto.providerConfiguration!["allowDefault"] = NSNumber(value: routeViaZTSwitch.isOn as Bool) } manager.save() restartRequiredLabel.isHidden = false } }
mit
76a62f97da449e8f439948bf955ef1cb
31.933775
145
0.624372
4.94334
false
false
false
false
10686142/eChance
Iraffle/WebPageVC.swift
1
1479
// // WebPageVC.swift // Iraffle // // Created by Vasco Meerman on 03/05/2017. // Copyright © 2017 Vasco Meerman. All rights reserved. // import UIKit class WebPageVC: UIViewController, UIWebViewDelegate { // MARK: - Outlets. @IBOutlet weak var backToMoreButton: UIButton! @IBOutlet weak var webView: UIWebView! @IBOutlet weak var labelSource: UILabel! // MARK: - Contants and Variables. let defaults = UserDefaults.standard var showURL: URL! override func viewDidLoad() { super.viewDidLoad() webView.delegate = self if let incomingURL = UserDefaults.standard.value(forKey: "webPageURL"){ showURL = URL(string: incomingURL as! String) let request = URLRequest(url: showURL) webView.loadRequest(request) } if let incomingSource = UserDefaults.standard.value(forKey: "sourceURL"){ labelSource.text = (incomingSource as! String) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func backToMoreTapped(_ sender: Any) { defaults.removeObject(forKey: "webPageURL") defaults.removeObject(forKey: "sourceURL") let vc = storyboard?.instantiateViewController(withIdentifier: "moreInfoVC") as! MoreVC present(vc, animated: true, completion: nil) } }
mit
090979943965ab9b3b210b212bbaec04
27.980392
95
0.643437
4.547692
false
false
false
false
edx/edx-app-ios
Source/ProfileOptionsViewController.swift
1
46480
// // ProfileOptionsViewController.swift // edX // // Created by Muhammad Umer on 27/07/2021. // Copyright © 2021 edX. All rights reserved. // import UIKit import MessageUI fileprivate let titleTextStyle = OEXMutableTextStyle(weight: .light, size: .small, color: OEXStyles.shared().neutralXDark()) fileprivate let subtitleTextStyle = OEXMutableTextStyle(weight: .bold, size: .base, color: OEXStyles.shared().primaryDarkColor()) fileprivate let imageSize: CGFloat = 36 class ProfileOptionsViewController: UIViewController { private enum ProfileOptions { case videoSetting case personalInformation case restorePurchase case help(Bool, Bool) case signout case deleteAccount } typealias Environment = OEXStylesProvider & OEXConfigProvider & NetworkManagerProvider & DataManagerProvider & OEXRouterProvider & OEXSessionProvider & OEXInterfaceProvider & OEXAnalyticsProvider let environment: Environment private let crossButtonSize: CGFloat = 20 private lazy var tableView: UITableView = { let tableView = UITableView() tableView.tableFooterView = UIView() tableView.rowHeight = UITableView.automaticDimension tableView.dataSource = self tableView.delegate = self tableView.separatorInset = .zero tableView.alwaysBounceVertical = false tableView.register(VideoSettingCell.self, forCellReuseIdentifier: VideoSettingCell.identifier) tableView.register(PersonalInformationCell.self, forCellReuseIdentifier: PersonalInformationCell.identifier) tableView.register(RestorePurchasesCell.self, forCellReuseIdentifier: RestorePurchasesCell.identifier) tableView.register(HelpCell.self, forCellReuseIdentifier: HelpCell.identifier) tableView.register(SignOutVersionCell.self, forCellReuseIdentifier: SignOutVersionCell.identifier) tableView.register(DeleteAccountCell.self, forCellReuseIdentifier: DeleteAccountCell.identifier) tableView.accessibilityIdentifier = "ProfileOptionsViewController:table-view" return tableView }() private var options: [ProfileOptions] = [] private var userProfile: UserProfile? { didSet { for cell in tableView.visibleCells where cell is PersonalInformationCell { if let indexPath = tableView.indexPath(for: cell) { tableView.reloadRows(at: [indexPath], with: .none) } } } } init(environment: Environment) { self.environment = environment super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = Strings.UserAccount.profile setupViews() addCloseButton() configureOptions() setupProfileLoader() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) environment.analytics.trackScreen(withName: AnalyticsScreenName.Profile.rawValue) setupProfileLoader() } private func setupViews() { view.backgroundColor = environment.styles.standardBackgroundColor() view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalTo(view) } } private func setupProfileLoader() { guard environment.config.profilesEnabled else { return } let profileFeed = environment.dataManager.userProfileManager.feedForCurrentUser() if let profile = profileFeed.output.value { userProfile = profile } else { profileFeed.output.listen(self, success: { [weak self] profile in self?.userProfile = profile }, failure : { _ in Logger.logError("Profiles", "Unable to fetch profile") }) profileFeed.refresh() } } private func addCloseButton() { let closeButton = UIBarButtonItem(image: Icon.Close.imageWithFontSize(size: crossButtonSize), style: .plain, target: nil, action: nil) closeButton.accessibilityLabel = Strings.Accessibility.closeLabel closeButton.accessibilityHint = Strings.Accessibility.closeHint closeButton.accessibilityIdentifier = "ProfileOptionsViewController:close-button" navigationItem.rightBarButtonItem = closeButton closeButton.oex_setAction { [weak self] in self?.dismiss(animated: true, completion: nil) } } private func configureOptions() { options.append(.videoSetting) if environment.config.profilesEnabled { options.append(.personalInformation) } if environment.config.inappPurchasesEnabled { options.append(.restorePurchase) } let feedbackEnabled = environment.config.feedbackEmailAddress() != nil let faqEnabled = environment.config.faqURL != nil if feedbackEnabled || faqEnabled { options.append(.help(feedbackEnabled, faqEnabled)) } options.append(.signout) if environment.config.deleteAccountURL != nil { options.append(.deleteAccount) } tableView.reloadData() } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .allButUpsideDown } deinit { NotificationCenter.default.removeObserver(self) } } extension ProfileOptionsViewController: MFMailComposeViewControllerDelegate { func launchEmailComposer() { if !MFMailComposeViewController.canSendMail() { UIAlertController().showAlert(withTitle: Strings.emailAccountNotSetUpTitle, message: Strings.emailAccountNotSetUpMessage, onViewController: self) } else { let mail = MFMailComposeViewController() mail.mailComposeDelegate = self mail.navigationBar.tintColor = OEXStyles.shared().navigationItemTintColor() mail.setSubject(Strings.SubmitFeedback.messageSubject) mail.setMessageBody(EmailTemplates.supportEmailMessageTemplate(), isHTML: false) if let fbAddress = environment.config.feedbackEmailAddress() { mail.setToRecipients([fbAddress]) } present(mail, animated: true, completion: nil) } } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { dismiss(animated: true, completion: nil) } } extension ProfileOptionsViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView(frame: .zero) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch options[indexPath.row] { case .videoSetting: return wifiCell(tableView, indexPath: indexPath) case .personalInformation: return personalInformationCell(tableView, indexPath: indexPath) case .restorePurchase: return restorePurchaseCell(tableView, indexPath: indexPath) case .help(let feedbackEnabled, let faqEnabled): return helpCell(tableView, indexPath: indexPath, feedbackEnabled: feedbackEnabled, faqEnabled: faqEnabled) case .signout: return signoutCell(tableView, indexPath: indexPath) case .deleteAccount: return deleteAccountCell(tableView, indexPath: indexPath) } } private func wifiCell(_ tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: VideoSettingCell.identifier, for: indexPath) as! VideoSettingCell cell.delegate = self cell.wifiSwitch.isOn = environment.interface?.shouldDownloadOnlyOnWifi ?? false cell.updateVideoDownloadQualityLabel() return cell } private func personalInformationCell(_ tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: PersonalInformationCell.identifier, for: indexPath) as! PersonalInformationCell guard environment.config.profilesEnabled, let username = environment.session.currentUser?.username, let email = environment.session.currentUser?.email else { return cell } if let userProfile = userProfile { cell.profileSubtitle = (userProfile.sharingLimitedProfile && userProfile.parentalConsent == false) ? Strings.ProfileOptions.UserProfile.message : nil cell.profileImageView.remoteImage = userProfile.image(networkManager: environment.networkManager) } cell.update(username: username, email: email) return cell } private func restorePurchaseCell(_ tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: RestorePurchasesCell.identifier, for: indexPath) as! RestorePurchasesCell } private func helpCell(_ tableView: UITableView, indexPath: IndexPath, feedbackEnabled: Bool, faqEnabled: Bool) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: HelpCell.identifier, for: indexPath) as! HelpCell cell.delegate = self cell.update(feedbackEnabled: feedbackEnabled, faqEnabled: faqEnabled, platformName: environment.config.platformName()) return cell } private func signoutCell(_ tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SignOutVersionCell.identifier, for: indexPath) as! SignOutVersionCell cell.delegate = self return cell } private func deleteAccountCell(_ tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: DeleteAccountCell.identifier, for: indexPath) as! DeleteAccountCell cell.delegate = self return cell } } extension ProfileOptionsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch options[indexPath.row] { case .personalInformation: guard environment.config.profilesEnabled, let username = environment.session.currentUser?.username else { return } environment.router?.showProfileForUsername(controller: self, username: username, editable: true) environment.analytics.trackProfileOptionClcikEvent(displayName: AnalyticsDisplayName.PersonalInformationClicked, name: AnalyticsEventName.PersonalInformationClicked) default: return } } } extension ProfileOptionsViewController: DownloadCellDelagete { func didTapWifiSwitch(isOn: Bool, wifiSwitch: UISwitch) { environment.analytics.trackWifi(isOn: isOn) if isOn { environment.interface?.setDownloadOnlyOnWifiPref(isOn) } else { let alertController = UIAlertController().showAlert(withTitle: Strings.cellularDownloadEnabledTitle, message: Strings.cellularDownloadEnabledMessage, cancelButtonTitle: nil, onViewController: self) { _, _, _ in } alertController.addButton(withTitle: Strings.doNotAllow) { [weak self] _ in self?.environment.analytics.trackWifi(allowed: false) wifiSwitch.setOn(true, animated: true) } alertController.addButton(withTitle: Strings.allow) { [weak self] _ in self?.environment.interface?.setDownloadOnlyOnWifiPref(isOn) self?.environment.analytics.trackWifi(allowed: true) } } } func didTapVideoQuality() { environment.analytics.trackEvent(with: AnalyticsDisplayName.ProfileVideoDownloadQualityClicked, name: AnalyticsEventName.ProfileVideoDownloadQualityClicked) environment.router?.showDownloadVideoQuality(from: self, delegate: self) } } extension ProfileOptionsViewController: VideoDownloadQualityDelegate { func didUpdateVideoQuality() { for cell in tableView.visibleCells where cell is VideoSettingCell { if let cell = cell as? VideoSettingCell { cell.updateVideoDownloadQualityLabel() } } } } extension ProfileOptionsViewController: HelpCellDelegate { func didTapEmail() { environment.analytics.trackProfileOptionClcikEvent(displayName: AnalyticsDisplayName.EmailSupportClicked, name: AnalyticsEventName.EmailSupportClicked) launchEmailComposer() } func didTapFAQ() { guard let faqURL = environment.config.faqURL, let url = URL(string: faqURL) else { return } environment.analytics.trackProfileOptionClcikEvent(displayName: AnalyticsDisplayName.FAQClicked, name: AnalyticsEventName.FAQClicked) if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } } extension ProfileOptionsViewController: SignoutCellDelegate { func didSingout() { OEXFileUtility.nukeUserPIIData() dismiss(animated: true) { [weak self] in self?.environment.router?.logout() } } } extension ProfileOptionsViewController: DeleteAccountCellDelegate { func didTapDeleteAccount() { guard let topController = UIApplication.shared.topMostController(), let URLString = environment.config.deleteAccountURL, let URL = URL(string: URLString) else { return } environment.analytics.trackEvent(with: AnalyticsDisplayName.ProfileDeleteAccountClicked, name: AnalyticsEventName.ProfileDeleteAccountClicked) environment.router?.showBrowserViewController(from: topController, title: Strings.ProfileOptions.Deleteaccount.webviewTitle, url: URL, alwaysRequireAuth: true) } } protocol DownloadCellDelagete: AnyObject { func didTapWifiSwitch(isOn: Bool, wifiSwitch: UISwitch) func didTapVideoQuality() } class VideoSettingCell: UITableViewCell { static let identifier = "VideoSettingCell" weak var delegate: DownloadCellDelagete? private lazy var wifiContainer = UIView() private lazy var videoQualityContainer = UIView() private lazy var optionLabel: UILabel = { let label = UILabel() label.attributedText = titleTextStyle.attributedString(withText: Strings.ProfileOptions.VideoSettings.title) label.accessibilityIdentifier = "VideoSettingCell:option-label" return label }() private lazy var videoSettingDescriptionLabel: UILabel = { let label = UILabel() label.attributedText = subtitleTextStyle.attributedString(withText: Strings.ProfileOptions.VideoSettings.heading) label.accessibilityIdentifier = "VideoSettingCell:video-setting-description-label" return label }() private lazy var videoSettingSubtitleLabel: UILabel = { let label = UILabel() label.attributedText = titleTextStyle.attributedString(withText: Strings.ProfileOptions.VideoSettings.message) label.accessibilityIdentifier = "VideoSettingCell:video-setting-subtitle-label" return label }() lazy var wifiSwitch: UISwitch = { let toggleSwitch = UISwitch() toggleSwitch.oex_addAction({ [weak self] _ in self?.delegate?.didTapWifiSwitch(isOn: toggleSwitch.isOn, wifiSwitch: toggleSwitch) }, for: .valueChanged) toggleSwitch.accessibilityIdentifier = "VideoSettingCell:wifi-switch" OEXStyles.shared().standardSwitchStyle().apply(to: toggleSwitch) return toggleSwitch }() private lazy var videoQualityDescriptionLabel: UILabel = { let label = UILabel() label.attributedText = subtitleTextStyle.attributedString(withText: Strings.videoDownloadQualityTitle) label.accessibilityIdentifier = "VideoSettingCell:video-quality-description-label" return label }() private lazy var videoQualitySubtitleLabel: UILabel = { let label = UILabel() label.accessibilityIdentifier = "VideoSettingCell:video-quality-subtitle-label" return label }() private lazy var chevronImageView: UIImageView = { let imageView = UIImageView() imageView.image = Icon.ChevronRight.imageWithFontSize(size: imageSize) imageView.tintColor = OEXStyles.shared().primaryBaseColor() imageView.isAccessibilityElement = false imageView.accessibilityIdentifier = "VideoSettingCell:chevron-image-view" return imageView }() private lazy var videoQualityButton: UIButton = { let button = UIButton() button.oex_addAction({ [weak self] _ in self?.delegate?.didTapVideoQuality() }, for: .touchUpInside) button.accessibilityIdentifier = "VideoSettingCell:video-quality-button" return button }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none accessibilityIdentifier = "ProfileOptionsViewController:video-setting-cell" setupViews() setupConstrains() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupViews() { contentView.addSubview(optionLabel) contentView.addSubview(wifiContainer) wifiContainer.addSubview(videoSettingDescriptionLabel) wifiContainer.addSubview(wifiSwitch) wifiContainer.addSubview(videoSettingSubtitleLabel) contentView.addSubview(videoQualityContainer) videoQualityContainer.addSubview(videoQualityDescriptionLabel) videoQualityContainer.addSubview(videoQualitySubtitleLabel) videoQualityContainer.addSubview(chevronImageView) videoQualityContainer.addSubview(videoQualityButton) } private func setupConstrains() { optionLabel.snp.makeConstraints { make in make.top.equalTo(contentView).offset(StandardVerticalMargin + (StandardVerticalMargin / 2)) make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView).inset(StandardHorizontalMargin) } wifiContainer.snp.makeConstraints { make in make.top.equalTo(optionLabel.snp.bottom).offset(StandardVerticalMargin) make.leading.equalTo(contentView).offset(StandardVerticalMargin) make.trailing.equalTo(contentView).inset(StandardVerticalMargin) make.bottom.equalTo(videoSettingDescriptionLabel.snp.bottom).offset(StandardVerticalMargin) } wifiSwitch.snp.makeConstraints { make in make.trailing.equalTo(wifiContainer).inset(StandardVerticalMargin) make.centerY.equalTo(videoSettingDescriptionLabel) } videoSettingDescriptionLabel.snp.makeConstraints { make in make.top.equalTo(wifiContainer) make.leading.equalTo(wifiContainer).offset(StandardVerticalMargin) make.trailing.equalTo(wifiSwitch.snp.leading) } videoSettingSubtitleLabel.snp.makeConstraints { make in make.top.equalTo(videoSettingDescriptionLabel.snp.bottom).offset(StandardVerticalMargin) make.leading.equalTo(wifiContainer).offset(StandardVerticalMargin) make.trailing.equalTo(wifiContainer) make.height.equalTo(StandardVerticalMargin * 2) make.bottom.equalTo(wifiContainer) } videoQualityContainer.snp.makeConstraints { make in make.top.equalTo(wifiContainer.snp.bottom).offset(StandardVerticalMargin * 2) make.leading.equalTo(contentView).offset(StandardVerticalMargin) make.trailing.equalTo(contentView).inset(StandardVerticalMargin) make.bottom.equalTo(contentView).inset(StandardVerticalMargin + (StandardVerticalMargin / 2)) } videoQualityDescriptionLabel.snp.makeConstraints { make in make.top.equalTo(videoQualityContainer) make.leading.equalTo(videoQualityContainer).offset(StandardVerticalMargin) make.trailing.equalTo(videoQualityContainer) } chevronImageView.snp.makeConstraints { make in make.height.equalTo(imageSize) make.width.equalTo(imageSize) make.trailing.equalTo(videoQualityContainer).inset(StandardHorizontalMargin / 2) make.centerY.equalTo(videoQualityContainer) } videoQualitySubtitleLabel.snp.makeConstraints { make in make.top.equalTo(videoQualityDescriptionLabel.snp.bottom).offset(StandardVerticalMargin) make.leading.equalTo(videoQualityContainer).offset(StandardVerticalMargin) make.trailing.equalTo(videoQualityContainer) make.height.equalTo(StandardVerticalMargin * 2) make.bottom.equalTo(videoQualityContainer) } videoQualityButton.snp.makeConstraints { make in make.edges.equalTo(videoQualityContainer) } } func updateVideoDownloadQualityLabel() { videoQualitySubtitleLabel.attributedText = titleTextStyle.attributedString(withText: OEXInterface.shared().getVideoDownladQuality().title) } } class PersonalInformationCell: UITableViewCell { static let identifier = "PersonalInformationCell" private var username: String? { didSet { guard let username = username else { return } usernameLabel.attributedText = subtitleTextStyle.attributedString(withText: Strings.ProfileOptions.UserProfile.username(username: username)) } } private var email: String? { didSet { guard let email = email else { return } emailLabel.attributedText = subtitleTextStyle.attributedString(withText: Strings.ProfileOptions.UserProfile.email(email: email)) } } var profileSubtitle: String? { didSet { subtitleLabel.attributedText = titleTextStyle.attributedString(withText: profileSubtitle) } } private lazy var profileView: UIView = { let view = UIView(frame: CGRect(x: 0, y: 0, width: imageSize + 10, height: imageSize + 10)) view.accessibilityIdentifier = "PersonalInformationCell:profile-view" return view }() private lazy var chevronImageView: UIImageView = { let imageView = UIImageView() imageView.image = Icon.ChevronRight.imageWithFontSize(size: imageSize) imageView.tintColor = OEXStyles.shared().primaryBaseColor() imageView.isAccessibilityElement = false imageView.accessibilityIdentifier = "PersonalInformationCell:chevron-image-view" return imageView }() lazy var profileImageView: ProfileImageView = { let view = ProfileImageView(defaultStyle: false) view.accessibilityIdentifier = "PersonalInformationCell:profile-image-view" return view }() private lazy var optionLabel: UILabel = { let label = UILabel() label.attributedText = titleTextStyle.attributedString(withText: Strings.ProfileOptions.UserProfile.title) label.accessibilityIdentifier = "PersonalInformationCell:option-label" return label }() private lazy var emailLabel: UILabel = { let label = UILabel() label.accessibilityIdentifier = "PersonalInformationCell:email-label" return label }() private lazy var usernameLabel: UILabel = { let label = UILabel() label.accessibilityIdentifier = "PersonalInformationCell:username-label" return label }() private lazy var subtitleLabel: UILabel = { let label = UILabel() label.accessibilityIdentifier = "PersonalInformationCell:subtitle-label" return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none accessibilityIdentifier = "ProfileOptionsViewController:wifi-cell" setupViews() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let borderStyle = OEXStyles.shared().profileImageViewBorder(width: 1) profileView.applyBorderStyle(style: borderStyle) profileView.layer.cornerRadius = imageSize / 2 profileView.clipsToBounds = true } private func setupViews() { contentView.addSubview(optionLabel) contentView.addSubview(emailLabel) contentView.addSubview(usernameLabel) contentView.addSubview(subtitleLabel) contentView.addSubview(chevronImageView) contentView.addSubview(profileView) profileView.addSubview(profileImageView) } private func setupConstrains() { optionLabel.snp.remakeConstraints { make in make.top.equalTo(contentView).offset(StandardVerticalMargin + (StandardVerticalMargin / 2)) make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView).inset(StandardHorizontalMargin) } emailLabel.snp.remakeConstraints { make in make.top.equalTo(optionLabel.snp.bottom).offset(StandardVerticalMargin) make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(profileView.snp.leading) } usernameLabel.snp.remakeConstraints { make in make.top.equalTo(emailLabel.snp.bottom).offset(StandardVerticalMargin / 2) make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(emailLabel) if profileSubtitle == nil { make.bottom.equalTo(contentView).inset(StandardVerticalMargin + (StandardVerticalMargin / 2)) } } if profileSubtitle != nil { subtitleLabel.snp.remakeConstraints { make in make.top.equalTo(usernameLabel.snp.bottom).offset(StandardVerticalMargin) make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView).inset(StandardHorizontalMargin) make.bottom.equalTo(contentView).inset(StandardVerticalMargin + (StandardVerticalMargin / 2)) } } chevronImageView.snp.remakeConstraints { make in make.height.equalTo(imageSize) make.width.equalTo(imageSize) make.centerY.equalTo(contentView) make.trailing.equalTo(contentView).inset(StandardHorizontalMargin) } profileView.snp.remakeConstraints { make in make.height.equalTo(imageSize) make.width.equalTo(imageSize) make.centerY.equalTo(contentView) make.trailing.equalTo(chevronImageView.snp.leading).inset(-StandardHorizontalMargin / 2) } profileImageView.snp.remakeConstraints { make in make.edges.equalTo(profileView) } } func update(username: String, email: String) { self.username = username self.email = email setupConstrains() } } class RestorePurchasesCell: UITableViewCell { static let identifier = "RestorePurchasesCell" private lazy var optionLabel: UILabel = { let label = UILabel() label.attributedText = titleTextStyle.attributedString(withText: Strings.ProfileOptions.Purchases.title) label.accessibilityIdentifier = "RestorePurchasesCell:option-label" return label }() private lazy var descriptionLabel: UILabel = { let label = UILabel() label.attributedText = subtitleTextStyle.attributedString(withText: Strings.ProfileOptions.Purchases.heading) label.accessibilityIdentifier = "RestorePurchasesCell:description-label" return label }() private lazy var subtitleLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.attributedText = titleTextStyle.attributedString(withText: Strings.ProfileOptions.Purchases.message) label.accessibilityIdentifier = "RestorePurchasesCell:subtitle-label" return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none accessibilityIdentifier = "ProfileOptionsViewController:restore-purchases-cell" setupViews() setupConstrains() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupViews() { contentView.addSubview(optionLabel) contentView.addSubview(descriptionLabel) contentView.addSubview(subtitleLabel) } private func setupConstrains() { optionLabel.snp.makeConstraints { make in make.top.equalTo(contentView).offset(StandardVerticalMargin + (StandardVerticalMargin / 2)) make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView).inset(StandardHorizontalMargin) } descriptionLabel.snp.makeConstraints { make in make.top.equalTo(optionLabel.snp.bottom).offset(StandardVerticalMargin) make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView).inset(StandardHorizontalMargin) } subtitleLabel.snp.makeConstraints { make in make.top.equalTo(descriptionLabel.snp.bottom).offset(StandardVerticalMargin / 2) make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView).inset(StandardHorizontalMargin) make.height.greaterThanOrEqualTo(StandardVerticalMargin * 2) make.bottom.equalTo(contentView).inset(StandardVerticalMargin + (StandardVerticalMargin / 2)) } } } protocol HelpCellDelegate: AnyObject { func didTapEmail() func didTapFAQ() } class HelpCell: UITableViewCell { static let identifier = "HelpCell" weak var delegate: HelpCellDelegate? private var feedbackEnabled: Bool = false private var faqEnabled: Bool = false private let lineSpacing: CGFloat = 4 private var platformName: String? { didSet { guard let platformName = platformName else { return } feedbackSubtitleLabel.attributedText = titleTextStyle.attributedString(withText: Strings.ProfileOptions.Help.Message.support(platformName: platformName)).setLineSpacing(lineSpacing) } } private lazy var feedbackSupportContainer: UIView = { let view = UIView() view.accessibilityIdentifier = "HelpCell:feedback-support-container" return view }() private lazy var faqContainer: UIView = { let view = UIView() view.accessibilityIdentifier = "HelpCell:faq-container" return view }() private lazy var optionLabel: UILabel = { let label = UILabel() label.attributedText = titleTextStyle.attributedString(withText: Strings.ProfileOptions.Help.title) label.accessibilityIdentifier = "HelpCell:option-label" return label }() private lazy var buttonStyle = OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().primaryBaseColor()) private lazy var feedbackLabel: UILabel = { let label = UILabel() label.attributedText = subtitleTextStyle.attributedString(withText: Strings.ProfileOptions.Help.Heading.feedback) label.accessibilityIdentifier = "HelpCell:feedback-label" return label }() private lazy var feedbackSubtitleLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.accessibilityIdentifier = "HelpCell:feedback-subtitle-label" return label }() private lazy var emailFeedbackButton: UIButton = { let button = UIButton() button.layer.borderWidth = 1 button.layer.borderColor = OEXStyles.shared().neutralXLight().cgColor button.oex_addAction({ [weak self] _ in self?.delegate?.didTapEmail() }, for: .touchUpInside) button.setAttributedTitle(buttonStyle.attributedString(withText: Strings.ProfileOptions.Help.ButtonTitle.feedback), for: .normal) button.accessibilityIdentifier = "HelpCell:email-feedback-button" return button }() private lazy var supportLabel: UILabel = { let label = UILabel() label.attributedText = subtitleTextStyle.attributedString(withText: Strings.ProfileOptions.Help.Heading.support) label.accessibilityIdentifier = "HelpCell:support-label" return label }() private lazy var supportSubtitleLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.attributedText = titleTextStyle.attributedString(withText: Strings.ProfileOptions.Help.Message.feedback).setLineSpacing(lineSpacing) label.accessibilityIdentifier = "HelpCell:support-subtitle-label" return label }() private lazy var faqButton: UIButton = { let button = UIButton() button.layer.borderWidth = 1 button.layer.borderColor = OEXStyles.shared().neutralXLight().cgColor button.oex_addAction({ [weak self] _ in self?.delegate?.didTapFAQ() }, for: .touchUpInside) let faqButtonTitle = [buttonStyle.attributedString(withText: Strings.ProfileOptions.Help.ButtonTitle.viewFaq), faqButtonIcon] let attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: faqButtonTitle) button.setAttributedTitle(attributedText, for: .normal) button.accessibilityIdentifier = "HelpCell:view-faq-button" return button }() private lazy var faqButtonIcon: NSAttributedString = { let icon = Icon.OpenInBrowser.imageWithFontSize(size: 18).image(with: OEXStyles.shared().primaryBaseColor()) let attachment = NSTextAttachment() attachment.image = icon if let image = attachment.image { attachment.bounds = CGRect(x: 0, y: -4.0, width: image.size.width, height: image.size.height) } return NSAttributedString(attachment: attachment) }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none accessibilityIdentifier = "ProfileOptionsViewController:help-cell" } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(feedbackEnabled: Bool, faqEnabled: Bool, platformName: String) { self.feedbackEnabled = feedbackEnabled self.faqEnabled = faqEnabled self.platformName = platformName setupViews() setupConstrains() } private func setupViews() { contentView.addSubview(optionLabel) if feedbackEnabled { feedbackSupportContainer.addSubview(feedbackLabel) feedbackSupportContainer.addSubview(feedbackSubtitleLabel) feedbackSupportContainer.addSubview(emailFeedbackButton) contentView.addSubview(feedbackSupportContainer) } if faqEnabled { faqContainer.addSubview(supportLabel) faqContainer.addSubview(supportSubtitleLabel) faqContainer.addSubview(faqButton) contentView.addSubview(faqContainer) } } private func setupConstrains() { optionLabel.snp.makeConstraints { make in make.top.equalTo(contentView).offset(StandardVerticalMargin + (StandardVerticalMargin / 2)) make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView).inset(StandardHorizontalMargin) } if feedbackEnabled { feedbackSupportContainer.snp.makeConstraints { make in make.top.equalTo(optionLabel.snp.bottom).offset(StandardVerticalMargin) make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView).inset(StandardHorizontalMargin) if faqEnabled { make.bottom.equalTo(emailFeedbackButton.snp.bottom).offset(StandardVerticalMargin) } else { make.bottom.equalTo(contentView).inset(StandardVerticalMargin) } } feedbackLabel.snp.makeConstraints { make in make.top.equalTo(feedbackSupportContainer) make.leading.equalTo(feedbackSupportContainer) make.trailing.equalTo(feedbackSupportContainer) } feedbackSubtitleLabel.snp.makeConstraints { make in make.top.equalTo(feedbackLabel.snp.bottom).offset(StandardVerticalMargin) make.leading.equalTo(feedbackSupportContainer) make.trailing.equalTo(feedbackSupportContainer) make.height.greaterThanOrEqualTo(StandardVerticalMargin * 2) } emailFeedbackButton.snp.makeConstraints { make in make.top.equalTo(feedbackSubtitleLabel.snp.bottom).offset(StandardVerticalMargin) make.leading.equalTo(feedbackSupportContainer) make.trailing.equalTo(feedbackSupportContainer) make.height.equalTo(StandardVerticalMargin * 5) if !faqEnabled { make.bottom.equalTo(feedbackSupportContainer).inset(StandardVerticalMargin) } } } if faqEnabled { faqContainer.snp.makeConstraints { make in if feedbackEnabled { make.top.equalTo(feedbackSupportContainer.snp.bottom).offset(StandardVerticalMargin + (StandardVerticalMargin / 2)) } else { make.top.equalTo(optionLabel.snp.bottom).offset(StandardVerticalMargin + (StandardVerticalMargin / 2)) } make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView).inset(StandardHorizontalMargin) make.bottom.equalTo(contentView).inset(StandardVerticalMargin) } supportLabel.snp.makeConstraints { make in make.top.equalTo(faqContainer).offset(StandardVerticalMargin) make.leading.equalTo(faqContainer) make.trailing.equalTo(faqContainer) } supportSubtitleLabel.snp.makeConstraints { make in make.top.equalTo(supportLabel.snp.bottom).offset(StandardVerticalMargin) make.leading.equalTo(faqContainer) make.trailing.equalTo(faqContainer) make.height.greaterThanOrEqualTo(StandardVerticalMargin * 2) } faqButton.snp.makeConstraints { make in make.top.equalTo(supportSubtitleLabel.snp.bottom).offset(StandardVerticalMargin) make.leading.equalTo(faqContainer) make.trailing.equalTo(faqContainer) make.height.equalTo(StandardVerticalMargin * 5) make.bottom.equalTo(faqContainer).inset(StandardVerticalMargin + (StandardVerticalMargin / 2)) } } } } protocol SignoutCellDelegate: AnyObject { func didSingout() } class SignOutVersionCell: UITableViewCell { static let identifier = "SignOutVersionCell" weak var delegate: SignoutCellDelegate? private lazy var signoutButton: UIButton = { let button = UIButton() button.layer.borderWidth = 1 button.layer.borderColor = OEXStyles.shared().neutralXLight().cgColor button.oex_addAction({ [weak self] _ in self?.delegate?.didSingout() }, for: .touchUpInside) let style = OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().primaryBaseColor()) button.setAttributedTitle(style.attributedString(withText: Strings.ProfileOptions.Signout.buttonTitle), for: .normal) button.accessibilityIdentifier = "SignOutVersionCell:signout-button" return button }() private lazy var versionLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.attributedText = titleTextStyle.attributedString(withText: Strings.versionDisplay(number: Bundle.main.oex_shortVersionString(), environment: "")) label.accessibilityIdentifier = "SignOutVersionCell:version-label" return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none accessibilityIdentifier = "ProfileOptionsViewController:signout-version-cell" setupViews() setupConstrains() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupViews() { contentView.addSubview(signoutButton) contentView.addSubview(versionLabel) } private func setupConstrains() { signoutButton.snp.makeConstraints { make in make.top.equalTo(contentView).offset(StandardVerticalMargin * 2) make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView).inset(StandardHorizontalMargin) make.height.equalTo(StandardVerticalMargin * 5) } versionLabel.snp.makeConstraints { make in make.top.equalTo(signoutButton.snp.bottom).offset(StandardVerticalMargin * 2) make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView).inset(StandardHorizontalMargin) make.bottom.equalTo(contentView).inset(StandardVerticalMargin * 2) } } } protocol DeleteAccountCellDelegate: AnyObject { func didTapDeleteAccount() } class DeleteAccountCell: UITableViewCell { static let identifier = "DeleteAccountCell" weak var delegate: DeleteAccountCellDelegate? private let infoTextStyle = OEXMutableTextStyle(weight: .light, size: .xSmall, color: OEXStyles.shared().neutralXDark()) private lazy var deleteAccountButton: UIButton = { let button = UIButton() button.layer.borderWidth = 1 button.layer.borderColor = OEXStyles.shared().errorBase().cgColor button.oex_addAction({ [weak self] _ in self?.delegate?.didTapDeleteAccount() }, for: .touchUpInside) let style = OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().errorBase()) button.setAttributedTitle(style.attributedString(withText: Strings.ProfileOptions.Deleteaccount.buttonTitle), for: .normal) button.accessibilityIdentifier = "DeleteAccountCell:signout-button" return button }() private lazy var infoLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.attributedText = infoTextStyle.attributedString(withText: Strings.ProfileOptions.Deleteaccount.infoMessage).setLineSpacing(4) label.accessibilityIdentifier = "DeleteAccountCell:info-label" label.textAlignment = .center return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none accessibilityIdentifier = "ProfileOptionsViewController:delete-account-cell" contentView.backgroundColor = OEXStyles.shared().neutralWhite() setupViews() setupConstrains() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupViews() { contentView.addSubview(deleteAccountButton) contentView.addSubview(infoLabel) } private func setupConstrains() { deleteAccountButton.snp.makeConstraints { make in make.top.equalTo(contentView).offset(StandardVerticalMargin * 3) make.leading.equalTo(contentView).offset(StandardHorizontalMargin) make.trailing.equalTo(contentView).inset(StandardHorizontalMargin) make.height.equalTo(StandardVerticalMargin * 5) } infoLabel.snp.makeConstraints { make in make.top.equalTo(deleteAccountButton.snp.bottom).offset(10) make.leading.equalTo(deleteAccountButton) make.trailing.equalTo(deleteAccountButton) make.bottom.equalTo(contentView).inset(StandardVerticalMargin * 2) } } }
apache-2.0
965155fc1df792b63219dfa663726ad0
40.536193
224
0.677037
5.541791
false
false
false
false
alblue/swift
test/SILGen/objc_protocols.swift
2
15689
// RUN: %target-swift-emit-silgen -module-name objc_protocols -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import gizmo import objc_protocols_Bas @objc protocol NSRuncing { func runce() -> NSObject func copyRuncing() -> NSObject func foo() static func mince() -> NSObject } @objc protocol NSFunging { func funge() func foo() } protocol Ansible { func anse() } // CHECK-LABEL: sil hidden @$s14objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[THIS:%.*]] : @guaranteed $T): // -- Result of runce is autoreleased according to default objc conv // CHECK: [[METHOD:%.*]] = objc_method [[THIS]] : {{\$.*}}, #NSRuncing.runce!1.foreign // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<T>([[THIS:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @autoreleased NSObject // -- Result of copyRuncing is received copy_valued according to -copy family // CHECK: [[METHOD:%.*]] = objc_method [[THIS]] : {{\$.*}}, #NSRuncing.copyRuncing!1.foreign // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<T>([[THIS:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @owned NSObject // -- Arguments are not consumed by objc calls // CHECK-NOT: destroy_value [[THIS]] func objc_generic<T : NSRuncing>(_ x: T) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) } // CHECK-LABEL: sil hidden @$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlF : $@convention(thin) <T where T : NSRuncing> (@guaranteed T) -> () { func objc_generic_partial_apply<T : NSRuncing>(_ x: T) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $T): // CHECK: [[FN:%.*]] = function_ref @[[THUNK1:\$s14objc_protocols9NSRuncingP5runceSo8NSObjectCyFTcTO]] : // CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[ARG]]) // CHECK: destroy_value [[METHOD]] _ = x.runce // CHECK: [[FN:%.*]] = function_ref @[[THUNK1]] : // CHECK: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T>() // CHECK: destroy_value [[METHOD]] _ = T.runce // CHECK: [[METATYPE:%.*]] = metatype $@thick T.Type // CHECK: [[FN:%.*]] = function_ref @[[THUNK2:\$s14objc_protocols9NSRuncingP5minceSo8NSObjectCyFZTcTO]] // CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[METATYPE]]) // CHECK: destroy_value [[METHOD:%.*]] _ = T.mince // CHECK-NOT: destroy_value [[ARG]] } // CHECK: } // end sil function '$s14objc_protocols0A22_generic_partial_applyyyxAA9NSRuncingRzlF' // CHECK: sil shared [serializable] [thunk] @[[THUNK1]] : // CHECK: bb0([[SELF:%.*]] : @guaranteed $Self): // CHECK: [[FN:%.*]] = function_ref @[[THUNK1_THUNK:\$s14objc_protocols9NSRuncingP5runceSo8NSObjectCyFTO]] : // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]]<Self>([[SELF_COPY]]) // CHECK: return [[METHOD]] // CHECK: } // end sil function '[[THUNK1]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK1_THUNK]] // CHECK: bb0([[SELF:%.*]] : @guaranteed $Self): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[FN:%.*]] = objc_method [[SELF_COPY]] : $Self, #NSRuncing.runce!1.foreign // CHECK: [[RESULT:%.*]] = apply [[FN]]<Self>([[SELF_COPY]]) // CHECK: destroy_value [[SELF_COPY]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '[[THUNK1_THUNK]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK2]] : // CHECK: [[FN:%.*]] = function_ref @[[THUNK2_THUNK:\$s14objc_protocols9NSRuncingP5minceSo8NSObjectCyFZTO]] // CHECK: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]]<Self>(%0) // CHECK: return [[METHOD]] // CHECK: } // end sil function '[[THUNK2]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK2_THUNK]] : // CHECK: [[METATYPE:%.*]] = thick_to_objc_metatype %0 // CHECK: [[FN:%.*]] = objc_method [[METATYPE]] : $@objc_metatype Self.Type, #NSRuncing.mince!1.foreign // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Self>([[METATYPE]]) // CHECK-NEXT: return [[RESULT]] // CHECK: } // end sil function '[[THUNK2_THUNK]]' // CHECK-LABEL: sil hidden @$s14objc_protocols0A9_protocol{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[THIS:%.*]] : @guaranteed $NSRuncing): // -- Result of runce is autoreleased according to default objc conv // CHECK: [[THIS1:%.*]] = open_existential_ref [[THIS]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]] // CHECK: [[METHOD:%.*]] = objc_method [[THIS1]] : $[[OPENED]], #NSRuncing.runce!1.foreign // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<[[OPENED]]>([[THIS1]]) // -- Result of copyRuncing is received copy_valued according to -copy family // CHECK: [[THIS2:%.*]] = open_existential_ref [[THIS]] : $NSRuncing to $[[OPENED2:@opened(.*) NSRuncing]] // CHECK: [[METHOD:%.*]] = objc_method [[THIS2]] : $[[OPENED2]], #NSRuncing.copyRuncing!1.foreign // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<[[OPENED2]]>([[THIS2:%.*]]) // -- Arguments are not consumed by objc calls // CHECK-NOT: destroy_value [[THIS]] func objc_protocol(_ x: NSRuncing) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) } // CHECK-LABEL: sil hidden @$s14objc_protocols0A23_protocol_partial_applyyyAA9NSRuncing_pF : $@convention(thin) (@guaranteed NSRuncing) -> () { func objc_protocol_partial_apply(_ x: NSRuncing) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $NSRuncing): // CHECK: [[OPENED_ARG:%.*]] = open_existential_ref [[ARG]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]] // CHECK: [[FN:%.*]] = function_ref @$s14objc_protocols9NSRuncingP5runceSo8NSObjectCyFTcTO // CHECK: [[RESULT:%.*]] = apply [[FN]]<[[OPENED]]>([[OPENED_ARG]]) // CHECK: destroy_value [[RESULT]] // CHECK-NOT: destroy_value [[ARG]] _ = x.runce // FIXME: rdar://21289579 // _ = NSRuncing.runce } // CHECK : } // end sil function '$s14objc_protocols0A23_protocol_partial_applyyyAA9NSRuncing_pF' // CHECK-LABEL: sil hidden @$s14objc_protocols0A21_protocol_composition{{[_0-9a-zA-Z]*}}F func objc_protocol_composition(_ x: NSRuncing & NSFunging) { // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]] // CHECK: [[METHOD:%.*]] = objc_method [[THIS]] : $[[OPENED]], #NSRuncing.runce!1.foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.runce() // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]] // CHECK: [[METHOD:%.*]] = objc_method [[THIS]] : $[[OPENED]], #NSFunging.funge!1.foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.funge() } // -- ObjC thunks get emitted for ObjC protocol conformances class Foo : NSRuncing, NSFunging, Ansible { // -- NSRuncing @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc static func mince() -> NSObject { return NSObject() } // -- NSFunging @objc func funge() {} // -- Both NSRuncing and NSFunging @objc func foo() {} // -- Ansible func anse() {} } // CHECK-LABEL: sil hidden [thunk] @$s14objc_protocols3FooC5runce{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @$s14objc_protocols3FooC11copyRuncing{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @$s14objc_protocols3FooC5funge{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @$s14objc_protocols3FooC3foo{{[_0-9a-zA-Z]*}}FTo // CHECK-NOT: sil hidden @_TToF{{.*}}anse{{.*}} class Bar { } extension Bar : NSRuncing { @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil hidden [thunk] @$s14objc_protocols3BarC5runce{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @$s14objc_protocols3BarC11copyRuncing{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @$s14objc_protocols3BarC3foo{{[_0-9a-zA-Z]*}}FTo // class Bas from objc_protocols_Bas module extension Bas : NSRuncing { // runce() implementation from the original definition of Bas @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil hidden [thunk] @$s18objc_protocols_Bas0C0C0a1_B0E11copyRuncing{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @$s18objc_protocols_Bas0C0C0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo // -- Inherited objc protocols protocol Fungible : NSFunging { } class Zim : Fungible { @objc func funge() {} @objc func foo() {} } // CHECK-LABEL: sil hidden [thunk] @$s14objc_protocols3ZimC5funge{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @$s14objc_protocols3ZimC3foo{{[_0-9a-zA-Z]*}}FTo // class Zang from objc_protocols_Bas module extension Zang : Fungible { // funge() implementation from the original definition of Zim @objc func foo() {} } // CHECK-LABEL: sil hidden [thunk] @$s18objc_protocols_Bas4ZangC0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo // -- objc protocols with property requirements in extensions // <rdar://problem/16284574> @objc protocol NSCounting { var count: Int {get} } class StoredPropertyCount { @objc let count = 0 } extension StoredPropertyCount: NSCounting {} // CHECK-LABEL: sil hidden [transparent] [thunk] @$s14objc_protocols19StoredPropertyCountC5countSivgTo class ComputedPropertyCount { @objc var count: Int { return 0 } } extension ComputedPropertyCount: NSCounting {} // CHECK-LABEL: sil hidden [thunk] @$s14objc_protocols21ComputedPropertyCountC5countSivgTo // -- adding @objc protocol conformances to native ObjC classes should not // emit thunks since the methods are already available to ObjC. // Gizmo declared in Inputs/usr/include/Gizmo.h extension Gizmo : NSFunging { } // CHECK-NOT: _TTo{{.*}}5Gizmo{{.*}} @objc class InformallyFunging { @objc func funge() {} @objc func foo() {} } extension InformallyFunging: NSFunging { } @objc protocol Initializable { init(int: Int) } // CHECK-LABEL: sil hidden @$s14objc_protocols28testInitializableExistential_1iAA0D0_pAaD_pXp_SitF : $@convention(thin) (@thick Initializable.Type, Int) -> @owned Initializable { func testInitializableExistential(_ im: Initializable.Type, i: Int) -> Initializable { // CHECK: bb0([[META:%[0-9]+]] : @trivial $@thick Initializable.Type, [[I:%[0-9]+]] : @trivial $Int): // CHECK: [[I2_BOX:%[0-9]+]] = alloc_box ${ var Initializable } // CHECK: [[PB:%.*]] = project_box [[I2_BOX]] // CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[META]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type // CHECK: [[ARCHETYPE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[ARCHETYPE_META]] : $@thick (@opened([[N]]) Initializable).Type to $@objc_metatype (@opened([[N]]) Initializable).Type // CHECK: [[I2_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[ARCHETYPE_META_OBJC]] : $@objc_metatype (@opened([[N]]) Initializable).Type, $@opened([[N]]) Initializable // CHECK: [[INIT_WITNESS:%[0-9]+]] = objc_method [[I2_ALLOC]] : $@opened([[N]]) Initializable, #Initializable.init!initializer.1.foreign : {{.*}} // CHECK: [[I2:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[I]], [[I2_ALLOC]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0 // CHECK: [[I2_EXIST_CONTAINER:%[0-9]+]] = init_existential_ref [[I2]] : $@opened([[N]]) Initializable : $@opened([[N]]) Initializable, $Initializable // CHECK: store [[I2_EXIST_CONTAINER]] to [init] [[PB]] : $*Initializable // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*Initializable // CHECK: [[I2:%[0-9]+]] = load [copy] [[READ]] : $*Initializable // CHECK: destroy_value [[I2_BOX]] : ${ var Initializable } // CHECK: return [[I2]] : $Initializable var i2 = im.init(int: i) return i2 } // CHECK: } // end sil function '$s14objc_protocols28testInitializableExistential_1iAA0D0_pAaD_pXp_SitF' class InitializableConformer: Initializable { @objc required init(int: Int) {} } // CHECK-LABEL: sil hidden [thunk] @$s14objc_protocols22InitializableConformerC{{[_0-9a-zA-Z]*}}fcTo final class InitializableConformerByExtension { init() {} } extension InitializableConformerByExtension: Initializable { @objc convenience init(int: Int) { self.init() } } // CHECK-LABEL: sil hidden [thunk] @$s14objc_protocols33InitializableConformerByExtensionC{{[_0-9a-zA-Z]*}}fcTo // Make sure we're crashing from trying to use materializeForSet here. @objc protocol SelectionItem { var time: Double { get set } } func incrementTime(contents: SelectionItem) { contents.time += 1.0 } @objc public protocol DangerousEscaper { @objc func malicious(_ mayActuallyEscape: () -> ()) } // Make sure we emit an withoutActuallyEscaping sentinel. // CHECK-LABEL: sil @$s14objc_protocols19couldActuallyEscapeyyyyc_AA16DangerousEscaper_ptF : $@convention(thin) (@guaranteed @callee_guaranteed () -> (), @guaranteed DangerousEscaper) -> () { // CHECK: bb0([[CLOSURE_ARG:%.*]] : @guaranteed $@callee_guaranteed () -> (), [[SELF:%.*]] : @guaranteed $DangerousEscaper): // CHECK: [[OE:%.*]] = open_existential_ref [[SELF]] // CHECK: [[CLOSURE_COPY1:%.*]] = copy_value [[CLOSURE_ARG]] // CHECK: [[NOESCAPE:%.*]] = convert_escape_to_noescape [not_guaranteed] [[CLOSURE_COPY1]] // CHECK: [[WITHOUT_ACTUALLY_ESCAPING_THUNK:%.*]] = function_ref @$sIg_Ieg_TR : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> () // CHECK: [[WITHOUT_ACTUALLY_ESCAPING_SENTINEL:%.*]] = partial_apply [callee_guaranteed] [[WITHOUT_ACTUALLY_ESCAPING_THUNK]]([[NOESCAPE]]) // CHECK: [[WITHOUT_ESCAPING:%.*]] = mark_dependence [[WITHOUT_ACTUALLY_ESCAPING_SENTINEL]] : $@callee_guaranteed () -> () on [[NOESCAPE]] // CHECK: [[WITHOUT_ESCAPING_COPY:%.*]] = copy_value [[WITHOUT_ESCAPING]] : $@callee_guaranteed () -> () // CHECK: [[BLOCK:%.*]] = alloc_stack $@block_storage @callee_guaranteed () -> () // CHECK: [[BLOCK_ADDR:%.*]] = project_block_storage [[BLOCK]] : $*@block_storage @callee_guaranteed () -> () // CHECK: store [[WITHOUT_ESCAPING_COPY]] to [init] [[BLOCK_ADDR]] : $*@callee_guaranteed () -> () // CHECK: [[BLOCK_INVOKE:%.*]] = function_ref @$sIeg_IyB_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> () // CHECK: [[BLOCK_CLOSURE:%.*]] = init_block_storage_header [[BLOCK]] : $*@block_storage @callee_guaranteed () -> (), invoke [[BLOCK_INVOKE]] : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> ()) -> (), type $@convention(block) @noescape () -> () // CHECK: [[BLOCK_CLOSURE_COPY:%.*]] = copy_block_without_escaping [[BLOCK_CLOSURE]] : $@convention(block) @noescape () -> () withoutEscaping [[WITHOUT_ESCAPING]] : $@callee_guaranteed () -> () // CHECK: destroy_addr [[BLOCK_ADDR]] : $*@callee_guaranteed () -> () // CHECK: dealloc_stack [[BLOCK]] : $*@block_storage @callee_guaranteed () -> () // CHECK: destroy_value [[CLOSURE_COPY1]] : $@callee_guaranteed () -> () // CHECK: [[METH:%.*]] = objc_method [[OE]] : {{.*}} DangerousEscaper, #DangerousEscaper.malicious!1.foreign // CHECK: apply [[METH]]<@opened("{{.*}}") DangerousEscaper>([[BLOCK_CLOSURE_COPY]], [[OE]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : DangerousEscaper> (@convention(block) @noescape () -> (), τ_0_0) -> () // CHECK: destroy_value [[BLOCK_CLOSURE_COPY]] : $@convention(block) @noescape () -> () // CHECK: return {{.*}} : $() public func couldActuallyEscape(_ closure: @escaping () -> (), _ villian: DangerousEscaper) { villian.malicious(closure) }
apache-2.0
f1e9bcc6ba1fba092d77a20af5511cf4
46.50303
273
0.644106
3.433954
false
false
false
false
alblue/swift
stdlib/public/core/Set.swift
1
55865
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// /// An unordered collection of unique elements. /// /// You use a set instead of an array when you need to test efficiently for /// membership and you aren't concerned with the order of the elements in the /// collection, or when you need to ensure that each element appears only once /// in a collection. /// /// You can create a set with any element type that conforms to the `Hashable` /// protocol. By default, most types in the standard library are hashable, /// including strings, numeric and Boolean types, enumeration cases without /// associated values, and even sets themselves. /// /// Swift makes it as easy to create a new set as to create a new array. Simply /// assign an array literal to a variable or constant with the `Set` type /// specified. /// /// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"] /// if ingredients.contains("sugar") { /// print("No thanks, too sweet.") /// } /// // Prints "No thanks, too sweet." /// /// Set Operations /// ============== /// /// Sets provide a suite of mathematical set operations. For example, you can /// efficiently test a set for membership of an element or check its /// intersection with another set: /// /// - Use the `contains(_:)` method to test whether a set contains a specific /// element. /// - Use the "equal to" operator (`==`) to test whether two sets contain the /// same elements. /// - Use the `isSubset(of:)` method to test whether a set contains all the /// elements of another set or sequence. /// - Use the `isSuperset(of:)` method to test whether all elements of a set /// are contained in another set or sequence. /// - Use the `isStrictSubset(of:)` and `isStrictSuperset(of:)` methods to test /// whether a set is a subset or superset of, but not equal to, another set. /// - Use the `isDisjoint(with:)` method to test whether a set has any elements /// in common with another set. /// /// You can also combine, exclude, or subtract the elements of two sets: /// /// - Use the `union(_:)` method to create a new set with the elements of a set /// and another set or sequence. /// - Use the `intersection(_:)` method to create a new set with only the /// elements common to a set and another set or sequence. /// - Use the `symmetricDifference(_:)` method to create a new set with the /// elements that are in either a set or another set or sequence, but not in /// both. /// - Use the `subtracting(_:)` method to create a new set with the elements of /// a set that are not also in another set or sequence. /// /// You can modify a set in place by using these methods' mutating /// counterparts: `formUnion(_:)`, `formIntersection(_:)`, /// `formSymmetricDifference(_:)`, and `subtract(_:)`. /// /// Set operations are not limited to use with other sets. Instead, you can /// perform set operations with another set, an array, or any other sequence /// type. /// /// var primes: Set = [2, 3, 5, 7] /// /// // Tests whether primes is a subset of a Range<Int> /// print(primes.isSubset(of: 0..<10)) /// // Prints "true" /// /// // Performs an intersection with an Array<Int> /// let favoriteNumbers = [5, 7, 15, 21] /// print(primes.intersection(favoriteNumbers)) /// // Prints "[5, 7]" /// /// Sequence and Collection Operations /// ================================== /// /// In addition to the `Set` type's set operations, you can use any nonmutating /// sequence or collection methods with a set. /// /// if primes.isEmpty { /// print("No primes!") /// } else { /// print("We have \(primes.count) primes.") /// } /// // Prints "We have 4 primes." /// /// let primesSum = primes.reduce(0, +) /// // 'primesSum' == 17 /// /// let primeStrings = primes.sorted().map(String.init) /// // 'primeStrings' == ["2", "3", "5", "7"] /// /// You can iterate through a set's unordered elements with a `for`-`in` loop. /// /// for number in primes { /// print(number) /// } /// // Prints "5" /// // Prints "7" /// // Prints "2" /// // Prints "3" /// /// Many sequence and collection operations return an array or a type-erasing /// collection wrapper instead of a set. To restore efficient set operations, /// create a new set from the result. /// /// let morePrimes = primes.union([11, 13, 17, 19]) /// /// let laterPrimes = morePrimes.filter { $0 > 10 } /// // 'laterPrimes' is of type Array<Int> /// /// let laterPrimesSet = Set(morePrimes.filter { $0 > 10 }) /// // 'laterPrimesSet' is of type Set<Int> /// /// Bridging Between Set and NSSet /// ============================== /// /// You can bridge between `Set` and `NSSet` using the `as` operator. For /// bridging to be possible, the `Element` type of a set must be a class, an /// `@objc` protocol (a protocol imported from Objective-C or marked with the /// `@objc` attribute), or a type that bridges to a Foundation type. /// /// Bridging from `Set` to `NSSet` always takes O(1) time and space. When the /// set's `Element` type is neither a class nor an `@objc` protocol, any /// required bridging of elements occurs at the first access of each element, /// so the first operation that uses the contents of the set (for example, a /// membership test) can take O(*n*). /// /// Bridging from `NSSet` to `Set` first calls the `copy(with:)` method /// (`- copyWithZone:` in Objective-C) on the set to get an immutable copy and /// then performs additional Swift bookkeeping work that takes O(1) time. For /// instances of `NSSet` that are already immutable, `copy(with:)` returns the /// same set in constant time; otherwise, the copying performance is /// unspecified. The instances of `NSSet` and `Set` share buffer using the /// same copy-on-write optimization that is used when two instances of `Set` /// share buffer. @_fixed_layout public struct Set<Element: Hashable> { @usableFromInline internal var _variant: _Variant /// Creates an empty set with preallocated space for at least the specified /// number of elements. /// /// Use this initializer to avoid intermediate reallocations of a set's /// storage buffer when you know how many elements you'll insert into the set /// after creation. /// /// - Parameter minimumCapacity: The minimum number of elements that the /// newly created set should be able to store without reallocating its /// storage buffer. public // FIXME(reserveCapacity): Should be inlinable init(minimumCapacity: Int) { _variant = _Variant(native: _NativeSet(capacity: minimumCapacity)) } /// Private initializer. @inlinable internal init(_native: __owned _NativeSet<Element>) { _variant = _Variant(native: _native) } #if _runtime(_ObjC) @inlinable internal init(_cocoa: __owned _CocoaSet) { _variant = _Variant(cocoa: _cocoa) } /// Private initializer used for bridging. /// /// Only use this initializer when both conditions are true: /// /// * it is statically known that the given `NSSet` is immutable; /// * `Element` is bridged verbatim to Objective-C (i.e., /// is a reference type). @inlinable public // SPI(Foundation) init(_immutableCocoaSet: __owned _NSSet) { _sanityCheck(_isBridgedVerbatimToObjectiveC(Element.self), "Set can be backed by NSSet _variant only when the member type can be bridged verbatim to Objective-C") self.init(_cocoa: _CocoaSet(_immutableCocoaSet)) } #endif } extension Set: ExpressibleByArrayLiteral { /// Creates a set containing the elements of the given array literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you use an array literal. Instead, create a new set using an array /// literal as its value by enclosing a comma-separated list of values in /// square brackets. You can use an array literal anywhere a set is expected /// by the type context. /// /// Here, a set of strings is created from an array literal holding only /// strings. /// /// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"] /// if ingredients.isSuperset(of: ["sugar", "salt"]) { /// print("Whatever it is, it's bound to be delicious!") /// } /// // Prints "Whatever it is, it's bound to be delicious!" /// /// - Parameter elements: A variadic list of elements of the new set. @inlinable public init(arrayLiteral elements: Element...) { if elements.isEmpty { self.init() return } let native = _NativeSet<Element>(capacity: elements.count) for element in elements { let (bucket, found) = native.find(element) if found { // FIXME: Shouldn't this trap? continue } native._unsafeInsertNew(element, at: bucket) } self.init(_native: native) } } extension Set: Sequence { /// Returns an iterator over the members of the set. @inlinable @inline(__always) public __consuming func makeIterator() -> Iterator { return _variant.makeIterator() } /// Returns a Boolean value that indicates whether the given element exists /// in the set. /// /// This example uses the `contains(_:)` method to test whether an integer is /// a member of a set of prime numbers. /// /// let primes: Set = [2, 3, 5, 7] /// let x = 5 /// if primes.contains(x) { /// print("\(x) is prime!") /// } else { /// print("\(x). Not prime.") /// } /// // Prints "5 is prime!" /// /// - Parameter member: An element to look for in the set. /// - Returns: `true` if `member` exists in the set; otherwise, `false`. /// /// - Complexity: O(1) @inlinable public func contains(_ member: Element) -> Bool { return _variant.contains(member) } @inlinable @inline(__always) public func _customContainsEquatableElement(_ member: Element) -> Bool? { return contains(member) } } // This is not quite Sequence.filter, because that returns [Element], not Self // (RangeReplaceableCollection.filter returns Self, but Set isn't an RRC) extension Set { /// Returns a new set containing the elements of the set that satisfy the /// given predicate. /// /// In this example, `filter(_:)` is used to include only names shorter than /// five characters. /// /// let cast: Set = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.count < 5 } /// /// shortNames.isSubset(of: cast) /// // true /// shortNames.contains("Vivien") /// // false /// /// - Parameter isIncluded: A closure that takes an element as its argument /// and returns a Boolean value indicating whether the element should be /// included in the returned set. /// - Returns: A set of the elements that `isIncluded` allows. @inlinable @available(swift, introduced: 4.0) public __consuming func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> Set { // FIXME(performance): Eliminate rehashes by using a bitmap. var result = Set() for element in self { if try isIncluded(element) { result.insert(element) } } return result } } extension Set: Collection { /// The starting position for iterating members of the set. /// /// If the set is empty, `startIndex` is equal to `endIndex`. @inlinable public var startIndex: Index { return _variant.startIndex } /// The "past the end" position for the set---that is, the position one /// greater than the last valid subscript argument. /// /// If the set is empty, `endIndex` is equal to `startIndex`. @inlinable public var endIndex: Index { return _variant.endIndex } /// Accesses the member at the given position. @inlinable public subscript(position: Index) -> Element { //FIXME(accessors): Provide a _read get { return _variant.element(at: position) } } @inlinable public func index(after i: Index) -> Index { return _variant.index(after: i) } @inlinable public func formIndex(after i: inout Index) { _variant.formIndex(after: &i) } // APINAMING: complexity docs are broadly missing in this file. /// Returns the index of the given element in the set, or `nil` if the /// element is not a member of the set. /// /// - Parameter member: An element to search for in the set. /// - Returns: The index of `member` if it exists in the set; otherwise, /// `nil`. /// /// - Complexity: O(1) @inlinable public func firstIndex(of member: Element) -> Index? { return _variant.index(for: member) } @inlinable @inline(__always) public func _customIndexOfEquatableElement( _ member: Element ) -> Index?? { return Optional(firstIndex(of: member)) } @inlinable @inline(__always) public func _customLastIndexOfEquatableElement( _ member: Element ) -> Index?? { // The first and last elements are the same because each element is unique. return _customIndexOfEquatableElement(member) } /// The number of elements in the set. /// /// - Complexity: O(1). @inlinable public var count: Int { return _variant.count } /// A Boolean value that indicates whether the set is empty. @inlinable public var isEmpty: Bool { return count == 0 } } // FIXME: rdar://problem/23549059 (Optimize == for Set) // Look into initially trying to compare the two sets by directly comparing the // contents of both buffers in order. If they happen to have the exact same // ordering we can get the `true` response without ever hashing. If the two // buffers' contents differ at all then we have to fall back to hashing the // rest of the elements (but we don't need to hash any prefix that did match). extension Set: Equatable { /// Returns a Boolean value indicating whether two sets have equal elements. /// /// - Parameters: /// - lhs: A set. /// - rhs: Another set. /// - Returns: `true` if the `lhs` and `rhs` have the same elements; otherwise, /// `false`. @inlinable public static func == (lhs: Set<Element>, rhs: Set<Element>) -> Bool { #if _runtime(_ObjC) switch (lhs._variant.isNative, rhs._variant.isNative) { case (true, true): return lhs._variant.asNative.isEqual(to: rhs._variant.asNative) case (false, false): return lhs._variant.asCocoa.isEqual(to: rhs._variant.asCocoa) case (true, false): return lhs._variant.asNative.isEqual(to: rhs._variant.asCocoa) case (false, true): return rhs._variant.asNative.isEqual(to: lhs._variant.asCocoa) } #else return lhs._variant.asNative.isEqual(to: rhs._variant.asNative) #endif } } extension Set: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { // FIXME(ABI)#177: <rdar://problem/18915294> Cache Set<T> hashValue // Generate a seed from a snapshot of the hasher. This makes members' hash // values depend on the state of the hasher, which improves hashing // quality. (E.g., it makes it possible to resolve collisions by passing in // a different hasher.) var copy = hasher let seed = copy._finalize() var hash = 0 for member in self { hash ^= member._rawHashValue(seed: seed) } hasher.combine(hash) } } extension Set: _HasCustomAnyHashableRepresentation { public __consuming func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(_box: _SetAnyHashableBox(self)) } } internal struct _SetAnyHashableBox<Element: Hashable>: _AnyHashableBox { internal let _value: Set<Element> internal let _canonical: Set<AnyHashable> internal init(_ value: __owned Set<Element>) { self._value = value self._canonical = value as Set<AnyHashable> } internal var _base: Any { return _value } internal var _canonicalBox: _AnyHashableBox { return _SetAnyHashableBox<AnyHashable>(_canonical) } internal func _isEqual(to other: _AnyHashableBox) -> Bool? { guard let other = other as? _SetAnyHashableBox<AnyHashable> else { return nil } return _canonical == other._value } internal var _hashValue: Int { return _canonical.hashValue } internal func _hash(into hasher: inout Hasher) { _canonical.hash(into: &hasher) } internal func _rawHashValue(_seed: Int) -> Int { return _canonical._rawHashValue(seed: _seed) } internal func _unbox<T: Hashable>() -> T? { return _value as? T } internal func _downCastConditional<T>( into result: UnsafeMutablePointer<T> ) -> Bool { guard let value = _value as? T else { return false } result.initialize(to: value) return true } } extension Set: SetAlgebra { /// Inserts the given element in the set if it is not already present. /// /// If an element equal to `newMember` is already contained in the set, this /// method has no effect. In the following example, a new element is /// inserted into `classDays`, a set of days of the week. When an existing /// element is inserted, the `classDays` set does not change. /// /// enum DayOfTheWeek: Int { /// case sunday, monday, tuesday, wednesday, thursday, /// friday, saturday /// } /// /// var classDays: Set<DayOfTheWeek> = [.wednesday, .friday] /// print(classDays.insert(.monday)) /// // Prints "(true, .monday)" /// print(classDays) /// // Prints "[.friday, .wednesday, .monday]" /// /// print(classDays.insert(.friday)) /// // Prints "(false, .friday)" /// print(classDays) /// // Prints "[.friday, .wednesday, .monday]" /// /// - Parameter newMember: An element to insert into the set. /// - Returns: `(true, newMember)` if `newMember` was not contained in the /// set. If an element equal to `newMember` was already contained in the /// set, the method returns `(false, oldMember)`, where `oldMember` is the /// element that was equal to `newMember`. In some cases, `oldMember` may /// be distinguishable from `newMember` by identity comparison or some /// other means. @inlinable @discardableResult public mutating func insert( _ newMember: __owned Element ) -> (inserted: Bool, memberAfterInsert: Element) { return _variant.insert(newMember) } /// Inserts the given element into the set unconditionally. /// /// If an element equal to `newMember` is already contained in the set, /// `newMember` replaces the existing element. In this example, an existing /// element is inserted into `classDays`, a set of days of the week. /// /// enum DayOfTheWeek: Int { /// case sunday, monday, tuesday, wednesday, thursday, /// friday, saturday /// } /// /// var classDays: Set<DayOfTheWeek> = [.monday, .wednesday, .friday] /// print(classDays.update(with: .monday)) /// // Prints "Optional(.monday)" /// /// - Parameter newMember: An element to insert into the set. /// - Returns: An element equal to `newMember` if the set already contained /// such a member; otherwise, `nil`. In some cases, the returned element /// may be distinguishable from `newMember` by identity comparison or some /// other means. @inlinable @discardableResult public mutating func update(with newMember: __owned Element) -> Element? { return _variant.update(with: newMember) } /// Removes the specified element from the set. /// /// This example removes the element `"sugar"` from a set of ingredients. /// /// var ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"] /// let toRemove = "sugar" /// if let removed = ingredients.remove(toRemove) { /// print("The recipe is now \(removed)-free.") /// } /// // Prints "The recipe is now sugar-free." /// /// - Parameter member: The element to remove from the set. /// - Returns: The value of the `member` parameter if it was a member of the /// set; otherwise, `nil`. @inlinable @discardableResult public mutating func remove(_ member: Element) -> Element? { return _variant.remove(member) } /// Removes the element at the given index of the set. /// /// - Parameter position: The index of the member to remove. `position` must /// be a valid index of the set, and must not be equal to the set's end /// index. /// - Returns: The element that was removed from the set. @inlinable @discardableResult public mutating func remove(at position: Index) -> Element { return _variant.remove(at: position) } /// Removes all members from the set. /// /// - Parameter keepingCapacity: If `true`, the set's buffer capacity is /// preserved; if `false`, the underlying buffer is released. The /// default is `false`. @inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { _variant.removeAll(keepingCapacity: keepCapacity) } /// Removes the first element of the set. /// /// Because a set is not an ordered collection, the "first" element may not /// be the first element that was added to the set. The set must not be /// empty. /// /// - Complexity: Amortized O(1) if the set does not wrap a bridged `NSSet`. /// If the set wraps a bridged `NSSet`, the performance is unspecified. /// /// - Returns: A member of the set. @inlinable @discardableResult public mutating func removeFirst() -> Element { _precondition(!isEmpty, "Can't removeFirst from an empty Set") return remove(at: startIndex) } // // APIs below this comment should be implemented strictly in terms of // *public* APIs above. `_variant` should not be accessed directly. // // This separates concerns for testing. Tests for the following APIs need // not to concern themselves with testing correctness of behavior of // underlying buffer (and different variants of it), only correctness of the // API itself. // /// Creates an empty set. /// /// This is equivalent to initializing with an empty array literal. For /// example: /// /// var emptySet = Set<Int>() /// print(emptySet.isEmpty) /// // Prints "true" /// /// emptySet = [] /// print(emptySet.isEmpty) /// // Prints "true" @inlinable public init() { self = Set<Element>(_native: _NativeSet()) } /// Creates a new set from a finite sequence of items. /// /// Use this initializer to create a new set from an existing sequence, for /// example, an array or a range. /// /// let validIndices = Set(0..<7).subtracting([2, 4, 5]) /// print(validIndices) /// // Prints "[6, 0, 1, 3]" /// /// This initializer can also be used to restore set methods after performing /// sequence operations such as `filter(_:)` or `map(_:)` on a set. For /// example, after filtering a set of prime numbers to remove any below 10, /// you can create a new set by using this initializer. /// /// let primes: Set = [2, 3, 5, 7, 11, 13, 17, 19, 23] /// let laterPrimes = Set(primes.lazy.filter { $0 > 10 }) /// print(laterPrimes) /// // Prints "[17, 19, 23, 11, 13]" /// /// - Parameter sequence: The elements to use as members of the new set. @inlinable public init<Source: Sequence>(_ sequence: __owned Source) where Source.Element == Element { self.init(minimumCapacity: sequence.underestimatedCount) if let s = sequence as? Set<Element> { // If this sequence is actually a native `Set`, then we can quickly // adopt its native buffer and let COW handle uniquing only // if necessary. self._variant = s._variant } else { for item in sequence { insert(item) } } } /// Returns a Boolean value that indicates whether the set is a subset of the /// given sequence. /// /// Set *A* is a subset of another set *B* if every member of *A* is also a /// member of *B*. /// /// let employees = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// print(attendees.isSubset(of: employees)) /// // Prints "true" /// /// - Parameter possibleSuperset: A sequence of elements. `possibleSuperset` /// must be finite. /// - Returns: `true` if the set is a subset of `possibleSuperset`; /// otherwise, `false`. @inlinable public func isSubset<S: Sequence>(of possibleSuperset: S) -> Bool where S.Element == Element { // FIXME(performance): isEmpty fast path, here and elsewhere. let other = Set(possibleSuperset) return isSubset(of: other) } /// Returns a Boolean value that indicates whether the set is a strict subset /// of the given sequence. /// /// Set *A* is a strict subset of another set *B* if every member of *A* is /// also a member of *B* and *B* contains at least one element that is not a /// member of *A*. /// /// let employees = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// print(attendees.isStrictSubset(of: employees)) /// // Prints "true" /// /// // A set is never a strict subset of itself: /// print(attendees.isStrictSubset(of: attendees)) /// // Prints "false" /// /// - Parameter possibleStrictSuperset: A sequence of elements. /// `possibleStrictSuperset` must be finite. /// - Returns: `true` is the set is strict subset of /// `possibleStrictSuperset`; otherwise, `false`. @inlinable public func isStrictSubset<S: Sequence>(of possibleStrictSuperset: S) -> Bool where S.Element == Element { // FIXME: code duplication. let other = Set(possibleStrictSuperset) return isStrictSubset(of: other) } /// Returns a Boolean value that indicates whether the set is a superset of /// the given sequence. /// /// Set *A* is a superset of another set *B* if every member of *B* is also a /// member of *A*. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees = ["Alicia", "Bethany", "Diana"] /// print(employees.isSuperset(of: attendees)) /// // Prints "true" /// /// - Parameter possibleSubset: A sequence of elements. `possibleSubset` must /// be finite. /// - Returns: `true` if the set is a superset of `possibleSubset`; /// otherwise, `false`. @inlinable public func isSuperset<S: Sequence>(of possibleSubset: __owned S) -> Bool where S.Element == Element { // FIXME(performance): Don't build a set; just ask if every element is in // `self`. let other = Set(possibleSubset) return other.isSubset(of: self) } /// Returns a Boolean value that indicates whether the set is a strict /// superset of the given sequence. /// /// Set *A* is a strict superset of another set *B* if every member of *B* is /// also a member of *A* and *A* contains at least one element that is *not* /// a member of *B*. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees = ["Alicia", "Bethany", "Diana"] /// print(employees.isStrictSuperset(of: attendees)) /// // Prints "true" /// print(employees.isStrictSuperset(of: employees)) /// // Prints "false" /// /// - Parameter possibleStrictSubset: A sequence of elements. /// `possibleStrictSubset` must be finite. /// - Returns: `true` if the set is a strict superset of /// `possibleStrictSubset`; otherwise, `false`. @inlinable public func isStrictSuperset<S: Sequence>(of possibleStrictSubset: S) -> Bool where S.Element == Element { let other = Set(possibleStrictSubset) return other.isStrictSubset(of: self) } /// Returns a Boolean value that indicates whether the set has no members in /// common with the given sequence. /// /// In the following example, the `employees` set is disjoint with the /// elements of the `visitors` array because no name appears in both. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let visitors = ["Marcia", "Nathaniel", "Olivia"] /// print(employees.isDisjoint(with: visitors)) /// // Prints "true" /// /// - Parameter other: A sequence of elements. `other` must be finite. /// - Returns: `true` if the set has no elements in common with `other`; /// otherwise, `false`. @inlinable public func isDisjoint<S: Sequence>(with other: S) -> Bool where S.Element == Element { // FIXME(performance): Don't need to build a set. let otherSet = Set(other) return isDisjoint(with: otherSet) } /// Returns a new set with the elements of both this set and the given /// sequence. /// /// In the following example, the `attendeesAndVisitors` set is made up /// of the elements of the `attendees` set and the `visitors` array: /// /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// let visitors = ["Marcia", "Nathaniel"] /// let attendeesAndVisitors = attendees.union(visitors) /// print(attendeesAndVisitors) /// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]" /// /// If the set already contains one or more elements that are also in /// `other`, the existing members are kept. If `other` contains multiple /// instances of equivalent elements, only the first instance is kept. /// /// let initialIndices = Set(0..<5) /// let expandedIndices = initialIndices.union([2, 3, 6, 6, 7, 7]) /// print(expandedIndices) /// // Prints "[2, 4, 6, 7, 0, 1, 3]" /// /// - Parameter other: A sequence of elements. `other` must be finite. /// - Returns: A new set with the unique elements of this set and `other`. @inlinable public __consuming func union<S: Sequence>(_ other: __owned S) -> Set<Element> where S.Element == Element { var newSet = self newSet.formUnion(other) return newSet } /// Inserts the elements of the given sequence into the set. /// /// If the set already contains one or more elements that are also in /// `other`, the existing members are kept. If `other` contains multiple /// instances of equivalent elements, only the first instance is kept. /// /// var attendees: Set = ["Alicia", "Bethany", "Diana"] /// let visitors = ["Diana", "Marcia", "Nathaniel"] /// attendees.formUnion(visitors) /// print(attendees) /// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]" /// /// - Parameter other: A sequence of elements. `other` must be finite. @inlinable public mutating func formUnion<S: Sequence>(_ other: __owned S) where S.Element == Element { for item in other { insert(item) } } /// Returns a new set containing the elements of this set that do not occur /// in the given sequence. /// /// In the following example, the `nonNeighbors` set is made up of the /// elements of the `employees` set that are not elements of `neighbors`: /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"] /// let nonNeighbors = employees.subtracting(neighbors) /// print(nonNeighbors) /// // Prints "["Chris", "Diana", "Alicia"]" /// /// - Parameter other: A sequence of elements. `other` must be finite. /// - Returns: A new set. @inlinable public __consuming func subtracting<S: Sequence>(_ other: S) -> Set<Element> where S.Element == Element { return self._subtracting(other) } @inlinable internal __consuming func _subtracting<S: Sequence>( _ other: S ) -> Set<Element> where S.Element == Element { var newSet = self newSet.subtract(other) return newSet } /// Removes the elements of the given sequence from the set. /// /// In the following example, the elements of the `employees` set that are /// also elements of the `neighbors` array are removed. In particular, the /// names `"Bethany"` and `"Eric"` are removed from `employees`. /// /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"] /// employees.subtract(neighbors) /// print(employees) /// // Prints "["Chris", "Diana", "Alicia"]" /// /// - Parameter other: A sequence of elements. `other` must be finite. @inlinable public mutating func subtract<S: Sequence>(_ other: S) where S.Element == Element { _subtract(other) } @inlinable internal mutating func _subtract<S: Sequence>(_ other: S) where S.Element == Element { for item in other { remove(item) } } /// Returns a new set with the elements that are common to both this set and /// the given sequence. /// /// In the following example, the `bothNeighborsAndEmployees` set is made up /// of the elements that are in *both* the `employees` and `neighbors` sets. /// Elements that are in only one or the other are left out of the result of /// the intersection. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"] /// let bothNeighborsAndEmployees = employees.intersection(neighbors) /// print(bothNeighborsAndEmployees) /// // Prints "["Bethany", "Eric"]" /// /// - Parameter other: A sequence of elements. `other` must be finite. /// - Returns: A new set. @inlinable public __consuming func intersection<S: Sequence>(_ other: S) -> Set<Element> where S.Element == Element { let otherSet = Set(other) return intersection(otherSet) } /// Removes the elements of the set that aren't also in the given sequence. /// /// In the following example, the elements of the `employees` set that are /// not also members of the `neighbors` set are removed. In particular, the /// names `"Alicia"`, `"Chris"`, and `"Diana"` are removed. /// /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"] /// employees.formIntersection(neighbors) /// print(employees) /// // Prints "["Bethany", "Eric"]" /// /// - Parameter other: A sequence of elements. `other` must be finite. @inlinable public mutating func formIntersection<S: Sequence>(_ other: S) where S.Element == Element { // Because `intersect` needs to both modify and iterate over // the left-hand side, the index may become invalidated during // traversal so an intermediate set must be created. // // FIXME(performance): perform this operation at a lower level // to avoid invalidating the index and avoiding a copy. let result = self.intersection(other) // The result can only have fewer or the same number of elements. // If no elements were removed, don't perform a reassignment // as this may cause an unnecessary uniquing COW. if result.count != count { self = result } } /// Returns a new set with the elements that are either in this set or in the /// given sequence, but not in both. /// /// In the following example, the `eitherNeighborsOrEmployees` set is made up /// of the elements of the `employees` and `neighbors` sets that are not in /// both `employees` *and* `neighbors`. In particular, the names `"Bethany"` /// and `"Eric"` do not appear in `eitherNeighborsOrEmployees`. /// /// let employees: Set = ["Alicia", "Bethany", "Diana", "Eric"] /// let neighbors = ["Bethany", "Eric", "Forlani"] /// let eitherNeighborsOrEmployees = employees.symmetricDifference(neighbors) /// print(eitherNeighborsOrEmployees) /// // Prints "["Diana", "Forlani", "Alicia"]" /// /// - Parameter other: A sequence of elements. `other` must be finite. /// - Returns: A new set. @inlinable public __consuming func symmetricDifference<S: Sequence>( _ other: __owned S ) -> Set<Element> where S.Element == Element { var newSet = self newSet.formSymmetricDifference(other) return newSet } /// Replace this set with the elements contained in this set or the given /// set, but not both. /// /// In the following example, the elements of the `employees` set that are /// also members of `neighbors` are removed from `employees`, while the /// elements of `neighbors` that are not members of `employees` are added to /// `employees`. In particular, the names `"Bethany"` and `"Eric"` are /// removed from `employees` while the name `"Forlani"` is added. /// /// var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"] /// let neighbors = ["Bethany", "Eric", "Forlani"] /// employees.formSymmetricDifference(neighbors) /// print(employees) /// // Prints "["Diana", "Forlani", "Alicia"]" /// /// - Parameter other: A sequence of elements. `other` must be finite. @inlinable public mutating func formSymmetricDifference<S: Sequence>( _ other: __owned S) where S.Element == Element { let otherSet = Set(other) formSymmetricDifference(otherSet) } } extension Set: CustomStringConvertible, CustomDebugStringConvertible { /// A string that represents the contents of the set. public var description: String { return _makeCollectionDescription() } /// A string that represents the contents of the set, suitable for debugging. public var debugDescription: String { return _makeCollectionDescription(withTypeName: "Set") } } extension Set { /// Removes the elements of the given set from this set. /// /// In the following example, the elements of the `employees` set that are /// also members of the `neighbors` set are removed. In particular, the /// names `"Bethany"` and `"Eric"` are removed from `employees`. /// /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"] /// employees.subtract(neighbors) /// print(employees) /// // Prints "["Diana", "Chris", "Alicia"]" /// /// - Parameter other: Another set. @inlinable public mutating func subtract(_ other: Set<Element>) { _subtract(other) } /// Returns a Boolean value that indicates whether this set is a subset of /// the given set. /// /// Set *A* is a subset of another set *B* if every member of *A* is also a /// member of *B*. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// print(attendees.isSubset(of: employees)) /// // Prints "true" /// /// - Parameter other: Another set. /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. @inlinable public func isSubset(of other: Set<Element>) -> Bool { guard self.count <= other.count else { return false } for member in self { if !other.contains(member) { return false } } return true } /// Returns a Boolean value that indicates whether this set is a superset of /// the given set. /// /// Set *A* is a superset of another set *B* if every member of *B* is also a /// member of *A*. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// print(employees.isSuperset(of: attendees)) /// // Prints "true" /// /// - Parameter other: Another set. /// - Returns: `true` if the set is a superset of `other`; otherwise, /// `false`. @inlinable public func isSuperset(of other: Set<Element>) -> Bool { return other.isSubset(of: self) } /// Returns a Boolean value that indicates whether this set has no members in /// common with the given set. /// /// In the following example, the `employees` set is disjoint with the /// `visitors` set because no name appears in both sets. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"] /// print(employees.isDisjoint(with: visitors)) /// // Prints "true" /// /// - Parameter other: Another set. /// - Returns: `true` if the set has no elements in common with `other`; /// otherwise, `false`. @inlinable public func isDisjoint(with other: Set<Element>) -> Bool { for member in self { if other.contains(member) { return false } } return true } /// Returns a new set containing the elements of this set that do not occur /// in the given set. /// /// In the following example, the `nonNeighbors` set is made up of the /// elements of the `employees` set that are not elements of `neighbors`: /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"] /// let nonNeighbors = employees.subtracting(neighbors) /// print(nonNeighbors) /// // Prints "["Diana", "Chris", "Alicia"]" /// /// - Parameter other: Another set. /// - Returns: A new set. @inlinable public __consuming func subtracting(_ other: Set<Element>) -> Set<Element> { return self._subtracting(other) } /// Returns a Boolean value that indicates whether the set is a strict /// superset of the given sequence. /// /// Set *A* is a strict superset of another set *B* if every member of *B* is /// also a member of *A* and *A* contains at least one element that is *not* /// a member of *B*. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// print(employees.isStrictSuperset(of: attendees)) /// // Prints "true" /// print(employees.isStrictSuperset(of: employees)) /// // Prints "false" /// /// - Parameter other: Another set. /// - Returns: `true` if the set is a strict superset of /// `other`; otherwise, `false`. @inlinable public func isStrictSuperset(of other: Set<Element>) -> Bool { return self.isSuperset(of: other) && self != other } /// Returns a Boolean value that indicates whether the set is a strict subset /// of the given sequence. /// /// Set *A* is a strict subset of another set *B* if every member of *A* is /// also a member of *B* and *B* contains at least one element that is not a /// member of *A*. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let attendees: Set = ["Alicia", "Bethany", "Diana"] /// print(attendees.isStrictSubset(of: employees)) /// // Prints "true" /// /// // A set is never a strict subset of itself: /// print(attendees.isStrictSubset(of: attendees)) /// // Prints "false" /// /// - Parameter other: Another set. /// - Returns: `true` if the set is a strict subset of /// `other`; otherwise, `false`. @inlinable public func isStrictSubset(of other: Set<Element>) -> Bool { return other.isStrictSuperset(of: self) } /// Returns a new set with the elements that are common to both this set and /// the given sequence. /// /// In the following example, the `bothNeighborsAndEmployees` set is made up /// of the elements that are in *both* the `employees` and `neighbors` sets. /// Elements that are in only one or the other are left out of the result of /// the intersection. /// /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"] /// let bothNeighborsAndEmployees = employees.intersection(neighbors) /// print(bothNeighborsAndEmployees) /// // Prints "["Bethany", "Eric"]" /// /// - Parameter other: Another set. /// - Returns: A new set. @inlinable public __consuming func intersection(_ other: Set<Element>) -> Set<Element> { var newSet = Set<Element>() for member in self { if other.contains(member) { newSet.insert(member) } } return newSet } /// Removes the elements of the set that are also in the given sequence and /// adds the members of the sequence that are not already in the set. /// /// In the following example, the elements of the `employees` set that are /// also members of `neighbors` are removed from `employees`, while the /// elements of `neighbors` that are not members of `employees` are added to /// `employees`. In particular, the names `"Alicia"`, `"Chris"`, and /// `"Diana"` are removed from `employees` while the names `"Forlani"` and /// `"Greta"` are added. /// /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"] /// employees.formSymmetricDifference(neighbors) /// print(employees) /// // Prints "["Diana", "Chris", "Forlani", "Alicia", "Greta"]" /// /// - Parameter other: Another set. @inlinable public mutating func formSymmetricDifference(_ other: __owned Set<Element>) { for member in other { if contains(member) { remove(member) } else { insert(member) } } } } extension Set { /// The position of an element in a set. @_fixed_layout public struct Index { // Index for native buffer is efficient. Index for bridged NSSet is // not, because neither NSEnumerator nor fast enumeration support moving // backwards. Even if they did, there is another issue: NSEnumerator does // not support NSCopying, and fast enumeration does not document that it is // safe to copy the state. So, we cannot implement Index that is a value // type for bridged NSSet in terms of Cocoa enumeration facilities. @_frozen @usableFromInline internal enum _Variant { case native(_HashTable.Index) #if _runtime(_ObjC) case cocoa(_CocoaSet.Index) #endif } @usableFromInline internal var _variant: _Variant @inlinable @inline(__always) internal init(_variant: __owned _Variant) { self._variant = _variant } @inlinable @inline(__always) internal init(_native index: _HashTable.Index) { self.init(_variant: .native(index)) } #if _runtime(_ObjC) @inlinable @inline(__always) internal init(_cocoa index: __owned _CocoaSet.Index) { self.init(_variant: .cocoa(index)) } #endif } } extension Set.Index { #if _runtime(_ObjC) @usableFromInline @_transparent internal var _guaranteedNative: Bool { return _canBeClass(Element.self) == 0 } /// Allow the optimizer to consider the surrounding code unreachable if /// Set<Element> is guaranteed to be native. @usableFromInline @_transparent internal func _cocoaPath() { if _guaranteedNative { _conditionallyUnreachable() } } @inlinable @inline(__always) internal mutating func _isUniquelyReferenced() -> Bool { defer { _fixLifetime(self) } var handle = _asCocoa.handleBitPattern return handle == 0 || _isUnique_native(&handle) } #endif #if _runtime(_ObjC) @usableFromInline @_transparent internal var _isNative: Bool { switch _variant { case .native: return true case .cocoa: _cocoaPath() return false } } #endif @usableFromInline @_transparent internal var _asNative: _HashTable.Index { switch _variant { case .native(let nativeIndex): return nativeIndex #if _runtime(_ObjC) case .cocoa: _preconditionFailure( "Attempting to access Set elements using an invalid index") #endif } } #if _runtime(_ObjC) @usableFromInline internal var _asCocoa: _CocoaSet.Index { @_transparent get { switch _variant { case .native: _preconditionFailure( "Attempting to access Set elements using an invalid index") case .cocoa(let cocoaIndex): return cocoaIndex } } _modify { guard case .cocoa(var cocoa) = _variant else { _preconditionFailure( "Attempting to access Set elements using an invalid index") } let dummy = _HashTable.Index(bucket: _HashTable.Bucket(offset: 0), age: 0) _variant = .native(dummy) yield &cocoa _variant = .cocoa(cocoa) } } #endif } extension Set.Index: Equatable { @inlinable public static func == ( lhs: Set<Element>.Index, rhs: Set<Element>.Index ) -> Bool { switch (lhs._variant, rhs._variant) { case (.native(let lhsNative), .native(let rhsNative)): return lhsNative == rhsNative #if _runtime(_ObjC) case (.cocoa(let lhsCocoa), .cocoa(let rhsCocoa)): lhs._cocoaPath() return lhsCocoa == rhsCocoa default: _preconditionFailure("Comparing indexes from different sets") #endif } } } extension Set.Index: Comparable { @inlinable public static func < ( lhs: Set<Element>.Index, rhs: Set<Element>.Index ) -> Bool { switch (lhs._variant, rhs._variant) { case (.native(let lhsNative), .native(let rhsNative)): return lhsNative < rhsNative #if _runtime(_ObjC) case (.cocoa(let lhsCocoa), .cocoa(let rhsCocoa)): lhs._cocoaPath() return lhsCocoa < rhsCocoa default: _preconditionFailure("Comparing indexes from different sets") #endif } } } extension Set.Index: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. public // FIXME(cocoa-index): Make inlinable func hash(into hasher: inout Hasher) { #if _runtime(_ObjC) guard _isNative else { hasher.combine(1 as UInt8) hasher.combine(_asCocoa._offset) return } hasher.combine(0 as UInt8) hasher.combine(_asNative.bucket.offset) #else hasher.combine(_asNative.bucket.offset) #endif } } extension Set { /// An iterator over the members of a `Set<Element>`. @_fixed_layout public struct Iterator { // Set has a separate IteratorProtocol and Index because of efficiency // and implementability reasons. // // Native sets have efficient indices. Bridged NSSet instances don't. // // Even though fast enumeration is not suitable for implementing // Index, which is multi-pass, it is suitable for implementing a // IteratorProtocol, which is being consumed as iteration proceeds. @usableFromInline @_frozen internal enum _Variant { case native(_NativeSet<Element>.Iterator) #if _runtime(_ObjC) case cocoa(_CocoaSet.Iterator) #endif } @usableFromInline internal var _variant: _Variant @inlinable internal init(_variant: __owned _Variant) { self._variant = _variant } @inlinable internal init(_native: __owned _NativeSet<Element>.Iterator) { self.init(_variant: .native(_native)) } #if _runtime(_ObjC) @usableFromInline internal init(_cocoa: __owned _CocoaSet.Iterator) { self.init(_variant: .cocoa(_cocoa)) } #endif } } extension Set.Iterator { #if _runtime(_ObjC) @usableFromInline @_transparent internal var _guaranteedNative: Bool { return _canBeClass(Element.self) == 0 } /// Allow the optimizer to consider the surrounding code unreachable if /// Set<Element> is guaranteed to be native. @usableFromInline @_transparent internal func _cocoaPath() { if _guaranteedNative { _conditionallyUnreachable() } } #endif #if _runtime(_ObjC) @usableFromInline @_transparent internal var _isNative: Bool { switch _variant { case .native: return true case .cocoa: _cocoaPath() return false } } #endif @usableFromInline @_transparent internal var _asNative: _NativeSet<Element>.Iterator { get { switch _variant { case .native(let nativeIterator): return nativeIterator #if _runtime(_ObjC) case .cocoa: _sanityCheckFailure("internal error: does not contain a native index") #endif } } set { self._variant = .native(newValue) } } #if _runtime(_ObjC) @usableFromInline @_transparent internal var _asCocoa: _CocoaSet.Iterator { get { switch _variant { case .native: _sanityCheckFailure("internal error: does not contain a Cocoa index") case .cocoa(let cocoa): return cocoa } } } #endif } extension Set.Iterator: IteratorProtocol { /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. @inlinable @inline(__always) public mutating func next() -> Element? { #if _runtime(_ObjC) guard _isNative else { guard let cocoaElement = _asCocoa.next() else { return nil } return _forceBridgeFromObjectiveC(cocoaElement, Element.self) } #endif return _asNative.next() } } extension Set.Iterator: CustomReflectable { /// A mirror that reflects the iterator. public var customMirror: Mirror { return Mirror( self, children: EmptyCollection<(label: String?, value: Any)>()) } } extension Set: CustomReflectable { /// A mirror that reflects the set. public var customMirror: Mirror { let style = Mirror.DisplayStyle.`set` return Mirror(self, unlabeledChildren: self, displayStyle: style) } } extension Set { /// Removes and returns the first element of the set. /// /// Because a set is not an ordered collection, the "first" element may not /// be the first element that was added to the set. /// /// - Returns: A member of the set. If the set is empty, returns `nil`. @inlinable public mutating func popFirst() -> Element? { guard !isEmpty else { return nil } return remove(at: startIndex) } /// The total number of elements that the set can contain without /// allocating new storage. @inlinable public var capacity: Int { return _variant.capacity } /// Reserves enough space to store the specified number of elements. /// /// If you are adding a known number of elements to a set, use this /// method to avoid multiple reallocations. This method ensures that the /// set has unique, mutable, contiguous storage, with space allocated /// for at least the requested number of elements. /// /// Calling the `reserveCapacity(_:)` method on a set with bridged /// storage triggers a copy to contiguous storage even if the existing /// storage has room to store `minimumCapacity` elements. /// /// - Parameter minimumCapacity: The requested number of elements to /// store. public // FIXME(reserveCapacity): Should be inlinable mutating func reserveCapacity(_ minimumCapacity: Int) { _variant.reserveCapacity(minimumCapacity) _sanityCheck(self.capacity >= minimumCapacity) } } public typealias SetIndex<Element: Hashable> = Set<Element>.Index public typealias SetIterator<Element: Hashable> = Set<Element>.Iterator
apache-2.0
f7e49e6675664377ba01e1ba0665742d
33.463294
109
0.640759
4.105909
false
false
false
false
brightdigit/marseft
Marseft/Configuration.swift
1
1731
// // Configuration.swift // TicTalkToc // // Created by Leo G Dion on 1/22/15. // Copyright (c) 2015 BrightDigit. All rights reserved. // import Foundation public typealias Decipher = (string: String) throws -> [String : AnyObject]? public protocol ConfigurationElementLookup { subscript(key: String) -> ConfigurationElementable? { get } } public protocol ConfigurationElementable : ConfigurationElementLookup { var value:AnyObject { get } var string: String? { get } var int: Int? { get } var timeInterval: NSTimeInterval? { get } func bool (defaultValue: Bool) -> Bool } public struct Configuration : ConfigurationElementLookup { let data:[String:AnyObject]? let keys: [String]? public init (configuration: String, keys: [String]? = nil, decipher: Decipher? = nil) throws { let actualDecipher:Decipher if decipher != nil { actualDecipher = decipher! } else { actualDecipher = Configuration.decipher } self.data = try actualDecipher(string: configuration) self.keys = keys } public subscript(key: String) -> ConfigurationElementable? { if let item: AnyObject = self.data?[key] { return ConfigurationElement(element: item, keys: keys) } else { return nil } } static func decipher (string: String) throws -> [String : AnyObject]? { if let data = NSData(base64EncodedString: string, options: NSDataBase64DecodingOptions()) { if let uncompressed = data.gunzippedData() { if let jsonData = try NSJSONSerialization.JSONObjectWithData(uncompressed, options: NSJSONReadingOptions()) as? [String : AnyObject] { return jsonData } } else { throw Error.Decompression } } else { throw Error.StringNSData } return nil } }
mit
f72fc513ff20cfe9c362d8396160039f
26.492063
138
0.700173
3.821192
false
true
false
false
wireapp/wire-ios-sync-engine
Source/UserSession/CallStateObserver.swift
1
8466
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireDataModel import CoreData @objc(ZMCallStateObserver) public final class CallStateObserver: NSObject { @objc static public let CallInProgressNotification = Notification.Name(rawValue: "ZMCallInProgressNotification") @objc static public let CallInProgressKey = "callInProgress" fileprivate weak var notificationStyleProvider: CallNotificationStyleProvider? fileprivate let localNotificationDispatcher: LocalNotificationDispatcher fileprivate let uiContext: NSManagedObjectContext fileprivate let syncContext: NSManagedObjectContext fileprivate var callStateToken: Any? fileprivate var missedCalltoken: Any? fileprivate let systemMessageGenerator = CallSystemMessageGenerator() @objc public init(localNotificationDispatcher: LocalNotificationDispatcher, contextProvider: ContextProvider, callNotificationStyleProvider: CallNotificationStyleProvider) { self.uiContext = contextProvider.viewContext self.syncContext = contextProvider.syncContext self.notificationStyleProvider = callNotificationStyleProvider self.localNotificationDispatcher = localNotificationDispatcher super.init() self.callStateToken = WireCallCenterV3.addCallStateObserver(observer: self, context: uiContext) self.missedCalltoken = WireCallCenterV3.addMissedCallObserver(observer: self, context: uiContext) } fileprivate var callInProgress: Bool = false { didSet { if callInProgress != oldValue { syncContext.performGroupedBlock { NotificationInContext(name: CallStateObserver.CallInProgressNotification, context: self.syncContext.notificationContext, userInfo: [ CallStateObserver.CallInProgressKey: self.callInProgress ]).post() } } } } } extension CallStateObserver: WireCallCenterCallStateObserver, WireCallCenterMissedCallObserver { public func callCenterDidChange(callState: CallState, conversation: ZMConversation, caller: UserType, timestamp: Date?, previousCallState: CallState?) { let callerId = (caller as? ZMUser)?.remoteIdentifier let conversationId = conversation.remoteIdentifier syncContext.performGroupedBlock { guard let callerId = callerId, let conversationId = conversationId, let conversation = ZMConversation.fetch(with: conversationId, in: self.syncContext), let caller = ZMUser.fetch(with: callerId, in: self.syncContext) else { return } self.uiContext.performGroupedBlock { if let activeCallCount = self.uiContext.zm_callCenter?.activeCalls.count { self.callInProgress = activeCallCount > 0 } } // This will unarchive the conversation when there is an incoming call self.updateConversation(conversation, with: callState, timestamp: timestamp) // CallKit depends on a fetched conversation & and is not used for muted conversations let skipCallKit = conversation.needsToBeUpdatedFromBackend || conversation.mutedMessageTypesIncludingAvailability != .none let notificationStyle = self.notificationStyleProvider?.callNotificationStyle ?? .callKit if notificationStyle == .pushNotifications || skipCallKit { self.localNotificationDispatcher.process(callState: callState, in: conversation, caller: caller) } self.updateConversationListIndicator(convObjectID: conversation.objectID, callState: callState) if let systemMessage = self.systemMessageGenerator.appendSystemMessageIfNeeded(callState: callState, conversation: conversation, caller: caller, timestamp: timestamp, previousCallState: previousCallState) { switch (systemMessage.systemMessageType, callState, conversation.conversationType) { case (.missedCall, .terminating(reason: .normal), .group), (.missedCall, .terminating(reason: .canceled), _ ): // group calls we didn't join, end with reason .normal. We should still insert a missed call in this case. // since the systemMessageGenerator keeps track whether we joined or not, we can use it to decide whether we should show a missed call APNS self.localNotificationDispatcher.processMissedCall(in: conversation, caller: caller) default: break } self.syncContext.enqueueDelayedSave() } } } public func updateConversationListIndicator(convObjectID: NSManagedObjectID, callState: CallState) { // We need to switch to the uiContext here because we are making changes that need to be present on the UI when the change notification fires uiContext.performGroupedBlock { guard let uiConv = (try? self.uiContext.existingObject(with: convObjectID)) as? ZMConversation else { return } switch callState { case .incoming(video: _, shouldRing: let shouldRing, degraded: _): uiConv.isIgnoringCall = uiConv.mutedMessageTypesIncludingAvailability != .none || !shouldRing uiConv.isCallDeviceActive = false case .terminating, .none, .mediaStopped: uiConv.isCallDeviceActive = false uiConv.isIgnoringCall = false case .outgoing, .answered, .established: uiConv.isCallDeviceActive = true case .unknown, .establishedDataChannel: break } if self.uiContext.zm_hasChanges { NotificationDispatcher.notifyNonCoreDataChanges(objectID: convObjectID, changedKeys: [ZMConversationListIndicatorKey], uiContext: self.uiContext) } } } public func callCenterMissedCall(conversation: ZMConversation, caller: UserType, timestamp: Date, video: Bool) { let callerId = (caller as? ZMUser)?.remoteIdentifier let conversationId = conversation.remoteIdentifier syncContext.performGroupedBlock { guard let callerId = callerId, let conversationId = conversationId, let conversation = ZMConversation.fetch(with: conversationId, in: self.syncContext), let caller = ZMUser.fetch(with: callerId, in: self.syncContext) else { return } if (self.notificationStyleProvider?.callNotificationStyle ?? .callKit) == .pushNotifications { self.localNotificationDispatcher.processMissedCall(in: conversation, caller: caller) } conversation.appendMissedCallMessage(fromUser: caller, at: timestamp) self.syncContext.enqueueDelayedSave() } } private func updateConversation(_ conversation: ZMConversation, with callState: CallState, timestamp: Date?) { switch callState { case .incoming(_, shouldRing: true, degraded: _): if conversation.isArchived && conversation.mutedMessageTypes != .all { conversation.isArchived = false } if let timestamp = timestamp { conversation.updateLastModified(timestamp) } syncContext.enqueueDelayedSave() default: break } } }
gpl-3.0
c969a7517da28327661d2b3e97627a94
45.516484
218
0.659225
5.72027
false
false
false
false
mauryat/firefox-ios
Client/Frontend/Widgets/ActivityStreamHighlightCell.swift
1
9166
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage struct ActivityStreamHighlightCellUX { static let LabelColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.black : UIColor(rgb: 0x353535) static let BorderWidth: CGFloat = 0.5 static let CellSideOffset = 20 static let TitleLabelOffset = 2 static let CellTopBottomOffset = 12 static let SiteImageViewSize: CGSize = UIDevice.current.userInterfaceIdiom == .pad ? CGSize(width: 99, height: 120) : CGSize(width: 99, height: 90) static let StatusIconSize = 12 static let FaviconSize = CGSize(width: 45, height: 45) static let DescriptionLabelColor = UIColor(colorString: "919191") static let SelectedOverlayColor = UIColor(white: 0.0, alpha: 0.25) static let CornerRadius: CGFloat = 3 static let BorderColor = UIColor(white: 0, alpha: 0.1) } class ActivityStreamHighlightCell: UICollectionViewCell { fileprivate lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.font = DynamicFontHelper.defaultHelper.MediumSizeHeavyWeightAS titleLabel.textColor = ActivityStreamHighlightCellUX.LabelColor titleLabel.textAlignment = .left titleLabel.numberOfLines = 3 return titleLabel }() fileprivate lazy var descriptionLabel: UILabel = { let descriptionLabel = UILabel() descriptionLabel.font = DynamicFontHelper.defaultHelper.SmallSizeRegularWeightAS descriptionLabel.textColor = ActivityStreamHighlightCellUX.DescriptionLabelColor descriptionLabel.textAlignment = .left descriptionLabel.numberOfLines = 1 return descriptionLabel }() fileprivate lazy var domainLabel: UILabel = { let descriptionLabel = UILabel() descriptionLabel.font = DynamicFontHelper.defaultHelper.SmallSizeRegularWeightAS descriptionLabel.textColor = ActivityStreamHighlightCellUX.DescriptionLabelColor descriptionLabel.textAlignment = .left descriptionLabel.numberOfLines = 1 descriptionLabel.setContentCompressionResistancePriority(1000, for: UILayoutConstraintAxis.vertical) return descriptionLabel }() lazy var siteImageView: UIImageView = { let siteImageView = UIImageView() siteImageView.contentMode = UIViewContentMode.scaleAspectFit siteImageView.clipsToBounds = true siteImageView.contentMode = UIViewContentMode.center siteImageView.layer.cornerRadius = ActivityStreamHighlightCellUX.CornerRadius siteImageView.layer.borderColor = ActivityStreamHighlightCellUX.BorderColor.cgColor siteImageView.layer.borderWidth = ActivityStreamHighlightCellUX.BorderWidth siteImageView.layer.masksToBounds = true return siteImageView }() fileprivate lazy var statusIcon: UIImageView = { let statusIcon = UIImageView() statusIcon.contentMode = UIViewContentMode.scaleAspectFit statusIcon.clipsToBounds = true statusIcon.layer.cornerRadius = ActivityStreamHighlightCellUX.CornerRadius return statusIcon }() fileprivate lazy var selectedOverlay: UIView = { let selectedOverlay = UIView() selectedOverlay.backgroundColor = ActivityStreamHighlightCellUX.SelectedOverlayColor selectedOverlay.isHidden = true return selectedOverlay }() override var isSelected: Bool { didSet { self.selectedOverlay.isHidden = !isSelected } } override init(frame: CGRect) { super.init(frame: frame) layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale isAccessibilityElement = true contentView.addSubview(siteImageView) contentView.addSubview(descriptionLabel) contentView.addSubview(selectedOverlay) contentView.addSubview(titleLabel) contentView.addSubview(statusIcon) contentView.addSubview(domainLabel) siteImageView.snp.makeConstraints { make in make.top.equalTo(contentView) make.leading.trailing.equalTo(contentView) make.centerX.equalTo(contentView) make.height.equalTo(ActivityStreamHighlightCellUX.SiteImageViewSize) } selectedOverlay.snp.makeConstraints { make in make.edges.equalTo(contentView) } domainLabel.snp.makeConstraints { make in make.leading.equalTo(siteImageView) make.trailing.equalTo(contentView) make.top.equalTo(siteImageView.snp.bottom).offset(5) } titleLabel.snp.makeConstraints { make in make.leading.equalTo(siteImageView) make.trailing.equalTo(contentView) make.top.equalTo(domainLabel.snp.bottom).offset(5) } descriptionLabel.snp.makeConstraints { make in make.leading.equalTo(statusIcon.snp.trailing).offset(ActivityStreamHighlightCellUX.TitleLabelOffset) make.bottom.equalTo(contentView) } statusIcon.snp.makeConstraints { make in make.size.equalTo(ActivityStreamHighlightCellUX.StatusIconSize) make.centerY.equalTo(descriptionLabel.snp.centerY) make.leading.equalTo(siteImageView) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() self.siteImageView.image = nil contentView.backgroundColor = UIColor.clear siteImageView.backgroundColor = UIColor.clear } func configureWithSite(_ site: Site) { if let mediaURLStr = site.metadata?.mediaURL, let mediaURL = URL(string: mediaURLStr) { self.siteImageView.sd_setImage(with: mediaURL) self.siteImageView.contentMode = .scaleAspectFill } else { let itemURL = site.tileURL self.siteImageView.setFavicon(forSite: site, onCompletion: { [weak self] (color, url) in if itemURL == url { self?.siteImageView.image = self?.siteImageView.image?.createScaled(ActivityStreamHighlightCellUX.FaviconSize) self?.siteImageView.backgroundColor = color } }) self.siteImageView.contentMode = .center } self.domainLabel.text = site.tileURL.hostSLD self.titleLabel.text = site.title.characters.count <= 1 ? site.url : site.title if let bookmarked = site.bookmarked, bookmarked { self.descriptionLabel.text = Strings.HighlightBookmarkText self.statusIcon.image = UIImage(named: "context_bookmark") } else { self.descriptionLabel.text = Strings.HighlightVistedText self.statusIcon.image = UIImage(named: "context_viewed") } } func configureWithPocketStory(_ pocketStory: PocketStory) { self.siteImageView.sd_setImage(with: pocketStory.imageURL) self.siteImageView.contentMode = .scaleAspectFill self.domainLabel.text = pocketStory.domain self.titleLabel.text = pocketStory.title self.descriptionLabel.text = Strings.PocketTrendingText self.statusIcon.image = UIImage(named: "context_pocket") } } struct HighlightIntroCellUX { static let margin: CGFloat = 20 static let foxImageWidth: CGFloat = 168 } class HighlightIntroCell: UICollectionViewCell { lazy var titleLabel: UILabel = { let textLabel = UILabel() textLabel.font = DynamicFontHelper.defaultHelper.MediumSizeBoldFontAS textLabel.textColor = UIColor.black textLabel.numberOfLines = 1 textLabel.adjustsFontSizeToFitWidth = true textLabel.minimumScaleFactor = 0.8 return textLabel }() lazy var descriptionLabel: UILabel = { let label = UILabel() label.font = DynamicFontHelper.defaultHelper.MediumSizeRegularWeightAS label.textColor = UIColor.darkGray label.numberOfLines = 0 return label }() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(titleLabel) contentView.addSubview(descriptionLabel) titleLabel.text = Strings.HighlightIntroTitle descriptionLabel.text = Strings.HighlightIntroDescription let titleInsets = UIEdgeInsets(top: HighlightIntroCellUX.margin, left: 0, bottom: 0, right: 0) titleLabel.snp.makeConstraints { make in make.leading.top.trailing.equalTo(self.contentView).inset(titleInsets) } descriptionLabel.snp.makeConstraints { make in make.leading.trailing.equalTo(titleLabel) make.top.equalTo(titleLabel.snp.bottom).offset(HighlightIntroCellUX.margin/2) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
ff38e37df8c7448715eb8f332e39c597
37.675105
151
0.68885
5.158132
false
false
false
false
adrfer/swift
test/Interpreter/struct_resilience.swift
1
4833
// RUN: rm -rf %t && mkdir %t // RUN: %target-build-swift -emit-library -Xfrontend -enable-resilience -c %S/../Inputs/resilient_struct.swift -o %t/resilient_struct.o // RUN: %target-build-swift -emit-module -Xfrontend -enable-resilience -c %S/../Inputs/resilient_struct.swift -o %t/resilient_struct.o // RUN: %target-build-swift %s -Xlinker %t/resilient_struct.o -I %t -L %t -o %t/main // RUN: %target-run %t/main import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif import resilient_struct var ResilientStructTestSuite = TestSuite("ResilientStruct") ResilientStructTestSuite.test("ResilientValue") { for b in [false, true] { let r = ResilientBool(b: b) expectEqual(b, r.b) } for i in [-12, -1, 12] { let r = ResilientInt(i: i) expectEqual(i, r.i) } for d in [-1.0, 0.0, -0.0, 1.0] { let r = ResilientDouble(d: d) expectEqual(d, r.d) } } ResilientStructTestSuite.test("StaticLayout") { for b1 in [false, true] { for i in [-12, -1, 12] { for b2 in [false, true] { for d in [-1.0, 0.0, -0.0, 1.0] { let r = ResilientLayoutRuntimeTest(b1: ResilientBool(b: b1), i: ResilientInt(i: i), b2: ResilientBool(b: b2), d: ResilientDouble(d: d)) expectEqual(b1, r.b1.b) expectEqual(i, r.i.i) expectEqual(b2, r.b2.b) expectEqual(d, r.d.d) } } } } } // Make sure structs with dynamic layout are instantiated correctly, // and can conform to protocols. protocol MyResilientLayoutProtocol { var b1: ResilientBool { get } } struct MyResilientLayoutRuntimeTest : MyResilientLayoutProtocol { let b1: ResilientBool let i: ResilientInt let b2: ResilientBool let d: ResilientDouble init(b1: ResilientBool, i: ResilientInt, b2: ResilientBool, d: ResilientDouble) { self.b1 = b1 self.i = i self.b2 = b2 self.d = d } } @inline(never) func getMetadata() -> Any.Type { return MyResilientLayoutRuntimeTest.self } ResilientStructTestSuite.test("DynamicLayoutMetatype") { do { var output = "" let expected = "- main.MyResilientLayoutRuntimeTest #0\n" dump(getMetadata(), &output) expectEqual(output, expected) } do { expectEqual(true, getMetadata() == getMetadata()) } } ResilientStructTestSuite.test("DynamicLayout") { for b1 in [false, true] { for i in [-12, -1, 12] { for b2 in [false, true] { for d in [-1.0, 0.0, -0.0, 1.0] { let r = MyResilientLayoutRuntimeTest(b1: ResilientBool(b: b1), i: ResilientInt(i: i), b2: ResilientBool(b: b2), d: ResilientDouble(d: d)) expectEqual(b1, r.b1.b) expectEqual(i, r.i.i) expectEqual(b2, r.b2.b) expectEqual(d, r.d.d) } } } } } @inline(never) func getB(p: MyResilientLayoutProtocol) -> Bool { return p.b1.b } ResilientStructTestSuite.test("DynamicLayoutConformance") { do { let r = MyResilientLayoutRuntimeTest(b1: ResilientBool(b: true), i: ResilientInt(i: 0), b2: ResilientBool(b: false), d: ResilientDouble(d: 0.0)) expectEqual(getB(r), true) } } protocol ProtocolWithAssociatedType { associatedtype T: MyResilientLayoutProtocol func getT() -> T } struct StructWithDependentAssociatedType : ProtocolWithAssociatedType { let r: MyResilientLayoutRuntimeTest init(r: MyResilientLayoutRuntimeTest) { self.r = r } func getT() -> MyResilientLayoutRuntimeTest { return r } } @inline(never) func getAssociatedType<T : ProtocolWithAssociatedType>(p: T) -> MyResilientLayoutProtocol.Type { return T.T.self } ResilientStructTestSuite.test("DynamicLayoutAssociatedType") { do { let r = MyResilientLayoutRuntimeTest(b1: ResilientBool(b: true), i: ResilientInt(i: 0), b2: ResilientBool(b: false), d: ResilientDouble(d: 0.0)) let metatype: MyResilientLayoutProtocol.Type = MyResilientLayoutRuntimeTest.self let associated: MyResilientLayoutProtocol.Type = getAssociatedType(StructWithDependentAssociatedType(r: r)); expectEqual(true, metatype == associated) expectEqual(getB(r), true) } } runAllTests()
apache-2.0
3dbe44b7f19a08ccb82d52630831eb0a
28.833333
135
0.600041
3.984336
false
true
false
false
inoity/nariko
Nariko/Classes/NarikoTool.swift
1
21928
// // NarikoTool.swift // Nariko // // Created by Zsolt Papp on 10/06/16. // Copyright © 2016 Nariko. All rights reserved. // import UIKit import SwiftHTTP public let okButton = UIButton() open class NarikoTool: UIResponder, UITextViewDelegate, UIGestureRecognizerDelegate { static open let sharedInstance = NarikoTool() var apiKey: String? let APPDELEGATE: UIApplicationDelegate = UIApplication.shared.delegate! let backgroundView = UIView() var narikoAlertView = UIView() var alertView = AlertView() var bubble: BubbleControl! var isAuth: Bool = false var WINDOW: UIWindow? var needReopen: Bool = false var textView = CustomTextView(frame: CGRect.zero) var textViewBackgroundView = UIView(frame: CGRect.zero) let textPlaceholderString = "Write your feedback here..." var firstKeyboardTime = true var container: UIView = UIView() var loadingView: UIView = UIView() var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView() func showActivityIndicator() { let screenSize: CGRect = UIApplication.shared.keyWindow!.bounds container.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height) container.center = CGPoint(x: screenSize.width/2, y: screenSize.height/2) container.backgroundColor = UIColor(red: 234.0/255.0, green: 237.0/255.0, blue: 242.0/255.0, alpha: 0.5) loadingView.frame = CGRect(x: 0, y: 0, width: 60, height: 60) loadingView.center = CGPoint(x: screenSize.width/2, y: (screenSize.height-50)/2) // loadingView.backgroundColor = UIColor.gray let gradientLayer = CAGradientLayer() gradientLayer.frame.size = loadingView.layer.frame.size gradientLayer.colors = [UIColor.gradTop.cgColor, UIColor.gradBottom.cgColor] gradientLayer.locations = [0.0, 1.0] loadingView.layer.addSublayer(gradientLayer) loadingView.clipsToBounds = true loadingView.layer.cornerRadius = 10 self.activityIndicator.frame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0); self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.white self.activityIndicator.center = CGPoint(x: loadingView.frame.size.width / 2, y: loadingView.frame.size.height / 2); loadingView.addSubview(self.activityIndicator) container.addSubview(loadingView) APPDELEGATE.window!!.addSubview(container) self.activityIndicator.startAnimating() } /* Hide activity indicator Actually remove activity indicator from its super view @param uiView - remove activity indicator from this view */ func hideActivityIndicator() { for view in loadingView.subviews { view.removeFromSuperview() } loadingView.removeFromSuperview() container.removeFromSuperview() self.activityIndicator.stopAnimating() } public override init() { super.init() registerSettingsBundle() NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillChangeFrame(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.checkAuth), name: UserDefaults.didChangeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.removeBubble), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) if UserDefaults.standard.string(forKey: "appAlreadyLaunched") == nil { isOnboarding = true let view = self.APPDELEGATE.window!!.rootViewController!.view backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.6) backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight] backgroundView.frame = (view?.frame)! view?.addSubview(backgroundView) narikoAlertView = OnboardingFirst.instanceFromNib() as! OnboardingFirst narikoAlertView.frame = CGRect(x: 20, y: 40, width: (view?.frame.width)! - 40, height: (view?.frame.height)! - 80) narikoAlertView.clipsToBounds = true let longPressRecog = UILongPressGestureRecognizer() longPressRecog.addTarget(self, action: #selector(tap(_:))) longPressRecog.minimumPressDuration = 1.5 longPressRecog.numberOfTouchesRequired = 3 longPressRecog.delegate = self narikoAlertView.addGestureRecognizer(longPressRecog) view?.addSubview(narikoAlertView) narikoAlertView.layoutIfNeeded() backgroundView.alpha = 0 narikoAlertView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {() -> Void in self.backgroundView.alpha = 1 self.narikoAlertView.transform = CGAffineTransform.identity }, completion: {(finished: Bool) -> Void in }) } } @objc fileprivate func tap(_ g: UILongPressGestureRecognizer) { switch g.state { case .began: let view = self.APPDELEGATE.window!!.rootViewController!.view UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: { self.narikoAlertView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) }, completion: { (finished) in if finished { self.narikoAlertView.removeFromSuperview() UserDefaults.standard.set(true, forKey: "appAlreadyLaunched") self.narikoAlertView = OnboardingSecond.instanceFromNib() as! OnboardingSecond self.narikoAlertView.frame = CGRect(x: ((view?.frame.width)! / 2) - (((view?.frame.width)! - 40)/2), y: ((view?.frame.height)! / 2) - (((view?.frame.height)! - 100)/2), width: (view?.frame.width)! - 40, height: (view?.frame.height)! - 100) self.narikoAlertView.clipsToBounds = true view?.addSubview(self.narikoAlertView) self.narikoAlertView.layoutIfNeeded() self.narikoAlertView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {() -> Void in self.backgroundView.alpha = 1 self.narikoAlertView.transform = CGAffineTransform.identity }, completion: { (finished) in if finished { self.needReopen = false self.perform(#selector(self.close), with: nil, afterDelay: 3) } }) } }) default: break } } @objc fileprivate func close() { UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {() -> Void in self.narikoAlertView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) self.alertView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) }, completion: { (finished) in if finished{ isOnboarding = false self.backgroundView.removeFromSuperview() self.narikoAlertView.removeFromSuperview() self.alertView.removeFromSuperview() if self.needReopen{ self.setupBubble() } } }) } open func closeNarikoAlertView() { narikoAlertView.transform = CGAffineTransform.identity UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {() -> Void in self.backgroundView.alpha = 0 self.narikoAlertView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) }, completion: {(finished: Bool) -> Void in self.backgroundView.removeFromSuperview() self.narikoAlertView.removeFromSuperview() }) } deinit { //Not needed for iOS9 and above. ARC deals with the observer. NotificationCenter.default.removeObserver(self) } open func registerSettingsBundle() { let appDefaults = [String:AnyObject]() UserDefaults.standard.register(defaults: appDefaults) } open func checkAuth() { let defaults = UserDefaults.standard // print(defaults.string(forKey: "nar_email")) // print(defaults.string(forKey: "nar_pass")) // print(Bundle.main.bundleIdentifier) if defaults.string(forKey: "nar_email") != nil && defaults.string(forKey: "nar_pass") != nil{ CallApi().authRequest(["Email": defaults.string(forKey: "nar_email")! as AnyObject, "Password": defaults.string(forKey: "nar_pass")! as AnyObject, "BundleId": Bundle.main.bundleIdentifier! as AnyObject], callCompletion: { (success, errorCode, msg) in if success{ self.apiKey = msg self.isAuth = true } else { print(errorCode) let alertController = UIAlertController (title: "Information", message: "Login failed, check your username and password!", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) if let url = settingsUrl { UIApplication.shared.openURL(url) } } let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil) alertController.addAction(settingsAction) alertController.addAction(cancelAction) self.APPDELEGATE.window!!.rootViewController!.present(alertController, animated: true, completion: nil); } }) } else { print("Not logged in!") } } open func setupBubble() { if APPDELEGATE.window!!.viewWithTag(3333) == nil{ let win = APPDELEGATE.window!! win.endEditing(true) bubble = BubbleControl(win: win, size: CGSize(width: 130, height: 80)) bubble.tag = 3333 let podBundle = Bundle(for: NarikoTool.self) if let url = podBundle.url(forResource: "Nariko", withExtension: "bundle") { let bundle = Bundle(url: url) bubble.image = UIImage(named: "Nariko_logo_200", in: bundle, compatibleWith: nil) } bubble.setOpenAnimation = { content, background in self.bubble.contentView!.bottom = win.bottom if (self.bubble.center.x > win.center.x) { self.bubble.contentView!.left = win.right self.bubble.contentView!.right = win.right } else { self.bubble.contentView!.right = win.left self.bubble.contentView!.left = win.left } } firstKeyboardTime = true // firstRot = true textViewBackgroundView.frame = CGRect(x: 0, y: 0, width: win.w, height: 41) textViewBackgroundView.backgroundColor = UIColor.white let topSeparatorView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 1)) topSeparatorView.backgroundColor = UIColor.lightGray textViewBackgroundView.addSubview(topSeparatorView) textView.delegate = self textView.layer.cornerRadius = 14 textView.layer.borderColor = UIColor.lightGray.cgColor textView.layer.borderWidth = 1 textView.autoresizingMask = [.flexibleWidth] textView.font = UIFont.systemFont(ofSize: 16) textView.textContainerInset = UIEdgeInsetsMake(4, 6, 4, 6) textView.scrollIndicatorInsets = UIEdgeInsetsMake(6, 6, 6, 6) textView.returnKeyType = .send textView.frame = CGRect(x: 16, y: 5, width: UIScreen.main.bounds.width - 32, height: 32) textViewBackgroundView.addSubview(textView) textPlaceholder() bubble.contentView = textViewBackgroundView win.addSubview(bubble) } // prevOrient = UIDeviceOrientation.portrait } fileprivate func textPlaceholder() { textView.text = textPlaceholderString textView.textColor = UIColor.lightGray textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument) textView.isEmpty = true updateTextHeight() } public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if(text == "\n") { textView.resignFirstResponder() send() return false } return true } public func textViewDidChange(_ textView: UITextView) { if textView.text == "" { textPlaceholder() } else if self.textView.isEmpty && textView.text != "" { let textPlaceholderStringCount = textPlaceholderString.characters.count textView.text = textView.text.substring(to: textView.text.index(textView.text.endIndex, offsetBy: -textPlaceholderStringCount)) textView.textColor = UIColor.black self.textView.isEmpty = false textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) } updateTextHeight() } public func textViewDidChangeSelection(_ textView: UITextView) { if self.textView.isEmpty { textView.selectedRange = NSMakeRange(0, 0) } } fileprivate func updateTextHeight() { let textViewHeight = textView.sizeThatFits(CGSize(width: textView.frame.width, height: CGFloat(FLT_MAX))).height let textViewClampedHeight = max(28, min(96, textViewHeight)) let heightDiff = textViewClampedHeight - textView.frame.height textView.isScrollEnabled = textViewClampedHeight == 96 if textView.frame.height != textViewClampedHeight { UIView.animate(withDuration: 0.3) { self.textView.frame = CGRect(x: self.textView.frame.origin.x, y: 5, width: self.textView.frame.width, height: textViewClampedHeight) self.textViewBackgroundView.frame = CGRect(x: 0, y: self.textViewBackgroundView.frame.origin.y - heightDiff, width: UIScreen.main.bounds.width, height: textViewClampedHeight + 9) self.bubble.frame = CGRect(x: self.bubble.x, y: self.bubble.y - heightDiff, width: self.bubble.size.width, height: self.bubble.size.height) } } } func keyboardWillChangeFrame(_ notification: Notification) { if let userInfo = notification.userInfo { let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue let duration: TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions().rawValue let animationCurve: UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw) var yOffset: CGFloat = 0 if (endFrame?.origin.y)! < UIScreen.main.bounds.height { yOffset = endFrame!.size.height } if firstKeyboardTime { setContentViewKeyboardFrame(yOffset) if bubble != nil { bubble.moveY(UIScreen.main.bounds.height - yOffset - textViewBackgroundView.frame.height - bubble.size.height) } firstKeyboardTime = false } else { UIView.animate(withDuration: duration, delay: 0, options: animationCurve, animations: { self.setContentViewKeyboardFrame(yOffset) }, completion: nil) if bubble != nil { bubble.moveY(UIScreen.main.bounds.height - yOffset - textViewBackgroundView.frame.height - bubble.size.height) } } if bubble != nil { self.bubble.moveX(UIScreen.main.bounds.width - self.bubble.size.width) } } } func setContentViewKeyboardFrame(_ yOffset: CGFloat) { self.textViewBackgroundView.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - yOffset - self.textViewBackgroundView.frame.height, width: UIScreen.main.bounds.width, height: self.textViewBackgroundView.frame.height) } func send() { if bubble.screenShot != nil { showActivityIndicator() CallApi().sendData(bubble.screenShot!, comment: textView.text) { (success, errorCode, msg) in if success { self.removeBubbleForce() self.hideActivityIndicator() let view = self.APPDELEGATE.window!!.rootViewController!.view self.alertView = AlertView.instanceFromNib() as! AlertView self.alertView.frame = CGRect(x: ((view?.frame.width)! / 2) - (((view?.frame.width)! - 40)/2), y: ((view?.frame.height)! / 2) - (((view?.frame.height)! - 100)/2), width: (view?.frame.width)! - 40, height: (view?.frame.height)! - 100) self.alertView.clipsToBounds = true self.alertView.updateUI(text1: "Your feedback has been submitted.", text2: "Thank you.") self.APPDELEGATE.window!!.rootViewController!.view?.addSubview(self.alertView) self.alertView.layoutIfNeeded() self.alertView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {() -> Void in self.alertView.transform = CGAffineTransform.identity }, completion: { (finished) in if finished{ self.needReopen = true self.perform(#selector(self.close), with: nil, afterDelay: 3) } }) } else { self.hideActivityIndicator() let alert = UIAlertController(title: "Error", message: "The screenshot could not be sent!", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil)) self.APPDELEGATE.window!!.rootViewController!.present(alert, animated: true, completion: nil) } } } else { hideActivityIndicator() let alert = UIAlertController(title: "Information", message: "The screenshot could not be taken!", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil)) APPDELEGATE.window!!.rootViewController!.present(alert, animated: true, completion: nil) } } var prevOrient: UIDeviceOrientation = UIDeviceOrientation.unknown var firstRot = true open func removeBubbleForce() { if let viewWithTag = APPDELEGATE.window!!.viewWithTag(3333) { bubble.closeContentView() viewWithTag.removeFromSuperview() } } open func removeBubble(){ if (prevOrient.isPortrait && UIDevice.current.orientation.isLandscape ) || (prevOrient.isLandscape && UIDevice.current.orientation.isPortrait) { if let viewWithTag = APPDELEGATE.window!!.viewWithTag(3333) { bubble.closeContentView() viewWithTag.removeFromSuperview() self.perform(#selector(self.setupBubble), with: nil, afterDelay: 0.1) } } if !UIDevice.current.orientation.isFlat{ prevOrient = UIDevice.current.orientation } } }
mit
ecd98d952bdf77d9ad77e68d21f51c31
43.476673
263
0.578693
5.319505
false
false
false
false
WilliamHester/Breadit-iOS
Breadit/Views/SubmissionImageCellView.swift
1
1867
// // SubmissionImageCell.swift // Breadit // // Created by William Hester on 4/23/16. // Copyright © 2016 William Hester. All rights reserved. // import UIKit import Alamofire import AlamofireImage class SubmissionImageCellView: SubmissionCellView { private static let previewHeight: CGFloat = 150 weak var delegate: ContentDelegate! var contentImage: UIImageView! var request: Request? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) stackView.add { v in self.contentImage = v.uiImageView { v in v.contentMode = .ScaleAspectFill v.clipsToBounds = true }.constrain { v in v.leftAnchor.constraintEqualToAnchor(self.stackView.leftAnchor).active = true v.rightAnchor.constraintEqualToAnchor(self.stackView.rightAnchor).active = true v.heightAnchor.constraintEqualToConstant(SubmissionImageCellView.previewHeight).active = true } as! UIImageView } let tapDetector = UITapGestureRecognizer(target: self, action: #selector(contentTapped(_:))) tapDetector.delegate = self tapDetector.cancelsTouchesInView = true contentImage.userInteractionEnabled = true contentImage.addGestureRecognizer(tapDetector) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() contentImage?.image = nil if let request = request { request.cancel() self.request = nil } } func contentTapped(sender: UITapGestureRecognizer) { delegate?.contentTapped(submission.link!) } }
apache-2.0
293a0cdc028ed70ed3692f867c882d27
30.627119
109
0.657556
5.286119
false
false
false
false
aschwaighofer/swift
test/Incremental/Verifier/single-file/AnyObject.swift
1
3069
// UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // UNSUPPORTED: CPU=armv7k && OS=ios // Exclude iOS-based 32-bit platforms because the Foundation overlays introduce // an extra dependency on _KeyValueCodingAndObservingPublishing only for 64-bit // platforms. // REQUIRES: objc_interop // RUN: %empty-directory(%t) // RUN: %{python} %S/../gen-output-file-map.py -o %t %S // RUN: cd %t && %target-swiftc_driver -typecheck -output-file-map %t/output.json -incremental -module-name main -verify-incremental-dependencies %s import Foundation // expected-provides {{LookupFactory}} // expected-provides {{NSObject}} // expected-private-superclass {{__C.NSObject}} // expected-private-conformance {{Foundation._KeyValueCodingAndObserving}} // expected-private-conformance {{Foundation._KeyValueCodingAndObservingPublishing}} // expected-private-conformance {{Swift.Hashable}} // expected-private-conformance {{Swift.Equatable}} // expected-private-conformance {{Swift.CustomDebugStringConvertible}} // expected-private-conformance {{Swift.CVarArg}} // expected-private-conformance {{Swift.CustomStringConvertible}} // expected-cascading-member {{Swift._ExpressibleByBuiltinIntegerLiteral.init}} // expected-cascading-superclass {{main.LookupFactory}} @objc private class LookupFactory: NSObject { // expected-provides {{AssignmentPrecedence}} // expected-provides {{IntegerLiteralType}} // expected-provides {{FloatLiteralType}} // expected-provides {{Int}} // expected-cascading-member {{__C.NSObject.someMember}} // expected-cascading-member {{__C.NSObject.Int}} // expected-cascading-member {{main.LookupFactory.Int}} @objc var someMember: Int = 0 // expected-cascading-member {{__C.NSObject.someMethod}} @objc func someMethod() {} // expected-cascading-member {{__C.NSObject.init}} // expected-cascading-member {{main.LookupFactory.init}} // expected-private-member {{main.LookupFactory.deinit}} // expected-cascading-member {{main.LookupFactory.someMember}} // expected-cascading-member {{main.LookupFactory.someMethod}} } // expected-private-member {{Swift.ExpressibleByNilLiteral.callAsFunction}} // expected-private-member {{Swift.CustomReflectable.callAsFunction}} // expected-private-member {{Swift._ObjectiveCBridgeable.callAsFunction}} // expected-private-member {{Swift.Optional.callAsFunction}} // expected-private-member {{Swift.CustomDebugStringConvertible.callAsFunction}} // expected-private-member {{Swift.Equatable.callAsFunction}} // expected-private-member {{Swift.Hashable.callAsFunction}} // expected-private-member {{Swift.Encodable.callAsFunction}} // expected-private-member {{Swift.Decodable.callAsFunction}} // expected-private-member {{Foundation._OptionalForKVO.callAsFunction}} // expected-provides {{AnyObject}} func lookupOnAnyObject(object: AnyObject) { // expected-provides {{lookupOnAnyObject}} _ = object.someMember // expected-private-dynamic-member {{someMember}} object.someMethod() // expected-private-dynamic-member {{someMethod}} }
apache-2.0
470f8fb8e33dd4849dc0767f3d09bfd6
48.5
148
0.759531
4.233103
false
false
false
false
aschwaighofer/swift
stdlib/public/core/BridgeStorage.swift
2
4084
//===--- BridgeStorage.swift - Discriminated storage for bridged types ----===// // // 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 // //===----------------------------------------------------------------------===// // // Types that are bridged to Objective-C need to manage an object // that may be either some native class or the @objc Cocoa // equivalent. _BridgeStorage discriminates between these two // possibilities and stores a single extra bit when the stored type is // native. It is assumed that the @objc class instance may in fact // be a tagged pointer, and thus no extra bits may be available. // //===----------------------------------------------------------------------===// import SwiftShims @frozen @usableFromInline internal struct _BridgeStorage<NativeClass: AnyObject> { @usableFromInline internal typealias Native = NativeClass @usableFromInline internal typealias ObjC = AnyObject // rawValue is passed inout to _isUnique. Although its value // is unchanged, it must appear mutable to the optimizer. @usableFromInline internal var rawValue: Builtin.BridgeObject @inlinable @inline(__always) internal init(native: Native, isFlagged flag: Bool) { // Note: Some platforms provide more than one spare bit, but the minimum is // a single bit. _internalInvariant(_usesNativeSwiftReferenceCounting(NativeClass.self)) rawValue = _makeNativeBridgeObject( native, flag ? (1 as UInt) << _objectPointerLowSpareBitShift : 0) } @inlinable @inline(__always) internal init(objC: ObjC) { _internalInvariant(_usesNativeSwiftReferenceCounting(NativeClass.self)) rawValue = _makeObjCBridgeObject(objC) } @inlinable @inline(__always) internal init(native: Native) { _internalInvariant(_usesNativeSwiftReferenceCounting(NativeClass.self)) rawValue = Builtin.reinterpretCast(native) } #if !(arch(i386) || arch(arm) || arch(wasm32)) @inlinable @inline(__always) internal init(taggedPayload: UInt) { rawValue = _bridgeObject(taggingPayload: taggedPayload) } #endif @inlinable @inline(__always) internal mutating func isUniquelyReferencedNative() -> Bool { return _isUnique(&rawValue) } @inlinable internal var isNative: Bool { @inline(__always) get { let result = Builtin.classifyBridgeObject(rawValue) return !Bool(Builtin.or_Int1(result.isObjCObject, result.isObjCTaggedPointer)) } } @inlinable static var flagMask: UInt { @inline(__always) get { return (1 as UInt) << _objectPointerLowSpareBitShift } } @inlinable internal var isUnflaggedNative: Bool { @inline(__always) get { return (_bitPattern(rawValue) & (_bridgeObjectTaggedPointerBits | _objCTaggedPointerBits | _objectPointerIsObjCBit | _BridgeStorage.flagMask)) == 0 } } @inlinable internal var isObjC: Bool { @inline(__always) get { return !isNative } } @inlinable internal var nativeInstance: Native { @inline(__always) get { _internalInvariant(isNative) return Builtin.castReferenceFromBridgeObject(rawValue) } } @inlinable internal var unflaggedNativeInstance: Native { @inline(__always) get { _internalInvariant(isNative) _internalInvariant(_nonPointerBits(rawValue) == 0) return Builtin.reinterpretCast(rawValue) } } @inlinable @inline(__always) internal mutating func isUniquelyReferencedUnflaggedNative() -> Bool { _internalInvariant(isNative) return _isUnique_native(&rawValue) } @inlinable internal var objCInstance: ObjC { @inline(__always) get { _internalInvariant(isObjC) return Builtin.castReferenceFromBridgeObject(rawValue) } } }
apache-2.0
eb74640c5a77829c84cc8e32a75aaaf3
27.964539
80
0.673115
4.715935
false
false
false
false
luismatute/On-The-Map
On The Map/ParseClient.swift
1
3022
// // ParseClient.swift // On The Map // // Created by Luis Matute on 5/28/15. // Copyright (c) 2015 Luis Matute. All rights reserved. // import Foundation class ParseClient: NSObject { // MARK: - Properties let auth = [ Constants.APPID: "X-Parse-Application-Id", Constants.APIKey: "X-Parse-REST-API-Key" ] var locations = [StudentLocation]() // MARK: - Class Properties override init() { super.init() } // MARK: - Convinience func getStudentLocations(forceDownload: Bool, callback: (result: [StudentLocation]?, errorString: String?) -> Void) { let parameters = [ParameterKeys.Limit: 100] let mutableParameters = $.escapedParameters(parameters) let urlString = "\(ParseClient.Constants.BaseURL)\(ParseClient.Methods.StudentLocation)" + mutableParameters var le_results = [StudentLocation]() // Check if we have already loaded the locations // If there is nothing, fetch them if self.locations.count == 0 || forceDownload == true { $.get(urlString).genericValues(auth).parseJSONWithCompletion(0) { (result, response, error) in if let error = error { callback(result: nil, errorString: error.localizedDescription) } else { if let results = result.valueForKey(JSONResponseKeys.Results) as? [[String : AnyObject]] { var locations = StudentLocation.studentLocationFromResults(results) callback(result: locations, errorString: nil) } else { callback(result: nil, errorString: "No Results Found") } } } } else { callback(result: self.locations, errorString: nil) } } func postStudentLocation(studentLocation: StudentLocation, callback: (success: Bool, errorString: String?) -> Void) { let urlString = "\(ParseClient.Constants.BaseURL)\(ParseClient.Methods.StudentLocation)" let jsonBody: String = "{\"uniqueKey\": \"\(studentLocation.uniqueKey)\", \"firstName\": \"\(studentLocation.firstName)\", \"lastName\": \"\(studentLocation.lastName)\",\"mapString\": \"\(studentLocation.mapString)\", \"mediaURL\": \"\(studentLocation.mediaURL)\",\"latitude\": \(studentLocation.latitude), \"longitude\": \(studentLocation.longitude)}" $.post(urlString).genericValues(auth).json(jsonBody).parseJSONWithCompletion(0) { (result, response, error) in if let err = error { callback(success: false, errorString: error.localizedDescription) } else { callback(success: true, errorString: nil) } } } // MARK: - Shared Instance class func sharedInstance() -> ParseClient { struct singleton { static var sharedInstance = ParseClient() } return singleton.sharedInstance } }
mit
177291f7776f225a6b0a0483cd67ef09
40.986111
360
0.601919
4.954098
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/GSR-Booking/Model/GSRLocationModel.swift
1
1012
// // GSRLocationModel.swift // PennMobile // // Created by Josh Doman on 2/3/18. // Copyright © 2018 PennLabs. All rights reserved. // import Foundation import SwiftyJSON class GSRLocationModel { static let shared = GSRLocationModel() fileprivate var locations = [GSRLocation]() func getLocations() -> [GSRLocation] { return locations } func getLocationName(for lid: String, gid: Int?) -> String { for location in locations { if location.lid == lid && location.gid == gid { return location.name } } return "" } func prepare() { DispatchQueue.main.async { GSRNetworkManager.instance.getLocations { result in switch result { case .success(let locations): self.locations = locations case .failure: // TODO handle error break } } } } }
mit
51392578c26f358617f9ea5005caa52f
22.511628
64
0.532146
4.814286
false
false
false
false
pkrawat1/TravelApp-ios
TravelApp/View/UserProfile/UserProfileCell.swift
1
6074
// // UserProfileCell.swift // TravelApp // // Created by Nitesh on 16/02/17. // Copyright © 2017 Pankaj Rawat. All rights reserved. // import UIKit class UserProfileCell: BaseCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { let cell = "cellId" let userFeed = "userFeed" let followerFeed = "followerFeed" let followingFeed = "followingFeed" let mediaFeed = "mediaFeed" var user: User? { didSet { print("******\(user?.email)") setupThumbnailImage() setupProfileImage() profileHeader.userNameLabel.text = user?.name } } lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() let cv = UICollectionView(frame: CGRect.init(), collectionViewLayout: layout) cv.backgroundColor = UIColor.appMainBGColor() cv.translatesAutoresizingMaskIntoConstraints = false cv.dataSource = self cv.delegate = self return cv }() lazy var menubar: UserMenuBar = { let mb = UserMenuBar() mb.userProfileCell = self mb.translatesAutoresizingMaskIntoConstraints = false return mb }() let profileHeader: UserProfileHeader = { let ph = UserProfileHeader() ph.translatesAutoresizingMaskIntoConstraints = false return ph }() func fetchUserDetails() { UserService.sharedInstance.getUser(userId: sharedData.currentUser.id!) { (user) in self.user = user self.collectionView.reloadData() } } override func setupViews() { // user = SharedData.sharedInstance.getCurrentUser() // fetchUserTripsFeed() fetchUserDetails() // print("******\(user?.email)") setupProfileHeader() setupMenuBar() setupCollectionView() } func setupThumbnailImage() { if let thumbnailImageUrl = user?.cover_photo?.url { self.profileHeader.thumbnailImageView.loadImageUsingUrlString(urlString: thumbnailImageUrl, width: Float(frame.width)) } } func setupProfileImage() { if let profileImageURL = user?.profile_pic?.url { self.profileHeader.userProfileImageView.loadImageUsingUrlString(urlString: profileImageURL, width: 44) } } func scrollToMenuIndex(menuIndex: IndexPath) { collectionView.scrollToItem(at: menuIndex, at: [], animated: true) } private func setupCollectionView() { if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.scrollDirection = .horizontal flowLayout.minimumLineSpacing = 0 } collectionView.isPagingEnabled = true addSubview(collectionView) collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cell) collectionView.register(UserFeed.self,forCellWithReuseIdentifier: userFeed) collectionView.register(Followers.self, forCellWithReuseIdentifier: followerFeed) collectionView.register(Followers.self, forCellWithReuseIdentifier: followingFeed) collectionView.register(Media.self, forCellWithReuseIdentifier: mediaFeed) collectionView.topAnchor.constraint(equalTo: menubar.bottomAnchor).isActive = true collectionView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true collectionView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true } private func setupProfileHeader() { addSubview(profileHeader) profileHeader.topAnchor.constraint(equalTo: topAnchor).isActive = true profileHeader.widthAnchor.constraint(equalTo: widthAnchor).isActive = true profileHeader.heightAnchor.constraint(equalToConstant: 150).isActive = true } private func setupMenuBar() { addSubview(menubar) menubar.topAnchor.constraint(equalTo: profileHeader.bottomAnchor).isActive = true menubar.widthAnchor.constraint(equalTo: widthAnchor).isActive = true menubar.heightAnchor.constraint(equalToConstant: 40).isActive = true } func scrollViewDidScroll(_ scrollView: UIScrollView) { menubar.horizontalBarLeftAnchor?.constant = scrollView.contentOffset.x / 4 } func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let index = targetContentOffset.pointee.x / frame.width let indexPath = NSIndexPath(item: Int(index), section: 0) menubar.collectionView.selectItem(at: indexPath as IndexPath, animated: true, scrollPosition: []) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 4 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var identifier: String = "" switch indexPath.item { case 0: identifier = userFeed case 1: identifier = followerFeed case 2: identifier = followingFeed case 3: identifier = mediaFeed default: identifier = userFeed } if indexPath.item == 0 { identifier = userFeed } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) cell.backgroundColor = UIColor.white return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: frame.width, height: frame.height) } }
mit
bfff14a1d27a8c5c882b2f8761bbcf3f
32.368132
160
0.650585
5.702347
false
false
false
false
devnikor/WordsKit
Tests/Data/StringsStatistic.swift
1
2603
// // StringsStatistic.swift // WordsKit // // Created by Игорь Никитин on 18.04.16. // // import Foundation struct StringsStatistic { let strings: [String] let frequentWords: [(String, Int)] let stringIndexWithMostOfTheFrequentWords: Int } extension StringsStatistic { static func smallDataSet() -> StringsStatistic { let strings = [ "Игорь пошел гулять", "Гулять пошел не Игорь, гулять отправился Антошка", "Я отправил гулять трех собак" ] let frequentWords = [ ("Гулять", 4), ("Игорь", 2), ("пошел", 2), ("Антошка", 1), ("не", 1), ("отправил", 1), ("отправился", 1), ("собак", 1), ("трех", 1), ("Я", 1), ] return StringsStatistic( strings: strings, frequentWords: frequentWords, stringIndexWithMostOfTheFrequentWords: 1 ) } static func emptyDataSet() -> StringsStatistic { return StringsStatistic( strings: [], frequentWords: [], stringIndexWithMostOfTheFrequentWords: 0 ) } static func wrongDataSet() -> StringsStatistic { let strings = ["d231e", "fkgji4", "1w"] let frequentWords = [("1w", 1), ("d231e", 1), ("fkgji4", 1)] return StringsStatistic( strings: strings, frequentWords: frequentWords, stringIndexWithMostOfTheFrequentWords: 0 ) } static func oneWordDataSet() -> StringsStatistic { let strings = ["привет"] let frequentWords = [("привет", 1)] return StringsStatistic( strings: strings, frequentWords: frequentWords, stringIndexWithMostOfTheFrequentWords: 0 ) } static func oneWordStringsDataSet() -> StringsStatistic { let strings = [ "привет", "как", "дела", "как", "жизнь" ] let frequentWords = [ ("как", 2), ("дела", 1), ("жизнь", 1), ("привет", 1) ] return StringsStatistic( strings: strings, frequentWords: frequentWords, stringIndexWithMostOfTheFrequentWords: 1 ) } }
mit
a76b3124462e5eba8ba4258c7e05c808
24.595745
68
0.50665
4.030151
false
false
false
false
CeranPaul/SketchCurves
SketchGen/Spline.swift
1
6853
// // Spline.swift // SketchCurves // // Created by Paul on 7/18/16. // Copyright © 2018 Ceran Digital Media. All rights reserved. See LICENSE.md // import UIKit /// Sequence of Cubic curves in 3D - tangent at the interior points /// This will eventually need to conform to protocol PenCurve /// Each piece is assumed to be parameterized from 0 to 1 open class Spline: PenCurve { // TODO: Explain this in a blog page // TODO: Add all of the functions that will make this comply with PenCurve. And the occasional test. // What to do about a closed Spline? /// Sequence of component curves var pieces: [Cubic] /// The enum that hints at the meaning of the curve open var usage: PenTypes open var parameterRange: ClosedRange<Double> // Never used /// Build from an ordered array of points using finite differences /// See the Wikipedia article on Cubic Hermite splines init(pts: [Point3D]) { pieces = [Cubic]() var deltaX = pts[1].x - pts[0].x var deltaY = pts[1].y - pts[0].y var deltaZ = pts[1].z - pts[0].z /// Because of the above assumption that each piece is parameterized in the range of 0 to 1 var slopePrior = Vector3D(i: deltaX, j: deltaY, k: deltaZ) /// Value will be calculated with each iteration in the loop var slopeNext: Vector3D for index in 1..<pts.count - 1 { deltaX = pts[index + 1].x - pts[index].x deltaY = pts[index + 1].y - pts[index].y deltaZ = pts[index + 1].z - pts[index].z slopeNext = Vector3D(i: deltaX, j: deltaY, k: deltaZ) let slopeFresh = (slopePrior + slopeNext) * 0.5 // Average let veer = Cubic(ptA: pts[index - 1], slopeA: slopePrior, ptB: pts[index], slopeB: slopeFresh) pieces.append(veer) // This might be a good place for a diagram showing the array indexing of points and curves slopePrior = slopeFresh // Prepare for the next iteration } deltaX = pts[pts.count - 1].x - pts[pts.count - 2].x deltaY = pts[pts.count - 1].y - pts[pts.count - 2].y deltaZ = pts[pts.count - 1].z - pts[pts.count - 2].z slopeNext = Vector3D(i: deltaX, j: deltaY, k: deltaZ) let veer = Cubic(ptA: pts[pts.count - 2], slopeA: slopePrior, ptB: pts[pts.count - 1], slopeB: slopeNext) pieces.append(veer) // Final piece in the array self.usage = PenTypes.ordinary self.pieces.forEach( {$0.setIntent(purpose: PenTypes.ordinary)} ) self.parameterRange = ClosedRange<Double>(uncheckedBounds: (lower: 0.0, upper: 1.0)) } /// Build from an array of points and correponding tangents, probably from screen points /// - Parameters: /// - pts: Points on the desired curve /// - tangents: Matched vectors to specify slope /// Currently doesn't check the length of input arrays init(pts: [Point3D], tangents: [Vector3D]) { pieces = [Cubic]() for ptIndex in 1..<pts.count { let alpha = pts[ptIndex - 1] // Retrieve the end points let omega = pts[ptIndex] let tangentA = tangents[(ptIndex - 1) * 2] let tangentB = tangents[(ptIndex - 1) * 2 + 1] let fresh = Cubic(ptA: alpha, slopeA: tangentA, ptB: omega, slopeB: tangentB) pieces.append(fresh) } self.usage = PenTypes.ordinary self.pieces.forEach( {$0.setIntent(purpose: PenTypes.ordinary)} ) self.parameterRange = ClosedRange<Double>(uncheckedBounds: (lower: 0.0, upper: 1.0)) } /// Build from an array of Cubics - typically the result of transforming init(curves: [Cubic]) { self.pieces = curves self.usage = PenTypes.ordinary self.parameterRange = ClosedRange<Double>(uncheckedBounds: (lower: 0.0, upper: 1.0)) } /// Attach new meaning to the curve. public func setIntent(purpose: PenTypes) -> Void { self.usage = purpose self.pieces.forEach( {$0.setIntent(purpose: purpose)} ) } /// Fetch the location of an end. /// - See: 'getOtherEnd()' public func getOneEnd() -> Point3D { let locomotive = pieces.first! return locomotive.getOneEnd() } /// Fetch the location of the opposite end. /// - See: 'getOneEnd()' public func getOtherEnd() -> Point3D { let caboose = pieces.last! return caboose.getOtherEnd() } /// Generate an enclosing volume public func getExtent() -> OrthoVol { var brick = self.pieces.first!.getExtent() if self.pieces.count > 1 { for g in 1..<self.pieces.count { brick = brick + self.pieces[g].getExtent() } } return brick } public func pointAt(t: Double) -> Point3D { let dummy = Point3D(x: 0.0, y: 0.0, z: 0.0) return dummy } /// Change the order of the components in the array, and the order of each component public func reverse() -> Void { self.pieces.forEach( {$0.reverse()} ) self.pieces = self.pieces.reversed() } /// Transform the set. /// Problem with the return type. public func transform(xirtam: Transform) -> PenCurve { let spaghetti = self.pieces.map( {$0.transform(xirtam: xirtam)} ) let _ = Spline(curves: spaghetti as! [Cubic]) return spaghetti.first! } /// Find the position of a point relative to the spline and its start point. /// Useless result at the moment. /// - Parameters: /// - speck: Point near the curve. /// - Returns: Tuple of distances relative to the origin public func resolveRelative(speck: Point3D) -> (along: Double, away: Double) { return (1.0, 1.0) } /// Plot the curves. This will be called by the UIView 'drawRect' function /// Won't be useful until Spline conforms to PenCurve /// - Parameters: /// - context: In-use graphics framework /// - tform: Model-to-display transform public func draw(context: CGContext, tform: CGAffineTransform) -> Void { self.pieces.forEach( {$0.draw(context: context, tform: tform)} ) } }
apache-2.0
e701bb75fbd86eebee2d902de68c3bd7
29.864865
125
0.555458
4.068884
false
false
false
false
hjcapple/LayoutKit
LayoutKit/LayoutKit.swift
1
18753
import Foundation #if os(iOS) import UIKit public typealias LayoutKitView = UIView #else import AppKit public typealias LayoutKitView = NSView #endif public extension LayoutKitView { func tk_layout(_ callback: ((inout LayoutKitMaker) -> Void)) { var make = LayoutKitMaker(bounds: self.bounds) callback(&make) } } public extension CGRect { func tk_layout(_ callback: ((inout LayoutKitMaker) -> Void)) { var make = LayoutKitMaker(bounds: self) callback(&make) } } /// //////////////////////////////////////////////////////// public struct LayoutKitMaker { fileprivate var _bounds: CGRect public var flexible: LayoutKitFlexible { return LayoutKitFlexible(num: 1) } public var placeHolder: LayoutKitPlaceHolder { return LayoutKitPlaceHolder() } public var w: CGFloat { return _bounds.size.width } public var h: CGFloat { return _bounds.size.height } public init(bounds: CGRect) { _bounds = bounds } } // MARK: - // MARK: bounds extension LayoutKitMaker { public mutating func resetBounds(_ bounds: CGRect) { _bounds = bounds } @discardableResult public mutating func insetEdges(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) -> CGRect { let oldBounds = _bounds _bounds.origin.x += left _bounds.origin.y += top _bounds.size.width -= (left + right) _bounds.size.height -= (top + bottom) return oldBounds } @discardableResult public mutating func insetEdges(edge: CGFloat) -> CGRect { return insetEdges(top: edge, left: edge, bottom: edge, right: edge) } } // MARK: - // MARK: size extension LayoutKitMaker { public struct SizeGroup { private let _views: [LayoutKitView] fileprivate init(views: [LayoutKitView]) { _views = views } fileprivate func setValue(_ size: CGSize) { for view in _views { var rt = view.frame rt.size = size view.frame = rt } } } public func size(_ views: [LayoutKitView]) -> SizeGroup { return SizeGroup(views: views) } public func size(_ views: LayoutKitView...) -> SizeGroup { return size(views) } } public func == (group: LayoutKitMaker.SizeGroup, size: CGSize) { group.setValue(size) } public func == (group: LayoutKitMaker.SizeGroup, size: (CGFloat, CGFloat)) { group == CGSize(width: size.0, height: size.1) } // MARK: - // MARK: width extension LayoutKitMaker { public struct WidthGroup { private let _items: [LayoutKitSetWidthItem] private let _totalWidth: CGFloat fileprivate init(items: [LayoutKitSetWidthItem], totalWidth: CGFloat) { _items = items _totalWidth = totalWidth } fileprivate func setValue(_ value: CGFloat) { for item in _items { item.layoutKit_setFrameWidth(value) } } fileprivate func setValues(_ values: [LayoutKitxPlaceItem]) { let flexibleValue = computeXFlexibleValue(_totalWidth, values) let count = min(_items.count, values.count) for i in 0 ..< count { let frameWidth = computeTotalWidth(values[i], flexibleValue: flexibleValue) _items[i].layoutKit_setFrameWidth(frameWidth) } } } public func width(_ items: [LayoutKitSetWidthItem]) -> WidthGroup { return WidthGroup(items: items, totalWidth: _bounds.size.width) } public func width(_ items: LayoutKitSetWidthItem...) -> WidthGroup { return width(items) } } public func == (group: LayoutKitMaker.WidthGroup, value: CGFloat) { group.setValue(value) } public func == (group: LayoutKitMaker.WidthGroup, values: [LayoutKitxPlaceItem]) { group.setValues(values) } // MARK: - // MARK: height extension LayoutKitMaker { public struct HeightGroup { private let _items: [LayoutKitSetHeightItem] private let _totalHeight: CGFloat fileprivate init(items: [LayoutKitSetHeightItem], totalHeight: CGFloat) { _items = items _totalHeight = totalHeight } fileprivate func setValue(_ value: CGFloat) { for item in _items { item.layoutKit_setFrameHeight(value) } } fileprivate func setValues(_ values: [LayoutKityPlaceItem]) { let flexibleValue = computeYFlexibleValue(_totalHeight, values) let count = min(_items.count, values.count) for i in 0 ..< count { let frameHeight = computeTotalHeight(values[i], flexibleValue: flexibleValue) _items[i].layoutKit_setFrameHeight(frameHeight) } } } public func height(_ items: [LayoutKitSetHeightItem]) -> HeightGroup { return HeightGroup(items: items, totalHeight: _bounds.height) } public func height(_ items: LayoutKitSetHeightItem...) -> HeightGroup { return height(items) } } public func == (group: LayoutKitMaker.HeightGroup, value: CGFloat) { group.setValue(value) } public func == (group: LayoutKitMaker.HeightGroup, value: [LayoutKityPlaceItem]) { group.setValues(value) } // MARK: - // MARK: xPlace extension LayoutKitMaker { static fileprivate func xPlace(_ items: [LayoutKitxPlaceItem], bounds: CGRect) { let flexibleValue = computeXFlexibleValue(bounds.width, items) var xpos = bounds.minX for item in items { item.layoutKit_setFrameOriginX(xpos) xpos += computeTotalWidth(item, flexibleValue: flexibleValue) } } public func xPlace(_ items: [LayoutKitxPlaceItem]) { LayoutKitMaker.xPlace(items, bounds: _bounds) } public func xPlace(_ items: LayoutKitxPlaceItem...) { return xPlace(items) } } // MARK: - // MARK: yPlace extension LayoutKitMaker { static fileprivate func yPlace(_ items: [LayoutKityPlaceItem], bounds: CGRect) { let flexibleValue = computeYFlexibleValue(bounds.height, items) var ypos = bounds.minY for item in items { item.layoutKit_setFrameOriginY(ypos) ypos += computeTotalHeight(item, flexibleValue: flexibleValue) } } public func yPlace(_ items: [LayoutKityPlaceItem]) { LayoutKitMaker.yPlace(items, bounds: _bounds) } public func yPlace(_ items: LayoutKityPlaceItem...) { return yPlace(items) } } // MARK: - // MARK: xPlace fixed extension LayoutKitMaker { public func xPlace(fixed first: LayoutKitView, _ items: LayoutKitxPlaceItem ...) { var bounds = _bounds let maxX = _bounds.maxX bounds.origin.x = first.frame.maxX bounds.size.width = maxX - bounds.origin.x LayoutKitMaker.xPlace(items, bounds: bounds) } public func xPlace(_ items: LayoutKitxPlaceItem ..., fixed last: LayoutKitView) { var bounds = _bounds let maxX = last.frame.minX bounds.size.width = maxX - bounds.origin.x LayoutKitMaker.xPlace(items, bounds: bounds) } } // MARK: - // MARK: yPlace fixed extension LayoutKitMaker { public func yPlace(fixed first: LayoutKitView, _ items: LayoutKityPlaceItem ...) { var bounds = _bounds let maxY = bounds.maxY bounds.origin.y = first.frame.maxY bounds.size.height = maxY - bounds.origin.y LayoutKitMaker.yPlace(items, bounds: bounds) } public func yPlace(_ items: LayoutKityPlaceItem ..., fixed last: LayoutKitView) { var bounds = _bounds; let minY = last.frame.minY bounds.size.height = minY - bounds.origin.y LayoutKitMaker.yPlace(items, bounds: bounds) } } // MARK: - // MARK: xCenter extension LayoutKitMaker { public func xCenter(_ views: [LayoutKitView]) { let midX = _bounds.midX for view in views { var frame = view.frame frame.origin.x = midX - frame.size.width * 0.5 view.frame = frame } } public func xCenter(_ views: LayoutKitView...) { xCenter(views) } } // MARK: - // MARK: yCenter extension LayoutKitMaker { public func yCenter(_ views: [LayoutKitView]) { let midY = _bounds.midY for view in views { var frame = view.frame frame.origin.y = midY - frame.size.height * 0.5 view.frame = frame } } public func yCenter(_ views: LayoutKitView...) { yCenter(views) } } // MARK: - // MARK: center extension LayoutKitMaker { public func center(_ views: [LayoutKitView]) { let midY = _bounds.midY let midX = _bounds.midX for view in views { var frame = view.frame frame.origin.x = midX - frame.size.width * 0.5 frame.origin.y = midY - frame.size.height * 0.5 view.frame = frame } } public func center(_ views: LayoutKitView...) { center(views) } } // MARK: - // MARK: xLeft extension LayoutKitMaker { public func xLeft(_ views: [LayoutKitView]) { let minX = _bounds.minX for view in views { var frame = view.frame frame.origin.x = minX view.frame = frame } } public func xLeft(_ views: LayoutKitView...) { xLeft(views) } } // MARK: - // MARK: xRight extension LayoutKitMaker { public func xRight(_ views: [LayoutKitView]) { let maxX = _bounds.maxX for view in views { var frame = view.frame frame.origin.x = maxX - frame.size.width view.frame = frame } } public func xRight(_ views: LayoutKitView...) { xRight(views) } } // MARK: - // MARK: yTop extension LayoutKitMaker { public func yTop(_ views: [LayoutKitView]) { let minY = _bounds.minY for view in views { var frame = view.frame frame.origin.y = minY view.frame = frame } } public func yTop(_ views: LayoutKitView...) { yTop(views) } } // MARK: - // MARK: yBottom extension LayoutKitMaker { public func yBottom(_ views: [LayoutKitView]) { let maxY = _bounds.maxY for view in views { var frame = view.frame frame.origin.y = maxY - frame.size.height view.frame = frame } } public func yBottom(_ views: LayoutKitView...) { yBottom(views) } } // MARK: - // MARK: xEqual extension LayoutKitMaker { public func xEqual(_ views: [LayoutKitView]) { for view in views { var frame = view.frame frame.origin.x = _bounds.origin.x frame.size.width = _bounds.size.width view.frame = frame } } public func xEqual(_ views: LayoutKitView...) { xEqual(views) } } // MARK: - // MARK: yEqual extension LayoutKitMaker { public func yEqual(_ views: [LayoutKitView]) { for view in views { var frame = view.frame frame.origin.y = _bounds.origin.y frame.size.height = _bounds.size.height view.frame = frame } } public func yEqual(_ views: LayoutKitView...) { yEqual(views) } } // MARK: - // MARK: equal extension LayoutKitMaker { public func equal(_ views: [LayoutKitView]) { for view in views { view.frame = _bounds } } public func equal(_ views: LayoutKitView...) { equal(views) } } #if os(iOS) // MARK: - // MARK: sizeToFit extension LayoutKitMaker { public func sizeToFit(_ views: [UIView]) { for view in views { view.sizeToFit() } } public func sizeToFit(_ views: UIView...) { sizeToFit(views) } } #endif // MARK: - // MARK: ref extension LayoutKitMaker { public func ref(_ view: LayoutKitView) -> LayoutKitMaker { return LayoutKitMaker(bounds: view.frame) } } // MARK: - // MARK: Flexible Value extension LayoutKitMaker { public func xFlexibleValue(_ items: [LayoutKitxPlaceItem]) -> CGFloat { return computeXFlexibleValue(_bounds.size.width, items) } public func xFlexibleValue(_ items: LayoutKitxPlaceItem...) -> CGFloat { return computeXFlexibleValue(_bounds.size.width, items) } fileprivate func yFlexibleValue(_ items: [LayoutKityPlaceItem]) -> CGFloat { return computeYFlexibleValue(_bounds.size.height, items) } public func yFlexibleValue(_ items: LayoutKityPlaceItem...) -> CGFloat { return computeYFlexibleValue(_bounds.size.height, items) } } /// ///////////////////////////////////////////////// // MARK: - // MARK: protocol public protocol LayoutKitxPlaceItem { var layoutKit_frameWidth: CGFloat { get } var layoutKit_numOfFlexible: CGFloat { get } func layoutKit_setFrameOriginX(_ x: CGFloat) } public protocol LayoutKityPlaceItem { var layoutKit_frameHeight: CGFloat { get } var layoutKit_numOfFlexible: CGFloat { get } func layoutKit_setFrameOriginY(_ y: CGFloat) } public protocol LayoutKitSetWidthItem { func layoutKit_setFrameWidth(_ width: CGFloat) } public protocol LayoutKitSetHeightItem { func layoutKit_setFrameHeight(_ height: CGFloat) } /// /////////////////////////////////// public final class LayoutKitRectHolder: LayoutKitxPlaceItem, LayoutKityPlaceItem, LayoutKitSetWidthItem, LayoutKitSetHeightItem { public var rect: CGRect public init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) { rect = CGRect(x: x, y: y, width: width, height: height) } public init(rect: CGRect) { self.rect = rect } public var layoutKit_numOfFlexible: CGFloat { return 0 } public var layoutKit_frameWidth: CGFloat { return rect.width } public var layoutKit_frameHeight: CGFloat { return rect.height } public func layoutKit_setFrameOriginX(_ x: CGFloat) { rect.origin.x = x } public func layoutKit_setFrameOriginY(_ y: CGFloat) { rect.origin.y = y } public func layoutKit_setFrameWidth(_ width: CGFloat) { rect.size.width = width } public func layoutKit_setFrameHeight(_ height: CGFloat) { rect.size.height = height } } // MARK: - // MARK: View extension LayoutKitView: LayoutKitxPlaceItem, LayoutKityPlaceItem, LayoutKitSetWidthItem, LayoutKitSetHeightItem { public var layoutKit_numOfFlexible: CGFloat { return 0 } public var layoutKit_frameWidth: CGFloat { return self.frame.width } public var layoutKit_frameHeight: CGFloat { return self.frame.height } public func layoutKit_setFrameOriginX(_ x: CGFloat) { var rt = self.frame rt.origin.x = x self.frame = rt } public func layoutKit_setFrameOriginY(_ y: CGFloat) { var rt = self.frame rt.origin.y = y self.frame = rt } public func layoutKit_setFrameWidth(_ width: CGFloat) { var rt = self.frame rt.size.width = width self.frame = rt } public func layoutKit_setFrameHeight(_ height: CGFloat) { var rt = self.frame rt.size.height = height self.frame = rt } } // MARK: - // MARK: CGFloat extension CGFloat: LayoutKitxPlaceItem, LayoutKityPlaceItem { public var layoutKit_numOfFlexible: CGFloat { return 0 } public var layoutKit_frameWidth: CGFloat { return self } public var layoutKit_frameHeight: CGFloat { return self } public func layoutKit_setFrameOriginX(_ x: CGFloat) { } public func layoutKit_setFrameOriginY(_ y: CGFloat) { } } // MARK: - // MARK: Int extension Int: LayoutKitxPlaceItem, LayoutKityPlaceItem { public var layoutKit_numOfFlexible: CGFloat { return 0 } public var layoutKit_frameWidth: CGFloat { return CGFloat(self) } public var layoutKit_frameHeight: CGFloat { return CGFloat(self) } public func layoutKit_setFrameOriginX(_ x: CGFloat) { } public func layoutKit_setFrameOriginY(_ y: CGFloat) { } } // MARK: - // MARK: LayoutKitFlexible public struct LayoutKitFlexible: LayoutKitxPlaceItem, LayoutKityPlaceItem { fileprivate let _num: CGFloat fileprivate init(num: CGFloat) { _num = num } public var layoutKit_numOfFlexible: CGFloat { return _num } public var layoutKit_frameWidth: CGFloat { return CGFloat(0.0) } public var layoutKit_frameHeight: CGFloat { return CGFloat(0.0) } public func layoutKit_setFrameOriginX(_ x: CGFloat) { } public func layoutKit_setFrameOriginY(_ y: CGFloat) { } } public func * (flexible: LayoutKitFlexible, num: CGFloat) -> LayoutKitFlexible { return LayoutKitFlexible(num: flexible._num * num) } public func * (num: CGFloat, flexible: LayoutKitFlexible) -> LayoutKitFlexible { return LayoutKitFlexible(num: flexible._num * num) } // MARK: - // MARK: LayoutKitPlaceHolder public struct LayoutKitPlaceHolder: LayoutKitSetWidthItem, LayoutKitSetHeightItem { public func layoutKit_setFrameWidth(_ width: CGFloat) { } public func layoutKit_setFrameHeight(_ height: CGFloat) { } } /// ////////////////////////////////////////////// // MARK: - // MARK: private functions private func computeTotalWidth(_ item: LayoutKitxPlaceItem, flexibleValue: CGFloat) -> CGFloat { return item.layoutKit_frameWidth + item.layoutKit_numOfFlexible * flexibleValue } private func computeTotalHeight(_ item: LayoutKityPlaceItem, flexibleValue: CGFloat) -> CGFloat { return item.layoutKit_frameHeight + item.layoutKit_numOfFlexible * flexibleValue } private func computeXFlexibleValue(_ totalWidth: CGFloat, _ items: [LayoutKitxPlaceItem]) -> CGFloat { var total = totalWidth var num: CGFloat = 0 for item in items { num += item.layoutKit_numOfFlexible total -= item.layoutKit_frameWidth } return (num < CGFloat.ulpOfOne) ? 0 : (total / num) } private func computeYFlexibleValue(_ totalHeight: CGFloat, _ items: [LayoutKityPlaceItem]) -> CGFloat { var total = totalHeight var num: CGFloat = 0 for item in items { num += item.layoutKit_numOfFlexible total -= item.layoutKit_frameHeight } return (num < CGFloat.ulpOfOne) ? 0 : (total / num) } /// ///////////////////////////////////////////////////
mit
404481835d55ab20c8baf078799ac97e
24.171812
129
0.610569
4.141564
false
false
false
false
nacho4d/Kitura-net
Sources/KituraNet/BufferList.swift
1
3647
/** * Copyright IBM Corporation 2016 * * 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. **/ #if os(OSX) import Darwin #elseif os(Linux) import Glibc #endif import Foundation // MARK: BufferList public class BufferList { // MARK: -- Private /// /// Internal storage buffer /// private var lclData = NSMutableData(capacity: 4096) /// /// Byte offset inside of internal storage buffer private var byteIndex = 0 // MARK: -- Public /// /// Get the number of bytes stored in the BufferList public var count: Int { return lclData!.length } /// /// Read the data in the BufferList /// public var data: NSData? { return lclData as NSData? } /// /// Initializes a BufferList instance /// /// - Returns: a BufferList instance /// public init() {} /// /// Append bytes in an array to buffer /// /// Parameter bytes: a pointer to the array /// Parameter length: number of bytes in the array /// public func appendBytes(bytes: UnsafePointer<UInt8>, length: Int) { lclData!.appendBytes(bytes, length: length) } /// /// Append data into BufferList /// /// Parameter data: The data to append /// public func appendData(data: NSData) { lclData!.appendBytes(data.bytes, length: data.length) } /// /// Fill the buffer with a byte array data /// /// - Parameter buffer: a [UInt8] for data you want in the buffer /// /// - Returns: /// public func fillArray(inout buffer: [UInt8]) -> Int { let result = min(buffer.count, lclData!.length-byteIndex) memcpy(UnsafeMutablePointer<UInt8>(buffer), lclData!.bytes+byteIndex, result) byteIndex += result return result } /// /// Fill the buffer with a byte array data /// /// - Parameter buffer: NSMutablePointer to the beginning of the array /// - Parameter length: the number of bytes in the array /// /// - Returns: /// public func fillBuffer(buffer: UnsafeMutablePointer<UInt8>, length: Int) -> Int { let result = min(length, lclData!.length-byteIndex) memcpy(buffer, lclData!.bytes+byteIndex, result) byteIndex += result return result } /// /// Fill the buffer with data /// /// - Parameter data: NSMutableData you want in the buffer /// /// - Returns: /// public func fillData(data: NSMutableData) -> Int { let result = lclData!.length-byteIndex data.appendBytes(lclData!.bytes+byteIndex, length: result) byteIndex += result return result } /// /// Resets the buffer to zero length and the beginning position /// public func reset() { lclData!.length = 0 byteIndex = 0 } /// /// Sets the buffer back to the beginning position /// public func rewind() { byteIndex = 0 } }
apache-2.0
d17534de08106e92053fcd122a660834
23.152318
85
0.585413
4.513614
false
false
false
false
weikz/Mr-Ride-iOS
Mr-Ride-iOS/BikeModel.swift
1
668
// // BikeModel.swift // Mr-Ride-iOS // // Created by 張瑋康 on 2016/6/13. // Copyright © 2016年 Appworks School Weikz. All rights reserved. // import Foundation import CoreLocation class BikeModel { let identifier: String let coordinate: CLLocationCoordinate2D let name: String let location: String let district: String init(identifier: String, coordinate: CLLocationCoordinate2D, name: String, location: String, district: String){ self.identifier = identifier self.coordinate = coordinate self.name = name self.location = location self.district = district } }
mit
5326db767af32a2c54cbcb1dbdd5d788
21.758621
115
0.657056
4.197452
false
false
false
false
ar9jun/Time-for-Cookies
Time for Cookies/Cookies/Reminder+Cookies.swift
1
9220
// // Reminder+Cookies.swift // Time for Cookies // // Created by Arjun Srivastava on 6/11/15. // Copyright (c) 2015 Arjun Srivastava. All rights reserved. // import Foundation import UIKit //MARK: - private struct Time{ var hour: Int var minute: Int var second: Int var error: String? } //MARK: - extension NSDate{ var time: String { if self.hour <= 12{ return "\(self.hour):\(self.minute):\(self.second)am" } else{ return "\(self.hour):\(self.minute):\(self.second)pm" } } } //MARK: - private extension Int{ func weekdayValue()->String{ switch self{ case 1: return "Sunday" case 2: return "Monday" case 3: return "Tuesday" case 4: return "Wednesday" case 5: return "Thursday" case 6: return "Friday" case 7: return "Saturday" default: return "err" } } } //MARK: - extension String{ //MARK: -Public func length() -> Int { return (self as NSString).length } func removeFromEnd(count:Int) -> String{ let stringLength = self.length() let substringIndex = (stringLength < count) ? 0 : stringLength - count return self.substringToIndex(advance(self.startIndex, substringIndex)) } //MARK: -Private private func monthValue() -> Int{ return self.toInt()! } private func dayValue() -> Int{ return self.toInt()! } private func yearValue()->Int{ if self.length() == 4{ //2015 return self.toInt()! } else{ //15 return (2000+self.toInt()!) } } private func weekdayValue() -> Int{ switch self.capitalizedString{ case "Sunday": return 1 case "Monday": return 2 case "Tuesday": return 3 case "Wednesday": return 4 case "Thursday": return 5 case "Friday": return 6 case "Saturday": return 7 default: return 0 } } private func timeValue()->Time{ //Get am or pm from last two characters of string var meridiem = self.substringFromIndex(self.endIndex.predecessor().predecessor()) //Remove am or pm from string var timeOnly = self.removeFromEnd(meridiem.length()) //Split string by ':' to get hour, min and sec var splitTimeString = split(timeOnly){$0 == ":"} //Ex. 12:14:54 = [12, 14, 54] if var hour = splitTimeString[0].toInt(){ if var minute = splitTimeString[1].toInt(){ if meridiem.lowercaseString == "am"{ if splitTimeString.count < 3{ //Seconds not included in string return Time(hour: hour, minute: minute, second: 0, error: nil) } else if splitTimeString.count == 3{ //Seconds included in string if var second = splitTimeString[2].toInt(){ return Time(hour: hour, minute: minute, second: second, error: nil) } } } else if meridiem.lowercaseString == "pm"{ //Add 12 to hour - to conform to 24-hour format time if splitTimeString.count < 3{ return Time(hour: hour+12, minute: minute, second: 0, error: nil) } else if splitTimeString.count == 3{ if var second = splitTimeString[2].toInt(){ return Time(hour: hour+12, minute: minute, second: second, error: nil) } } } } } //Shouldn't reach here if there aren't any errors return Time(hour: -1, minute: -1, second: -1, error: "Not in correct format. Correct Format = 12:00:00pm") } } //MARK: - class Reminder{ //MARK: - Local Notifications //MARK: -Repeat Yearly func createYearlyLocalNotification(alertBody: String, alertAction: String, year: Int = NSDate().year, month: Int = NSDate().month, day: Int = NSDate().day, atTime: String = "12:00:00pm") -> Bool{ //Repeat yearly local notification return setLocalNotification(alertBody, alertAction: alertAction, repeatInterval: .CalendarUnitWeekday, onYear: year, onMonth: month, onDay: day, atTime: atTime) } //MARK: -Repeat Monthly func createMonthlyLocalNotification(alertBody: String, alertAction: String, year: Int = NSDate().year, month: Int = NSDate().month, day: Int = NSDate().day, atTime: String = "12:00:00pm") -> Bool{ //Repeat monthly local notification return setLocalNotification(alertBody, alertAction: alertAction, repeatInterval: .CalendarUnitWeekday, onYear: year, onMonth: month, onDay: day, atTime: atTime) } //MARK: -Repeat Weekly func createWeeklyLocalNotification(alertBody: String, alertAction: String, onWeekday: String = "Sunday", atTime: String = "12:00:00pm") -> Bool{ //Repeat weekly local notification return setLocalNotification(alertBody, alertAction: alertAction, repeatInterval: .CalendarUnitWeekday, onWeekday: onWeekday, atTime: atTime) } //MARK: -Repeat Daily func createDailyLocalNotification(alertBody: String, alertAction: String, year: Int = NSDate().year, month: Int = NSDate().month, day: Int = NSDate().day, atTime: String = "12:00:00pm") -> Bool{ //Repeat daily local notification return setLocalNotification(alertBody, alertAction: alertAction, repeatInterval: .CalendarUnitWeekday, onYear: year, onMonth: month, onDay: day, atTime: atTime) } //MARK: -One Time With NSDate func createLocalNotification(alertBody: String, alertAction: String, date withDate: NSDate = NSDate()) -> Bool{ //One time local notification return setLocalNotification(alertBody, alertAction: alertAction, onYear: withDate.year, onMonth: withDate.month, onDay: withDate.day, onWeekday: withDate.weekday.weekdayValue(), atTime: withDate.time) } //MARK: -One Time With Date String func createLocalNotification(alertBody: String, alertAction: String, repeatInterval: NSCalendarUnit? = nil, onYear: Int = NSDate().year, onMonth: Int = NSDate().month, onDay: Int = NSDate().day, onWeekday: String = NSDate().weekday.weekdayValue(), atTime: String = NSDate().time) -> Bool{ //One time local notification return setLocalNotification(alertBody, alertAction: alertAction, onYear: onYear, onMonth: onMonth, onDay: onDay, onWeekday: onWeekday, atTime: atTime) } //MARK: - Private //MARK: -Create Local Notification private func setLocalNotification(alertBody: String, alertAction: String, repeatInterval: NSCalendarUnit? = nil, onYear: Int? = nil, onMonth: Int? = nil, onDay: Int? = nil, onWeekday: String? = nil, atTime: String) -> Bool{ //Check that user allowed notifications let currentSettings = UIApplication.sharedApplication().currentUserNotificationSettings() let required:UIUserNotificationType = UIUserNotificationType.Alert if (currentSettings.types & required) == nil { println("User did not allow notifications") return false } //Create notification var localNotification = UILocalNotification() localNotification.timeZone = NSTimeZone.defaultTimeZone() localNotification.alertBody = alertBody localNotification.alertAction = alertAction var calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! var now = NSDate() var compForFireDate = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitWeekday | .CalendarUnitDay | .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond, fromDate: now) if let weekday = onWeekday{ compForFireDate.weekday = weekday.weekdayValue() } if let year = onYear{ compForFireDate.year = year } if let month = onMonth{ compForFireDate.month = month } if let day = onDay{ compForFireDate.day = day } var time = atTime.timeValue() if time.error != nil{ println(time.error!) return false } compForFireDate.hour = atTime.timeValue().hour compForFireDate.minute = atTime.timeValue().minute compForFireDate.second = atTime.timeValue().second localNotification.fireDate = compForFireDate.date if let interval = repeatInterval{ localNotification.repeatInterval = interval } //Schedule notification UIApplication.sharedApplication().scheduleLocalNotification(localNotification) println("Created notification!") return true } }
mit
44c6a618f81ffdd8d16222ce8163ecec
36.48374
292
0.595987
4.74036
false
false
false
false
Sticky-Gerbil/furry-adventure
FurryAdventure/Controller/CartVC.swift
1
2658
// // CartVC.swift // FurryAdventure // // Created by Sang Saephan on 3/20/17. // Copyright © 2017 Sticky Gerbils. All rights reserved. // import UIKit class CartVC: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cart.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CartViewCell", for: indexPath) cell.textLabel?.text = cart[indexPath.row].capitalized return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { // Deletes an item from the cart if editingStyle == .delete { cart.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .automatic) } } @IBAction func onFindRecipesPressed(_ sender: Any) { UserDefaults.standard.set(false, forKey: "nutSwitchState") UserDefaults.standard.set(false, forKey: "peanutSwitchState") UserDefaults.standard.set(false, forKey: "fishSwitchState") UserDefaults.standard.set(false, forKey: "shellfishSwitchState") UserDefaults.standard.set(false, forKey: "wheatSwitchState") UserDefaults.standard.set(false, forKey: "soySwitchState") UserDefaults.standard.set(false, forKey: "dairySwitchState") var ingredients = [Ingredient]() for index in 0..<cart.count { let newIngredient = Ingredient(cart[index]) ingredients.append(newIngredient) } YummlyApiClient.shared.findRecipes(by: ingredients) {recipes in let storyboard = UIStoryboard(name: "RecipeSearchView", bundle: nil) let viewController = storyboard.instantiateViewController(withIdentifier: "RecipeSearchVC") as! RecipeSearchVC viewController.recipes = recipes viewController.ingredients = ingredients EdamamApiClient.shared.findRecipes(by: ingredients, completion: { (recipes) in for recipe in recipes { viewController.recipes.append(recipe) } self.present(viewController, animated: true, completion: nil) }) } } }
apache-2.0
dc4c805860c8c7d0983249c84e4bd675
36.422535
127
0.649605
5.013208
false
false
false
false
catloafsoft/AudioKit
AudioKit/Common/Nodes/Effects/Delay/Variable Delay/AKVariableDelay.swift
1
4349
// // AKVariableDelay.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// A delay line with cubic interpolation. /// /// - parameter input: Input node to process /// - parameter time: Delay time (in seconds) that can be changed during performance. This value must not exceed the maximum delay time. /// - parameter feedback: Feedback amount. Should be a value between 0-1. /// - parameter maximumDelayTime: The maximum delay time, in seconds. /// public class AKVariableDelay: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKVariableDelayAudioUnit? internal var token: AUParameterObserverToken? private var timeParameter: AUParameter? private var feedbackParameter: AUParameter? /// Delay time (in seconds) that can be changed during performance. This value must not exceed the maximum delay time. public var time: Double = 1 { willSet(newValue) { if time != newValue { timeParameter?.setValue(Float(newValue), originator: token!) } } } /// Feedback amount. Should be a value between 0-1. public var feedback: Double = 0 { willSet(newValue) { if feedback != newValue { feedbackParameter?.setValue(Float(newValue), originator: token!) } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this delay node /// /// - parameter input: Input node to process /// - parameter time: Delay time (in seconds) that can be changed during performance. This value must not exceed the maximum delay time. /// - parameter feedback: Feedback amount. Should be a value between 0-1. /// - parameter maximumDelayTime: The maximum delay time, in seconds. /// public init( _ input: AKNode, time: Double = 1, feedback: Double = 0, maximumDelayTime: Double = 5) { self.time = time self.feedback = feedback var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x76646c61 /*'vdla'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKVariableDelayAudioUnit.self, asComponentDescription: description, name: "Local AKVariableDelay", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKVariableDelayAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } timeParameter = tree.valueForKey("time") as? AUParameter feedbackParameter = tree.valueForKey("feedback") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.timeParameter!.address { self.time = Double(value) } else if address == self.feedbackParameter!.address { self.feedback = Double(value) } } } timeParameter?.setValue(Float(time), originator: token!) feedbackParameter?.setValue(Float(feedback), originator: token!) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
c9044fc6ca40faee7bf44c821cc60cb5
33.515873
140
0.62911
5.092506
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Components/AccountPicker/Other/AccountPickerAccountProvider.swift
1
3411
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainNamespace import DIKit import PlatformKit import RxSwift import ToolKit public protocol AccountPickerAccountProviding: AnyObject { var accounts: Observable<[BlockchainAccount]> { get } } public final class AccountPickerAccountProvider: AccountPickerAccountProviding { // MARK: - Types private enum Error: LocalizedError { case loadingFailed(account: BlockchainAccount, action: AssetAction, error: String) var errorDescription: String? { switch self { case .loadingFailed(let account, let action, let error): let type = String(reflecting: account) let asset = account.currencyType.displayCode let label = account.label return "Failed to load: '\(type)' asset '\(asset)' label '\(label)' action '\(action)' error '\(error)'." } } } // MARK: - Private Properties private let action: AssetAction private let coincore: CoincoreAPI private let singleAccountsOnly: Bool private let failSequence: Bool private let errorRecorder: ErrorRecording private let app: AppProtocol // MARK: - Properties public var accounts: Observable<[BlockchainAccount]> { app.modePublisher() .flatMap { [coincore] appMode in coincore.allAccounts(filter: appMode.filter) } .map { [singleAccountsOnly] allAccountsGroup -> [BlockchainAccount] in if singleAccountsOnly { return allAccountsGroup.accounts } return [allAccountsGroup] + allAccountsGroup.accounts } .eraseError() .flatMapFilter( action: action, failSequence: failSequence, onFailure: { [action, errorRecorder] account, error in let error: Error = .loadingFailed( account: account, action: action, error: error.localizedDescription ) errorRecorder.error(error) } ) .asObservable() } // MARK: - Init /// Default initializer. /// - Parameters: /// - singleAccountsOnly: If the return should be filtered to included only `SingleAccount`s. (opposed to `AccountGroup`s) /// - coincore: A `Coincore` instance. /// - errorRecorder: An `ErrorRecording` instance. /// - action: The desired action. This account provider will only return accounts/account groups that can execute this action. /// - failSequence: A flag indicating if, in the event of a wallet erring out, the whole `accounts: Single<[BlockchainAccount]>` sequence should err or if the offending element should be filtered out. Check `flatMapFilter`. public init( singleAccountsOnly: Bool, coincore: CoincoreAPI = resolve(), errorRecorder: ErrorRecording = resolve(), action: AssetAction, failSequence: Bool, app: AppProtocol = resolve() ) { self.action = action self.coincore = coincore self.singleAccountsOnly = singleAccountsOnly self.failSequence = failSequence self.errorRecorder = errorRecorder self.app = app } }
lgpl-3.0
07fd768300c415369a95c413b55f5ec9
35.666667
229
0.612903
5.143288
false
false
false
false
hironytic/Kiretan0
Kiretan0/Model/Utility/DataStore.swift
1
11073
// // DataStore.swift // Kiretan0 // // Copyright (c) 2017 Hironori Ichimiya <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import FirebaseFirestore import RxSwift public protocol DataStore { var deletePlaceholder: Any { get } var serverTimestampPlaceholder: Any { get } func collection(_ collectionID: String) -> CollectionPath func observeDocument<E: Entity>(at documentPath: DocumentPath) -> Observable<E?> func observeCollection<E: Entity>(matches query: DataStoreQuery) -> Observable<CollectionChange<E>> func write(block: @escaping (DocumentWriter) throws -> Void) -> Completable } public protocol DataStoreQuery { func whereField(_ field: String, isEqualTo value: Any) -> DataStoreQuery func whereField(_ field: String, isLessThan value: Any) -> DataStoreQuery func whereField(_ field: String, isLessThanOrEqualTo value: Any) -> DataStoreQuery func whereField(_ field: String, isGreaterThan value: Any) -> DataStoreQuery func whereField(_ field: String, isGreaterThanOrEqualTo value: Any) -> DataStoreQuery func order(by field: String) -> DataStoreQuery func order(by field: String, descending: Bool) -> DataStoreQuery } public protocol CollectionPath: DataStoreQuery { var collectionID: String { get } func document() -> DocumentPath func document(_ documentID: String) -> DocumentPath } public protocol DocumentPath { var documentID: String { get } func collection(_ collectionID: String) -> CollectionPath } public protocol DocumentWriter { func setDocumentData(_ documentData: [String: Any], at documentPath: DocumentPath) func updateDocumentData(_ documentData: [String: Any], at documentPath: DocumentPath) func mergeDocumentData(_ documentData: [String: Any], at documentPath: DocumentPath) func deleteDocument(at documentPath: DocumentPath) } public protocol DataStoreResolver { func resolveDataStore() -> DataStore } extension DefaultResolver: DataStoreResolver { public func resolveDataStore() -> DataStore { return DefaultDataStore(resolver: self) } } public class DefaultDataStore: DataStore { public typealias Resolver = NullResolver private let _resolver: Resolver public init(resolver: Resolver) { _resolver = resolver } public var deletePlaceholder: Any { return FieldValue.delete() } public var serverTimestampPlaceholder: Any { return FieldValue.serverTimestamp() } public func collection(_ collectionID: String) -> CollectionPath { return DefaultCollectionPath(Firestore.firestore().collection(collectionID)) } public func observeDocument<E: Entity>(at documentPath: DocumentPath) -> Observable<E?> { return Observable.create { observer in let listener = (documentPath as! DefaultDocumentPath).documentRef.addSnapshotListener { (documentSnapshot, error) in if let error = error { observer.onError(error) } else { let dSnapshot = documentSnapshot! if dSnapshot.exists { do { let entity = try E.init(raw: RawEntity(documentID: dSnapshot.documentID, data: dSnapshot.data()!)) observer.onNext(entity) } catch let error { observer.onError(error) } } else { observer.onNext(nil) } } } return Disposables.create { listener.remove() } } } public func observeCollection<E: Entity>(matches query: DataStoreQuery) -> Observable<CollectionChange<E>> { return Observable.create { observer in let listener = (query as! DefaultDataStoreQuery).query.addSnapshotListener{ (querySnapshot, error) in if let error = error { observer.onError(error) } else { do { let qSnapshot = querySnapshot! var generatedEntities = [String: E]() let entity: (DocumentSnapshot) throws -> E = { doc in let docID = doc.documentID if let result = generatedEntities[docID] { return result } else { let result = try E.init(raw: RawEntity(documentID: docID, data: doc.data()!)) generatedEntities[docID] = result return result } } let result = try qSnapshot.documents.map(entity) let events = try qSnapshot.documentChanges.map { change -> CollectionEvent<E> in switch change.type { case .added: return .inserted(Int(change.newIndex), try entity(change.document)) case .modified: return .moved(Int(change.oldIndex), Int(change.newIndex), try entity(change.document)) case .removed: return .deleted(Int(change.oldIndex)) } } observer.onNext(CollectionChange(result: result, events: events)) } catch let error { observer.onError(error) } } } return Disposables.create { listener.remove() } } } public func write(block: @escaping (DocumentWriter) throws -> Void) -> Completable { return Completable.create { observer in let batch = Firestore.firestore().batch() let writer = DefaultDocumentWriter(batch) do { try block(writer) } catch let error { observer(.error(error)) } batch.commit { error in if let error = error { observer(.error(error)) } else { observer(.completed) } } return Disposables.create() } } } private class DefaultDataStoreQuery: DataStoreQuery { public let query: Query public init(_ query: Query) { self.query = query } public func whereField(_ field: String, isEqualTo value: Any) -> DataStoreQuery { return DefaultDataStoreQuery(query.whereField(field, isEqualTo: value)) } public func whereField(_ field: String, isLessThan value: Any) -> DataStoreQuery { return DefaultDataStoreQuery(query.whereField(field, isLessThan: value)) } public func whereField(_ field: String, isLessThanOrEqualTo value: Any) -> DataStoreQuery { return DefaultDataStoreQuery(query.whereField(field, isLessThanOrEqualTo: value)) } public func whereField(_ field: String, isGreaterThan value: Any) -> DataStoreQuery { return DefaultDataStoreQuery(query.whereField(field, isGreaterThan: value)) } public func whereField(_ field: String, isGreaterThanOrEqualTo value: Any) -> DataStoreQuery { return DefaultDataStoreQuery(query.whereField(field, isGreaterThanOrEqualTo: value)) } public func order(by field: String) -> DataStoreQuery { return DefaultDataStoreQuery(query.order(by: field)) } public func order(by field: String, descending: Bool) -> DataStoreQuery { return DefaultDataStoreQuery(query.order(by: field, descending: descending)) } } private class DefaultCollectionPath: DefaultDataStoreQuery, CollectionPath { public var collectionRef: CollectionReference { return query as! CollectionReference } public init(_ collectionRef: CollectionReference) { super.init(collectionRef) } public var collectionID: String { return collectionRef.collectionID } public func document() -> DocumentPath { return DefaultDocumentPath(collectionRef.document()) } func document(_ documentID: String) -> DocumentPath { return DefaultDocumentPath(collectionRef.document(documentID)) } } private class DefaultDocumentPath: DocumentPath { public let documentRef: DocumentReference public init(_ documentRef: DocumentReference) { self.documentRef = documentRef } public var documentID: String { return documentRef.documentID } func collection(_ collectionID: String) -> CollectionPath { return DefaultCollectionPath(documentRef.collection(collectionID)) } } private class DefaultDocumentWriter: DocumentWriter { public let writeBatch: WriteBatch public init(_ writeBatch: WriteBatch) { self.writeBatch = writeBatch } public func setDocumentData(_ documentData: [String: Any], at documentPath: DocumentPath) { writeBatch.setData(documentData, forDocument: (documentPath as! DefaultDocumentPath).documentRef) } public func updateDocumentData(_ documentData: [String: Any], at documentPath: DocumentPath) { writeBatch.updateData(documentData, forDocument: (documentPath as! DefaultDocumentPath).documentRef) } public func mergeDocumentData(_ documentData: [String: Any], at documentPath: DocumentPath) { writeBatch.setData(documentData, forDocument: (documentPath as! DefaultDocumentPath).documentRef, options: SetOptions.merge()) } public func deleteDocument(at documentPath: DocumentPath) { writeBatch.deleteDocument((documentPath as! DefaultDocumentPath).documentRef) } }
mit
3708b882e2e98ac3c669489601a960da
37.581882
134
0.623499
5.112188
false
false
false
false
overtake/TelegramSwift
packages/TGUIKit/Sources/ShimmerLayer.swift
1
25905
// // File.swift // // // Created by Mike Renoir on 08.07.2022. // import Foundation import Cocoa import SwiftSignalKit private struct Shimmerkey : Hashable { var backroundColor: NSColor var foregroundColor: NSColor func hash(into hasher: inout Hasher) { hasher.combine(backroundColor.hexString) hasher.combine(foregroundColor.hexString) } } private var cached:[Shimmerkey: CGImage] = [:] private final class ShimmerEffectForegroundLayer: SimpleLayer { private var currentBackgroundColor: NSColor? private var currentForegroundColor: NSColor? private let imageViewContainer: SimpleLayer private let imageView: SimpleLayer private var absoluteLocation: (CGRect, CGSize)? private var shouldBeAnimating = false override init() { self.imageViewContainer = SimpleLayer() self.imageView = SimpleLayer() super.init() self.imageViewContainer.addSublayer(self.imageView) self.addSublayer(self.imageViewContainer) self.didExitHierarchy = { [weak self] in self?.updateAnimation() } self.didEnterHierarchy = { [weak self] in self?.updateAnimation() } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(backgroundColor: NSColor, foregroundColor: NSColor) { if let currentBackgroundColor = self.currentBackgroundColor, currentBackgroundColor.isEqual(backgroundColor), let currentForegroundColor = self.currentForegroundColor, currentForegroundColor.isEqual(foregroundColor) { return } self.currentBackgroundColor = backgroundColor self.currentForegroundColor = foregroundColor let key = Shimmerkey(backroundColor: backgroundColor, foregroundColor: foregroundColor) let image: CGImage? if let cachedImage = cached[key] { image = cachedImage } else { image = generateImage(CGSize(width: 320.0, height: 16.0), opaque: false, scale: 1.0, rotatedContext: { size, context in context.clear(CGRect(origin: CGPoint(), size: size)) context.setFillColor(backgroundColor.cgColor) context.fill(CGRect(origin: CGPoint(), size: size)) context.clip(to: CGRect(origin: CGPoint(), size: size)) let transparentColor = foregroundColor.withAlphaComponent(0.0).cgColor let peakColor = foregroundColor.cgColor var locations: [CGFloat] = [0.0, 0.5, 1.0] let colors: [CGColor] = [transparentColor, peakColor, transparentColor] // let colorSpace = CGColorSpaceCreateDeviceRGB() let gradient = CGGradient(colorsSpace: DeviceGraphicsContextSettings.shared.colorSpace, colors: colors as CFArray, locations: &locations)! context.drawLinearGradient(gradient, start: CGPoint(x: 0.0, y: 0.0), end: CGPoint(x: size.width, y: 0.0), options: CGGradientDrawingOptions()) }) cached[key] = image } self.imageView.contents = image } func updateAbsoluteRect(_ rect: CGRect, within containerSize: CGSize) { if let absoluteLocation = self.absoluteLocation, absoluteLocation.0 == rect && absoluteLocation.1 == containerSize { return } let sizeUpdated = self.absoluteLocation?.1 != containerSize let frameUpdated = self.absoluteLocation?.0 != rect self.absoluteLocation = (rect, containerSize) if sizeUpdated { if self.shouldBeAnimating { self.imageView.removeAnimation(forKey: "shimmer") self.addImageAnimation() } else { self.updateAnimation() } } if frameUpdated { self.imageViewContainer.frame = CGRect(origin: CGPoint(x: -rect.minX, y: -rect.minY), size: containerSize) } } private func updateAnimation() { let shouldBeAnimating = self.absoluteLocation != nil if shouldBeAnimating != self.shouldBeAnimating { self.shouldBeAnimating = shouldBeAnimating if shouldBeAnimating { self.addImageAnimation() } else { self.imageView.removeAnimation(forKey: "shimmer") } } } private func addImageAnimation() { guard let containerSize = self.absoluteLocation?.1 else { return } let gradientHeight: CGFloat = 320.0 self.imageView.frame = CGRect(origin: CGPoint(x: -gradientHeight, y: 0.0), size: CGSize(width: gradientHeight, height: containerSize.height)) let animation = self.imageView.makeAnimation(from: 0.0 as NSNumber, to: (containerSize.width + gradientHeight) as NSNumber, keyPath: "position.x", timingFunction: .easeOut, duration: 1.3 * 1.0, delay: 0.0, mediaTimingFunction: nil, removeOnCompletion: true, additive: true) animation.repeatCount = Float.infinity animation.beginTime = 1.0 self.imageView.add(animation, forKey: "shimmer") } } private let decodingMap: [String] = ["A", "A", "C", "A", "A", "A", "A", "H", "A", "A", "A", "L", "M", "A", "A", "A", "Q", "A", "S", "T", "A", "V", "A", "A", "A", "Z", "a", "a", "c", "a", "a", "a", "a", "h", "a", "a", "a", "l", "m", "a", "a", "a", "q", "a", "s", "t", "a", "v", "a", ".", "a", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", ","] private func decodeStickerThumbnailData(_ data: Data) -> String { var string = "M" data.forEach { byte in if byte >= 128 + 64 { string.append(decodingMap[Int(byte) - 128 - 64]) } else { if byte >= 128 { string.append(",") } else if byte >= 64 { string.append("-") } string.append("\(byte & 63)") } } string.append("z") return string } public class ShimmerLayer: SimpleLayer { private let backgroundView: SimpleLayer private let effectView: ShimmerEffectForegroundLayer private let foregroundView: SimpleLayer private var maskView: SimpleLayer? private var currentData: Data? private var currentBackgroundColor: NSColor? private var currentForegroundColor: NSColor? private var currentShimmeringColor: NSColor? private var currentSize = CGSize() public override init() { self.backgroundView = SimpleLayer() self.effectView = ShimmerEffectForegroundLayer() self.foregroundView = SimpleLayer() super.init() self.addSublayer(self.backgroundView) self.addSublayer(self.effectView) self.addSublayer(self.foregroundView) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required override init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } public func updateAbsoluteRect(_ rect: CGRect, within containerSize: CGSize) { self.effectView.updateAbsoluteRect(rect, within: containerSize) } public func update(backgroundColor: NSColor?, foregroundColor: NSColor = NSColor(rgb: 0x748391, alpha: 0.2), shimmeringColor: NSColor = NSColor(rgb: 0x748391, alpha: 0.35), data: Data?, size: CGSize, imageSize: NSSize, cornerRadius: CGFloat? = nil) { if self.currentData == data, let currentBackgroundColor = self.currentBackgroundColor, currentBackgroundColor.isEqual(backgroundColor), let currentForegroundColor = self.currentForegroundColor, currentForegroundColor.isEqual(foregroundColor), let currentShimmeringColor = self.currentShimmeringColor, currentShimmeringColor.isEqual(shimmeringColor), self.currentSize == size { return } self.currentBackgroundColor = backgroundColor self.currentForegroundColor = foregroundColor self.currentShimmeringColor = shimmeringColor self.currentData = data self.currentSize = size self.backgroundView.backgroundColor = foregroundColor.cgColor self.effectView.update(backgroundColor: backgroundColor == nil ? .clear : foregroundColor, foregroundColor: shimmeringColor) let signal: Signal<CGImage?, NoError> = Signal { subscriber in let image = generateImage(size, rotatedContext: { size, context in if let backgroundColor = backgroundColor { context.setFillColor(backgroundColor.cgColor) context.setBlendMode(.copy) context.fill(CGRect(origin: CGPoint(), size: size)) context.setFillColor(NSColor.clear.cgColor) } else { context.clear(CGRect(origin: CGPoint(), size: size)) context.setFillColor(NSColor.black.cgColor) } if let data = data { var path = decodeStickerThumbnailData(data) if !path.hasPrefix("z") { path = "\(path)z" } let reader = PathDataReader(input: path) let segments = reader.read() let scale = max(size.width, size.height) / max(imageSize.width, imageSize.height) context.scaleBy(x: scale, y: scale) renderPath(segments, context: context) } else { let path = CGMutablePath() if let cornerRadius = cornerRadius { path.addRoundedRect(in: CGRect(origin: CGPoint(), size: size), cornerWidth: cornerRadius, cornerHeight: cornerRadius) } else { path.addRoundedRect(in: CGRect(origin: CGPoint(), size: size), cornerWidth: min(min(4, size.height / 2), size.width / 2), cornerHeight: min(min(size.height / 2, 4), size.height / 2)) } context.addPath(path) context.fillPath() } }) subscriber.putNext(image) subscriber.putCompletion() return EmptyDisposable } |> runOn(Queue.concurrentDefaultQueue()) |> deliverOnMainQueue if backgroundColor == nil { self.foregroundView.contents = nil let maskView: SimpleLayer if let current = self.maskView { maskView = current } else { maskView = SimpleLayer() maskView.frame = CGRect(origin: CGPoint(), size: size) self.maskView = maskView self.mask = maskView } _ = signal.start(next: { [weak self] image in self?.maskView?.contents = image }) } else { _ = signal.start(next: { [weak self] image in self?.foregroundView.contents = image self?.maskView?.contents = image }) if let _ = self.maskView { self.mask = nil self.maskView = nil } } self.backgroundView.frame = CGRect(origin: CGPoint(), size: size) self.foregroundView.frame = CGRect(origin: CGPoint(), size: size) self.effectView.frame = CGRect(origin: CGPoint(), size: size) } } open class PathSegment: Equatable { public enum SegmentType { case M case L case C case Q case A case z case H case V case S case T case m case l case c case q case a case h case v case s case t case E case e } public let type: SegmentType public let data: [Double] public init(type: PathSegment.SegmentType = .M, data: [Double] = []) { self.type = type self.data = data } open func isAbsolute() -> Bool { switch type { case .M, .L, .H, .V, .C, .S, .Q, .T, .A, .E: return true default: return false } } public static func == (lhs: PathSegment, rhs: PathSegment) -> Bool { return lhs.type == rhs.type && lhs.data == rhs.data } } private func renderPath(_ segments: [PathSegment], context: CGContext) { var currentPoint: CGPoint? var cubicPoint: CGPoint? var quadrPoint: CGPoint? var initialPoint: CGPoint? func M(_ x: Double, y: Double) { let point = CGPoint(x: CGFloat(x), y: CGFloat(y)) context.move(to: point) setInitPoint(point) } func m(_ x: Double, y: Double) { if let cur = currentPoint { let next = CGPoint(x: CGFloat(x) + cur.x, y: CGFloat(y) + cur.y) context.move(to: next) setInitPoint(next) } else { M(x, y: y) } } func L(_ x: Double, y: Double) { lineTo(CGPoint(x: CGFloat(x), y: CGFloat(y))) } func l(_ x: Double, y: Double) { if let cur = currentPoint { lineTo(CGPoint(x: CGFloat(x) + cur.x, y: CGFloat(y) + cur.y)) } else { L(x, y: y) } } func H(_ x: Double) { if let cur = currentPoint { lineTo(CGPoint(x: CGFloat(x), y: CGFloat(cur.y))) } } func h(_ x: Double) { if let cur = currentPoint { lineTo(CGPoint(x: CGFloat(x) + cur.x, y: CGFloat(cur.y))) } } func V(_ y: Double) { if let cur = currentPoint { lineTo(CGPoint(x: CGFloat(cur.x), y: CGFloat(y))) } } func v(_ y: Double) { if let cur = currentPoint { lineTo(CGPoint(x: CGFloat(cur.x), y: CGFloat(y) + cur.y)) } } func lineTo(_ p: CGPoint) { context.addLine(to: p) setPoint(p) } func c(_ x1: Double, y1: Double, x2: Double, y2: Double, x: Double, y: Double) { if let cur = currentPoint { let endPoint = CGPoint(x: CGFloat(x) + cur.x, y: CGFloat(y) + cur.y) let controlPoint1 = CGPoint(x: CGFloat(x1) + cur.x, y: CGFloat(y1) + cur.y) let controlPoint2 = CGPoint(x: CGFloat(x2) + cur.x, y: CGFloat(y2) + cur.y) context.addCurve(to: endPoint, control1: controlPoint1, control2: controlPoint2) setCubicPoint(endPoint, cubic: controlPoint2) } } func C(_ x1: Double, y1: Double, x2: Double, y2: Double, x: Double, y: Double) { let endPoint = CGPoint(x: CGFloat(x), y: CGFloat(y)) let controlPoint1 = CGPoint(x: CGFloat(x1), y: CGFloat(y1)) let controlPoint2 = CGPoint(x: CGFloat(x2), y: CGFloat(y2)) context.addCurve(to: endPoint, control1: controlPoint1, control2: controlPoint2) setCubicPoint(endPoint, cubic: controlPoint2) } func s(_ x2: Double, y2: Double, x: Double, y: Double) { if let cur = currentPoint { let nextCubic = CGPoint(x: CGFloat(x2) + cur.x, y: CGFloat(y2) + cur.y) let next = CGPoint(x: CGFloat(x) + cur.x, y: CGFloat(y) + cur.y) let xy1: CGPoint if let curCubicVal = cubicPoint { xy1 = CGPoint(x: CGFloat(2 * cur.x) - curCubicVal.x, y: CGFloat(2 * cur.y) - curCubicVal.y) } else { xy1 = cur } context.addCurve(to: next, control1: xy1, control2: nextCubic) setCubicPoint(next, cubic: nextCubic) } } func S(_ x2: Double, y2: Double, x: Double, y: Double) { if let cur = currentPoint { let nextCubic = CGPoint(x: CGFloat(x2), y: CGFloat(y2)) let next = CGPoint(x: CGFloat(x), y: CGFloat(y)) let xy1: CGPoint if let curCubicVal = cubicPoint { xy1 = CGPoint(x: CGFloat(2 * cur.x) - curCubicVal.x, y: CGFloat(2 * cur.y) - curCubicVal.y) } else { xy1 = cur } context.addCurve(to: next, control1: xy1, control2: nextCubic) setCubicPoint(next, cubic: nextCubic) } } func z() { context.fillPath() } func setQuadrPoint(_ p: CGPoint, quadr: CGPoint) { currentPoint = p quadrPoint = quadr cubicPoint = nil } func setCubicPoint(_ p: CGPoint, cubic: CGPoint) { currentPoint = p cubicPoint = cubic quadrPoint = nil } func setInitPoint(_ p: CGPoint) { setPoint(p) initialPoint = p } func setPoint(_ p: CGPoint) { currentPoint = p cubicPoint = nil quadrPoint = nil } for segment in segments { var data = segment.data switch segment.type { case .M: M(data[0], y: data[1]) data.removeSubrange(Range(uncheckedBounds: (lower: 0, upper: 2))) while data.count >= 2 { L(data[0], y: data[1]) data.removeSubrange((0 ..< 2)) } case .m: m(data[0], y: data[1]) data.removeSubrange((0 ..< 2)) while data.count >= 2 { l(data[0], y: data[1]) data.removeSubrange((0 ..< 2)) } case .L: while data.count >= 2 { L(data[0], y: data[1]) data.removeSubrange((0 ..< 2)) } case .l: while data.count >= 2 { l(data[0], y: data[1]) data.removeSubrange((0 ..< 2)) } case .H: H(data[0]) case .h: h(data[0]) case .V: V(data[0]) case .v: v(data[0]) case .C: while data.count >= 6 { C(data[0], y1: data[1], x2: data[2], y2: data[3], x: data[4], y: data[5]) data.removeSubrange((0 ..< 6)) } case .c: while data.count >= 6 { c(data[0], y1: data[1], x2: data[2], y2: data[3], x: data[4], y: data[5]) data.removeSubrange((0 ..< 6)) } case .S: while data.count >= 4 { S(data[0], y2: data[1], x: data[2], y: data[3]) data.removeSubrange((0 ..< 4)) } case .s: while data.count >= 4 { s(data[0], y2: data[1], x: data[2], y: data[3]) data.removeSubrange((0 ..< 4)) } case .z: z() default: print("unknown") break } } } private class PathDataReader { private let input: String private var current: UnicodeScalar? private var previous: UnicodeScalar? private var iterator: String.UnicodeScalarView.Iterator private static let spaces: Set<UnicodeScalar> = Set("\n\r\t ,".unicodeScalars) init(input: String) { self.input = input self.iterator = input.unicodeScalars.makeIterator() } public func read() -> [PathSegment] { readNext() var segments = [PathSegment]() while let array = readSegments() { segments.append(contentsOf: array) } return segments } private func readSegments() -> [PathSegment]? { if let type = readSegmentType() { let argCount = getArgCount(segment: type) if argCount == 0 { return [PathSegment(type: type)] } var result = [PathSegment]() let data: [Double] if type == .a || type == .A { data = readDataOfASegment() } else { data = readData() } var index = 0 var isFirstSegment = true while index < data.count { let end = index + argCount if end > data.count { break } var currentType = type if type == .M && !isFirstSegment { currentType = .L } if type == .m && !isFirstSegment { currentType = .l } result.append(PathSegment(type: currentType, data: Array(data[index..<end]))) isFirstSegment = false index = end } return result } return nil } private func readData() -> [Double] { var data = [Double]() while true { skipSpaces() if let value = readNum() { data.append(value) } else { return data } } } private func readDataOfASegment() -> [Double] { let argCount = getArgCount(segment: .A) var data: [Double] = [] var index = 0 while true { skipSpaces() let value: Double? let indexMod = index % argCount if indexMod == 3 || indexMod == 4 { value = readFlag() } else { value = readNum() } guard let doubleValue = value else { return data } data.append(doubleValue) index += 1 } return data } private func skipSpaces() { var currentCharacter = current while let character = currentCharacter, Self.spaces.contains(character) { currentCharacter = readNext() } } private func readFlag() -> Double? { guard let ch = current else { return .none } readNext() switch ch { case "0": return 0 case "1": return 1 default: return .none } } fileprivate func readNum() -> Double? { guard let ch = current else { return .none } guard ch >= "0" && ch <= "9" || ch == "." || ch == "-" else { return .none } var chars = [ch] var hasDot = ch == "." while let ch = readDigit(&hasDot) { chars.append(ch) } var buf = "" buf.unicodeScalars.append(contentsOf: chars) guard let value = Double(buf) else { return .none } return value } fileprivate func readDigit(_ hasDot: inout Bool) -> UnicodeScalar? { if let ch = readNext() { if (ch >= "0" && ch <= "9") || ch == "e" || (previous == "e" && ch == "-") { return ch } else if ch == "." && !hasDot { hasDot = true return ch } } return nil } fileprivate func isNum(ch: UnicodeScalar, hasDot: inout Bool) -> Bool { switch ch { case "0"..."9": return true case ".": if hasDot { return false } hasDot = true default: return true } return false } @discardableResult private func readNext() -> UnicodeScalar? { previous = current current = iterator.next() return current } private func isAcceptableSeparator(_ ch: UnicodeScalar?) -> Bool { if let ch = ch { return "\n\r\t ,".contains(String(ch)) } return false } private func readSegmentType() -> PathSegment.SegmentType? { while true { if let type = getPathSegmentType() { readNext() return type } if readNext() == nil { return nil } } } fileprivate func getPathSegmentType() -> PathSegment.SegmentType? { if let ch = current { switch ch { case "M": return .M case "m": return .m case "L": return .L case "l": return .l case "C": return .C case "c": return .c case "Q": return .Q case "q": return .q case "A": return .A case "a": return .a case "z", "Z": return .z case "H": return .H case "h": return .h case "V": return .V case "v": return .v case "S": return .S case "s": return .s case "T": return .T case "t": return .t default: break } } return nil } fileprivate func getArgCount(segment: PathSegment.SegmentType) -> Int { switch segment { case .H, .h, .V, .v: return 1 case .M, .m, .L, .l, .T, .t: return 2 case .S, .s, .Q, .q: return 4 case .C, .c: return 6 case .A, .a: return 7 default: return 0 } } }
gpl-2.0
daf20a02e6a9f7100e6a2106b0a6f850
31.749684
384
0.508975
4.481834
false
false
false
false
2016321/CycleScrollView
CycleScrollView/KingfisherManager/KingfisherManger.swift
1
1131
// // KingfisherManger.swift // SexyVC // // Created by 王昱斌 on 17/5/2. // Copyright © 2017年 Qtin. All rights reserved. // import Foundation import Kingfisher extension UIImageView{ func setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil){ kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } } extension UIButton{ func setImage(with resource: Resource?, state: UIControlState, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil){ kf.setImage(with: resource, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } }
apache-2.0
8896c2557c8d8722df8b11cb44bfb20a
32
159
0.645276
5.194444
false
false
false
false
xshfsky/WeiBo
WeiBo/WeiBo/Classes/Home/Controller/HomeTableViewController.swift
1
4171
// // HomeTableViewController.swift // WeiBo // // Created by Miller on 15/9/26. // Copyright © 2015年 Xie Yufeng. All rights reserved. // import UIKit class HomeTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() if isLogin == false { visiterView?.setVisterViewInfo(true, imageNamed: "visitordiscover_feed_image_house", title: "关注一些人,回这里看看有什么惊喜") return } self.navigationItem.leftBarButtonItem = UIBarButtonItem(target: self, action: Selector("leftBtnClick:"), imageNamed: "navigationbar_friendattention") self.navigationItem.rightBarButtonItem = UIBarButtonItem(target: self, action: Selector("rightBtnClick:"), imageNamed: "navigationbar_pop") let titleBtn = TitleButton(type: UIButtonType.Custom) titleBtn.setTitle("自我修养 ", forState: UIControlState.Normal) titleBtn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) titleBtn.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Normal) titleBtn.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Selected) titleBtn.addTarget(self, action: Selector("titleBtnClick:"), forControlEvents: UIControlEvents.TouchDown) titleBtn.sizeToFit() self.navigationItem.titleView = titleBtn } func titleBtnClick(btn: UIButton) { btn.selected = !btn.selected YFLog(__FUNCTION__) } func leftBtnClick(btn: UIButton) { YFLog(__FUNCTION__) } func rightBtnClick(btn: UIButton) { YFLog(__FUNCTION__) } // 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. } */ }
mit
3960d090052b41f2a15c6c82a7a5e1d8
36.527273
157
0.684109
5.278772
false
false
false
false
ecwineland/Presente
Presente/ViewController.swift
1
3282
// // ViewController.swift // Presente // // Created by Evan Wineland on 10/8/15. // Copyright © 2015 Evan Wineland. All rights reserved. // import UIKit import Parse import ParseUI class ViewController: UIViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate { var logInViewController: PFLogInViewController = PFLogInViewController() var signUpViewController: PFSignUpViewController = PFSignUpViewController() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if (PFUser.currentUser() == nil) { self.logInViewController.fields = [PFLogInFields.UsernameAndPassword, PFLogInFields.LogInButton, PFLogInFields.SignUpButton, PFLogInFields.PasswordForgotten, PFLogInFields.DismissButton] // Log In Logo let logoInTitle = UILabel() logoInTitle.text = "Presente" self.logInViewController.logInView?.logo = logoInTitle self.logInViewController.delegate = self // Sign Up Logo let signUpTitle = UILabel() signUpTitle.text = "Presente" self.signUpViewController.signUpView!.logo = signUpTitle self.signUpViewController.delegate = self self.logInViewController.signUpController = self.signUpViewController } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Parse Log In func logInViewController(logInController: PFLogInViewController, shouldBeginLogInWithUsername username: String, password: String) -> Bool { return (!username.isEmpty || !password.isEmpty) // Same as his code, right? } func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) { self.dismissViewControllerAnimated(true, completion: nil) } func logInViewController(logInController: PFLogInViewController, didFailToLogInWithError error: NSError?) { print("Failed to log in") } // MARK: Parse Sign Up func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) { self.dismissViewControllerAnimated(true, completion: nil) } func signUpViewController(signUpController: PFSignUpViewController, didFailToSignUpWithError error: NSError?) { print("Failed to sign up") } func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController) { print("User dismissed signup") } // Mark: Actions @IBAction func simpleAction(sender: AnyObject) { self.presentViewController(self.logInViewController, animated: true, completion: nil) } @IBAction func customAction(sender: AnyObject) { self.performSegueWithIdentifier("custom", sender: self) } @IBAction func logoutAction(sender: AnyObject) { PFUser.logOut() } }
mit
635d01af8870a4cc7358c9bd98a0788c
32.824742
198
0.670222
5.676471
false
false
false
false
CD1212/Doughnut
Doughnut/Library/Utils.swift
1
3262
/* * Doughnut Podcast Client * Copyright (C) 2017 Chris Dyer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation class Utils { static func formatDuration(_ seconds: Int) -> String { guard seconds > 0 else { return "" } let formatter = DateComponentsFormatter() formatter.allowedUnits = [.hour, .minute] formatter.unitsStyle = .short return formatter.string(from: TimeInterval(seconds)) ?? "" } static func iTunesFeedUrl(iTunesUrl: String, completion: @escaping (_ result: String?) -> Void) -> Bool { guard let iTunesId = Utils.iTunesPodcastId(iTunesUrl: iTunesUrl) else { return false } guard let iTunesDataUrl = URL(string: "https://itunes.apple.com/lookup?id=\(iTunesId)&entity=podcast") else { return false } let request = URLSession.shared.dataTask(with: iTunesDataUrl) { (data, response, error) in guard let data = data, error == nil else { completion(nil) return } do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any] let results = json["results"] as? [[String: Any]] ?? [] for r in results { for result in r { if result.key == "feedUrl" { completion((result.value as! String)) return } } } } catch let error { print(error) } completion(nil) } request.resume() return true } static func iTunesPodcastId(iTunesUrl: String) -> String? { let regex = try! NSRegularExpression(pattern: "\\/id(\\d+)") let matches = regex.matches(in: iTunesUrl, options: [], range: NSRange(location: 0, length: iTunesUrl.characters.count)) for match in matches as [NSTextCheckingResult] { // range at index 0: full match // range at index 1: first capture group let substring = (iTunesUrl as NSString).substring(with: match.range(at: 1)) return substring } return nil } static func dataToUtf8(_ data: Data) -> Data? { var convertedString: NSString? let encoding = NSString.stringEncoding(for: data, encodingOptions: nil, convertedString: &convertedString, usedLossyConversion: nil) if let str = NSString(data: data, encoding: encoding) as String? { return str.data(using: .utf8) } return nil } static func removeQueryString(url: URL) -> URL { let components = NSURLComponents(url: url, resolvingAgainstBaseURL: false) components?.query = nil components?.fragment = nil return components?.url ?? url } }
gpl-3.0
7cabe142206636803ea39f51b5f839cf
31.949495
136
0.647149
4.286465
false
false
false
false
WestlakeAPC/Shoot-Out
Shoot Out/Common Classes/GameEvent.swift
1
5199
// // Event.swift // Shoot Out // // Created by Eli Bradley on 8/14/17. // Copyright © 2017 Westlake APC. All rights reserved. // import Foundation import SpriteKit enum GameEvent { case characterAssignment(randomNumber: Int) case shot case died case restart case terminated case propertyUpdate(Properties) } struct Properties { // SpriteKit physics bodies var ourCharacterPhysics: CGVector var ourCharacterPosition: CGPoint var ourCharacterDirection: Direction // Arrays var playerBulletArray: [BulletInformation] = [] var enemyBulletArray: [BulletInformation] = [] } struct BulletInformation { var position: CGPoint var direction: Direction } enum Direction: String { case left case right } // MARK: NSCoding wrapper classes. class EncodableGameEvent: NSObject, NSCoding { let gameEvent: GameEvent init(_ gameEvent: GameEvent) { self.gameEvent = gameEvent } func encode(with coder: NSCoder) { switch (gameEvent) { case .characterAssignment(let randomNumber): coder.encode("character_assignment", forKey: "message_type") coder.encode(randomNumber, forKey: "random_number_value") case .shot: coder.encode("shot", forKey: "message_type") case .died: coder.encode("died", forKey: "message_type") case .restart: coder.encode("restart", forKey: "message_type") case .terminated: coder.encode("terminated", forKey: "message_type") case .propertyUpdate(let properties): coder.encode("property_update", forKey: "message_type") coder.encode(EncodableProperties(properties), forKey: "properties") } } required init?(coder: NSCoder) { switch (coder.decodeObject(forKey: "message_type") as! String) { case "character_assignment": let value = coder.decodeInteger(forKey: "random_number_value") gameEvent = .characterAssignment(randomNumber: value) case "shot": gameEvent = .shot case "died": gameEvent = .died case "restart": gameEvent = .restart case "terminated": gameEvent = .terminated case "property_update": let properties = coder.decodeObject(forKey: "properties") as! EncodableProperties gameEvent = .propertyUpdate(properties.properties) default: gameEvent = .died // I don't know why, this shouldn't happen anyways } } } class EncodableProperties: NSObject, NSCoding { let properties: Properties init(_ properties: Properties) { self.properties = properties } func encode(with coder: NSCoder) { coder.encode(properties.ourCharacterPhysics, forKey: "physics") coder.encode(properties.ourCharacterPosition, forKey: "position") coder.encode(properties.ourCharacterDirection.rawValue, forKey: "direction") let playerBulletArray = properties.playerBulletArray.map { EncodableBulletInformation($0) } let enemyBulletArray = properties.enemyBulletArray.map { EncodableBulletInformation($0) } coder.encode(playerBulletArray, forKey: "player_bullets") coder.encode(enemyBulletArray, forKey: "enemy_bullets") } required init?(coder: NSCoder) { let ourCharacterPhysics = coder.decodeCGVector(forKey: "physics") let ourCharacterPosition = coder.decodeCGPoint(forKey: "position") let ourCharacterDirection = Direction(rawValue: coder.decodeObject(forKey: "direction") as! String)! let playerBulletArray = (coder.decodeObject(forKey: "player_bullets") as! [EncodableBulletInformation]).map { $0.bulletInformation } let enemyBulletArray = (coder.decodeObject(forKey: "enemy_bullets") as! [EncodableBulletInformation]).map { $0.bulletInformation } properties = Properties(ourCharacterPhysics: ourCharacterPhysics, ourCharacterPosition: ourCharacterPosition, ourCharacterDirection: ourCharacterDirection, playerBulletArray: playerBulletArray, enemyBulletArray: enemyBulletArray) } } class EncodableBulletInformation: NSObject, NSCoding { let bulletInformation: BulletInformation init(_ bulletInformation: BulletInformation) { self.bulletInformation = bulletInformation } func encode(with coder: NSCoder) { coder.encode(bulletInformation.position, forKey: "position") coder.encode(bulletInformation.direction.rawValue, forKey: "direction") } required init?(coder: NSCoder) { let position = coder.decodeCGPoint(forKey: "position") let direction = Direction(rawValue: coder.decodeObject(forKey: "direction") as! String)! bulletInformation = BulletInformation(position: position, direction: direction) } }
apache-2.0
b79248999d59ed1fec8619468f33b423
34.848276
140
0.636976
4.830855
false
false
false
false
GRSource/GRTabBarController
Example/Controllers/GRSecond_RootViewController.swift
2
3172
// // GRSecond_RootViewController.swift // GRTabBarController // // Created by iOS_Dev5 on 2017/2/9. // Copyright © 2017年 GRSource. All rights reserved. // import UIKit class GRSecond_RootViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() self.title = "二" // 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 numberOfSections(in 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, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
724975244fac432f896ef9ab1dd2001f
32.336842
136
0.669719
5.252073
false
false
false
false
manfengjun/KYMart
Section/Cart/View/KYOrderTVCell.swift
1
1363
// // KYOrderTVCell.swift // KYMart // // Created by JUN on 2017/7/5. // Copyright © 2017年 JUN. All rights reserved. // import UIKit class KYOrderTVCell: UITableViewCell { @IBOutlet weak var productIV: UIImageView! @IBOutlet weak var productInfoL: UILabel! @IBOutlet weak var productPropertyL: UILabel! @IBOutlet weak var moneyL: UILabel! @IBOutlet weak var countL: UILabel! var model:OrderCartList? { didSet { if let text = model?.goods_name { productInfoL.text = text } if let text = model?.goods_id { let url = imageUrl(goods_id: text) productIV.sd_setImage(with: url, placeholderImage: nil) } if let text = model?.goods_price { moneyL.text = "¥\(text)" } if let text = model?.goods_num { countL.text = "X\(text)" } if let text = model?.spec_key_name { productPropertyL.text = text } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
590fb98e9af2a9ab3aef28cdf52a7d34
25.647059
71
0.552612
4.328025
false
false
false
false
mahomealex/MASQLiteWrapper
MASQLiteWrapper/ViewController.swift
1
1303
// // ViewController.swift // SQLiteWrapper // // Created by 林东鹏 on 02/05/2017. // Copyright © 2017 Alex. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. DBHelper.sharedInstance.setupDB() let model = TestModel() model.uid = "a" model.name = "name" model.age = 23 //insert or update DBHelper.operation()?.save(model: model) //save array DBHelper.operation()?.saveAll(models: [model]) //query var array = DBHelper.operation()?.queryAll(model) print(array ?? "") array = DBHelper.operation()?.queryAll(TestModel.self) print(array ?? "") //delete DBHelper.operation()?.delete(model: model) //delete by primarykey DBHelper.sharedInstance.delete(uid: "a") //query by primarykey DBHelper.sharedInstance.model(uid: "a") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
cd81b8e89725c9d14867217630f9ce47
23
80
0.571759
4.645161
false
false
false
false
tjw/swift
test/Serialization/typealias.swift
1
1134
// RUN: %empty-directory(%t) // RUN: %target-build-swift -module-name alias -emit-module -o %t %S/Inputs/alias.swift // RUN: llvm-bcanalyzer %t/alias.swiftmodule | %FileCheck %s // RUN: %target-build-swift -I %t %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck -check-prefix=OUTPUT %s // REQUIRES: executable_test // CHECK-NOT: UnknownCode import alias var i : MyInt64 i = 42 var j : AnotherInt64 = i print("\(j)\n", terminator: "") // OUTPUT: 42 var both : TwoInts both = (i, j) var named : ThreeNamedInts named.b = 64 print("\(named.b)\n", terminator: "") // OUTPUT: 64 var none : None none = () func doNothing() {} var nullFn : NullFunction = doNothing func negate(x: MyInt64) -> AnotherInt64 { return -x } var monadic : IntFunction = negate print("\(monadic(i))\n", terminator: "") // OUTPUT: -42 func subtract(x: MyInt64, y: MyInt64) -> MyInt64 { return x - y } var dyadic : TwoIntFunction = subtract print("\(dyadic((named.b, i))) \(dyadic(both))\n", terminator: "") // OUTPUT: 22 0 // Used for tests that only need to be type-checked. func check(_: BaseAlias) { } let x: GG<Int> = 0 let x2: GInt = 1
apache-2.0
be5e3b2b93e374af9622591903e800a6
19.618182
87
0.650794
2.849246
false
false
false
false
SwiftStudies/OysterKit
Sources/OysterKit/Parser/ParsingStrategy.swift
1
4704
// Copyright (c) 2016, RED When Excited // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation /** At this point this is a singleton to enforce the absence of any non-explicit state. It captures the current strategy for parsing used by all the different consumers of languages. If it turns out there is a need for multiple strategies this will be turned into a protocol, and multiple implementations can be provided. */ enum ParsingStrategy { /** Encapsulates all of the state associated with a parsing operation meaning that the two supplied static functions do not require any storage and are inherently thread safe. This is desireable as concurrent evaluation of rules is a generic goal of this project */ class ParsingContext { let lexer : LexicalAnalyzer let ir : IntermediateRepresentation let grammar : Grammar var complete = false init(lexer:LexicalAnalyzer, ir:IntermediateRepresentation, grammar:Grammar){ self.lexer = lexer self.grammar = grammar self.ir = ir } } static func parse(_ source : String, using grammar:Grammar, with lexerType:LexicalAnalyzer.Type = Lexer.self, into ir:IntermediateRepresentation) throws { let context = ParsingContext(lexer: lexerType.init(source: source), ir: ir, grammar: grammar) do { while !context.complete { if try !pass(in: context) { throw ProcessingError.interpretation(message: "Failure reported in pass(), but no error was thrown", causes: []) } } } } static func pass(`in` context :ParsingContext) throws -> Bool{ if context.complete { return false } var productionErrors = [Error]() var success = false if !context.lexer.endOfInput { let positionBeforeParsing = context.lexer.index for rule in context.grammar.rules { do { try rule.match(with: context.lexer, for: context.ir) success = true productionErrors.removeAll() break } catch let error as CausalErrorType where error.isFatal { throw error } catch { productionErrors.append(error) } } if !productionErrors.isEmpty { throw ProcessingError.parsing(message: "No rules matched input", range: productionErrors.range ?? context.lexer.index...context.lexer.index, causes: productionErrors) } if context.lexer.index == positionBeforeParsing { throw ProcessingError.scanning(message: "Lexer not advanced", position: context.lexer.index, causes: []) } if context.lexer.endOfInput { context.complete = true } return success } else { throw ProcessingError.scanning(message: "Unexpected end of input", position: context.lexer.source.unicodeScalars.endIndex, causes: []) } } }
bsd-2-clause
9c77fc9f6210062575b83292d13edf4a
42.962617
182
0.623087
5.226667
false
false
false
false
OrangeJam/iSchool
iSchool/AssignmentsTableViewController.swift
1
4352
// // AssignmentsTableViewController.swift // iSchool // // Created by Kári Helgason on 05/09/14. // Copyright (c) 2014 OrangeJam. All rights reserved. // import UIKit class AssignmentsTableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var emptyLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.tableView.rowHeight = 50 self.refreshControl = UIRefreshControl() self.refreshControl?.tintColor = UIColor.grayColor() self.refreshControl?.addTarget(self, action: "reloadData", forControlEvents: .ValueChanged ) tableView.delegate = self // Set the width of the empty label to be the width of the screen. self.emptyLabel.frame = CGRect(x: 0, y: 0, width: self.tableView.bounds.width, height: self.emptyLabel.frame.height) // Set the text of the empty label. self.emptyLabel.text = NSLocalizedString("No assignments", comment: "Text for the empty label when there are no assignments") self.emptyLabel.hidden = false } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshData", name: Notification.assignment.rawValue, object: nil ) NSNotificationCenter.defaultCenter().addObserver(self, selector: "endRefresh", name: Notification.networkError.rawValue, object: nil ) DataStore.sharedInstance.fetchAssignments() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let count = DataStore.sharedInstance.getAssignments().count self.emptyLabel.hidden = !(count == 0) return count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let assignments = DataStore.sharedInstance.getAssignments() let cell = tableView.dequeueReusableCellWithIdentifier("AssignmentsTableViewCell") as AssignmentsTableViewCell cell.setAssignment(assignments[indexPath.row]) return cell } // // Test when no assignments are due for user. // override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return 4 // } // // override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // let assignments = DataStore.sharedInstance.getAssignments() // let cell = tableView.dequeueReusableCellWithIdentifier("AssignmentsTableViewCell") as AssignmentsTableViewCell // cell.assignmentStub() // return cell // } // // Test ends override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let detail = self.storyboard?.instantiateViewControllerWithIdentifier("DetailView") as? DetailViewController { let assignments = DataStore.sharedInstance.getAssignments() let a = assignments[indexPath.row] detail.setDetailForURL(NSURL(string: a.URL)!, title: a.name) let bbItem = UIBarButtonItem(title: NSLocalizedString("Back", comment: "Back button"), style: .Plain, target: nil, action: nil) navigationItem.backBarButtonItem = bbItem navigationController?.pushViewController(detail, animated: true) } } override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { tableView.cellForRowAtIndexPath(indexPath)?.setSelected(false, animated: true) } func reloadData() { DataStore.sharedInstance.fetchAssignments() endRefresh() } func refreshData() { self.tableView.reloadData() } func endRefresh() { refreshControl?.endRefreshing() } }
bsd-3-clause
53f4b0ccd1037e363ae36b9d31658a19
38.198198
133
0.674558
5.398263
false
false
false
false
mleiv/UIHeaderTabs
UIHeaderTabsExample/UIHeaderTabsExample/UIHeaderTabs/UIHeaderTab.swift
2
1450
// // UIHeaderTab.swift // // Created by Emily Ivie on 9/10/15. // Copyright © 2015 urdnot. // Licensed under The MIT License // For full copyright and license information, please see http://opensource.org/licenses/MIT // Redistributions of files must retain the above copyright notice. import UIKit @IBDesignable public class UIHeaderTab: UIView { @IBInspectable public var title: String = "Tab" { didSet { if oldValue != title { setupTab() } } } @IBInspectable public var selected: Bool = false { didSet { if oldValue != selected { setupTab() } } } @IBInspectable public var index: Int = 0 { didSet { if oldValue != index { setupTab() } } } public var onClick: ((Int) -> Void)? @IBOutlet weak var unselectedWrapper: UIView! @IBOutlet weak var selectedWrapper: UIView! @IBOutlet weak var button: UIButton! @IBOutlet weak var label1: UILabel! @IBOutlet weak var label2: UILabel! @IBOutlet weak var selectedUnderline: UIView! @IBAction func onClick(sender: UIButton) { onClick?(index) } internal func setupTab() { label1.text = title label2.text = title unselectedWrapper.hidden = selected selectedWrapper.hidden = !selected } }
mit
fbf987891ba66a54a3622b04438248dc
23.576271
93
0.57764
4.6
false
false
false
false
roambotics/swift
SwiftCompilerSources/Sources/Optimizer/DataStructures/FunctionUses.swift
2
5339
//===--- FunctionUses.swift -----------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SIL /// Provides a list of instructions, which reference a function. /// /// A function "use" is an instruction in another (or the same) function which /// references the function. In most cases those are `function_ref` instructions, /// but can also be e.g. `keypath` instructions. /// /// 'FunctionUses' performs an analysis of all functions in the module and collects /// instructions which reference other functions. This utility can be used to do /// inter-procedural caller-analysis. /// /// In order to use `FunctionUses`, first call `collect()` and then get use-lists of /// functions with `getUses(of:)`. struct FunctionUses { // Function uses are stored in a single linked list, whereas the "next" is not a pointer // but an index into `FunctionUses.useStorage`. fileprivate struct Use { // The index of the next use in `FunctionUses.useStorage`. let next: Int? // The instruction which references the function. let usingInstruction: Instruction } // The head of the single-linked list of function uses. fileprivate struct FirstUse { // The head of the use-list. var first: Int? // True if the function has unknown uses var hasUnknownUses: Bool init(of function: Function) { self.hasUnknownUses = function.isPossiblyUsedExternally || function.isAvailableExternally } mutating func insert(_ inst: Instruction, _ uses: inout [Use]) { let newFirst = uses.count uses.append(Use(next: first, usingInstruction: inst)) first = newFirst } } /// The list of uses of a function. struct UseList : CollectionLikeSequence, CustomStringConvertible { struct Iterator : IteratorProtocol { fileprivate let useStorage: [Use] fileprivate var currentUseIdx: Int? mutating func next() -> Instruction? { if let useIdx = currentUseIdx { let use = useStorage[useIdx] currentUseIdx = use.next return use.usingInstruction } return nil } } // The "storage" for all function uses. fileprivate let useStorage: [Use] // The head of the single-linked use list. fileprivate let firstUse: FirstUse /// True if the function has unknown uses in addition to the list of referencing instructions. /// /// This is the case, e.g. if the function has public linkage or if the function /// is referenced from a vtable or witness table. var hasUnknownUses: Bool { firstUse.hasUnknownUses } func makeIterator() -> Iterator { return Iterator(useStorage: useStorage, currentUseIdx: firstUse.first) } var description: String { var result = "[\n" if hasUnknownUses { result += "<unknown uses>\n" } for inst in self { result += "@\(inst.function.name): \(inst)\n" } result += "]" return result } var customMirror: Mirror { Mirror(self, children: []) } } // The "storage" for all function uses. private var useStorage: [Use] = [] // The use-list head for each function. private var uses: [Function: FirstUse] = [:] /// Returns the use-list of `function`. /// /// Note that `collect` must be called before `getUses` can be used. func getUses(of function: Function) -> UseList { UseList(useStorage: useStorage, firstUse: uses[function, default: FirstUse(of: function)]) } /// Collects all uses of all function in the module. mutating func collect(context: ModulePassContext) { // Already start with a reasonable big capacity to reduce the number of // re-allocations when appending to the data structures. useStorage.reserveCapacity(128) uses.reserveCapacity(64) // Mark all functions, which are referenced from tables, to have "unknown" uses. for vTable in context.vTables { for entry in vTable.entries { markUnknown(entry.function) } } for witnessTable in context.witnessTables { for entry in witnessTable.entries { if entry.kind == .Method, let f = entry.methodFunction { markUnknown(f) } } } for witnessTable in context.defaultWitnessTables { for entry in witnessTable.entries { if entry.kind == .Method, let f = entry.methodFunction { markUnknown(f) } } } // Collect all instructions, which reference functions, in the module. for function in context.functions { for inst in function.instructions { inst.visitReferencedFunctions { referencedFunc in uses[referencedFunc, default: FirstUse(of: referencedFunc)].insert(inst, &useStorage) } } } } private mutating func markUnknown(_ function: Function) { uses[function, default: FirstUse(of: function)].hasUnknownUses = true } }
apache-2.0
a3f1bdfaebd860793e3f84a256bf0e24
31.554878
98
0.650684
4.419702
false
false
false
false
jshultz/swift2_ios9_json_example
json_example/ViewController.swift
1
1179
// // ViewController.swift // json_example // // Created by Jason Shultz on 11/9/15. // Copyright © 2015 HashRocket. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let url = NSURL(string: "http://www.telize.com/geoip")! let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in if let urlContent = data { do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers) let country = jsonResult["country"]! as! NSString print(country) } catch { print("JSON serialization failed") } } } task.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
da7e745bb5bd9e25ace9c2a6f22c4613
26.395349
140
0.56961
5.354545
false
false
false
false
IngmarStein/swift
test/ClangModules/availability_implicit_macosx.swift
4
4394
// RUN: %swift -parse -verify -target x86_64-apple-macosx10.51 %clang-importer-sdk -I %S/Inputs/custom-modules %s %S/Inputs/availability_implicit_macosx_other.swift // RUN: not %swift -parse -target x86_64-apple-macosx10.51 %clang-importer-sdk -I %S/Inputs/custom-modules %s %S/Inputs/availability_implicit_macosx_other.swift 2>&1 | %FileCheck %s '--implicit-check-not=<unknown>:0' // REQUIRES: OS=macosx // This is a temporary test for checking of availability diagnostics (explicit unavailability, // deprecation, and potential unavailability) in synthesized code. After this checking // is fully staged in, the tests in this file will be moved. // import Foundation func useClassThatTriggersImportOfDeprecatedEnum() { // Check to make sure that the bodies of enum methods that are synthesized // when importing deprecated enums do not themselves trigger deprecation // warnings in the synthesized code. _ = NSClassWithDeprecatedOptionsInMethodSignature.sharedInstance() } func useClassThatTriggersImportOExplicitlyUnavailableOptions() { _ = NSClassWithPotentiallyUnavailableOptionsInMethodSignature.sharedInstance() } func useClassThatTriggersImportOfPotentiallyUnavailableOptions() { _ = NSClassWithExplicitlyUnavailableOptionsInMethodSignature.sharedInstance() } func directUseShouldStillTriggerDeprecationWarning() { _ = NSDeprecatedOptions.first // expected-warning {{'NSDeprecatedOptions' was deprecated in OS X 10.51: Use a different API}} _ = NSDeprecatedEnum.first // expected-warning {{'NSDeprecatedEnum' was deprecated in OS X 10.51: Use a different API}} } func useInSignature(_ options: NSDeprecatedOptions) { // expected-warning {{'NSDeprecatedOptions' was deprecated in OS X 10.51: Use a different API}} } class SuperClassWithDeprecatedInitializer { @available(OSX, introduced: 10.9, deprecated: 10.51) init() { } } class SubClassWithSynthesizedDesignedInitializerOverride : SuperClassWithDeprecatedInitializer { // The synthesized designated initializer override calls super.init(), which is // deprecated, so the synthesized initializer is marked as deprecated as well. // This does not generate a warning here (perhaps it should?) but any call // to Sub's initializer will cause a deprecation warning. } func callImplicitInitializerOnSubClassWithSynthesizedDesignedInitializerOverride() { _ = SubClassWithSynthesizedDesignedInitializerOverride() // expected-warning {{'init()' was deprecated in OS X 10.51}} } @available(OSX, introduced: 10.9, deprecated: 10.51) class NSDeprecatedSuperClass { var i : Int = 7 // Causes initializer to be synthesized } class NotDeprecatedSubClassOfDeprecatedSuperClass : NSDeprecatedSuperClass { // expected-warning {{'NSDeprecatedSuperClass' was deprecated in OS X 10.51}} } func callImplicitInitializerOnNotDeprecatedSubClassOfDeprecatedSuperClass() { // We do not expect a warning here because the synthesized initializer // in NotDeprecatedSubClassOfDeprecatedSuperClass is not itself marked // deprecated. _ = NotDeprecatedSubClassOfDeprecatedSuperClass() } @available(OSX, introduced: 10.9, deprecated: 10.51) class NSDeprecatedSubClassOfDeprecatedSuperClass : NSDeprecatedSuperClass { } // Tests synthesis of materializeForSet class ClassWithLimitedAvailabilityAccessors { var limitedGetter: Int { @available(OSX, introduced: 10.52) get { return 10 } set(newVal) {} } var limitedSetter: Int { get { return 10 } @available(OSX, introduced: 10.52) set(newVal) {} } } @available(*, unavailable) func unavailableFunction() -> Int { return 10 } // expected-note 3{{'unavailableFunction()' has been explicitly marked unavailable here}} class ClassWithReferencesLazyInitializers { var propWithUnavailableInInitializer: Int = unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}} lazy var lazyPropWithUnavailableInInitializer: Int = unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}} } @available(*, unavailable) func unavailableUseInUnavailableFunction() { // Diagnose references to unavailable functions in non-implicit code // as errors unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}} expected-warning {{result of call to 'unavailableFunction()' is unused}} } @available(OSX 10.52, *) func foo() { let _ = SubOfOtherWithInit() }
apache-2.0
1cabbe4d3297eb25e9a3ae43508c72f8
39.311927
216
0.774238
4.376494
false
false
false
false
swift-lang/swift-k
tests/language-behaviour/arrays/111-array-individual-assigns.swift
2
215
int i[]; i[0]=1; i[1]=100; i[2]=10000; type messagefile; app (messagefile t) p(int inp[]) { echo inp[1] stdout=@filename(t); } messagefile outfile <"111-array-individual-assigns.out">; outfile = p(i);
apache-2.0
d848c5352efd02792e88455e1a4150ad
13.333333
57
0.623256
2.621951
false
false
true
false
shimisheetrit/MyMFSDKCore
DemoAppSwift/DemoAppSwift/SettingsViewController.swift
1
5303
// // SettingsViewController.swift // DemoAppSwift // // Created by Shimi Sheetrit on 2/16/16. // Copyright © 2016 Matomy Media Group Ltd. All rights reserved. // import UIKit import AVFoundation class SettingsViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { private var isScannerReading: Bool! private var captureSession: AVCaptureSession! private var videoPreviewLayer: AVCaptureVideoPreviewLayer! @IBOutlet weak var hashTextField: UITextField! @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var viewPreview: UIView! @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var startButton: UIButton! @IBOutlet weak var doneButtonItem: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() self.isScannerReading = false self.captureSession = nil self.startButton.layer.cornerRadius = 4.0 self.statusLabel.text = "QR Code Reader is not yet running..." self.view.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: "dismissKeyboard")) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dismissKeyboard() { self.hashTextField.resignFirstResponder() } //MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "SettingsToMainSegue") { if(self.hashTextField.text?.characters.count > 0) { let vc = segue.destinationViewController as! MainViewController vc.invh = self.hashTextField.text! } } } @IBAction func startStopReading(_ sender: AnyObject) { if(!self.isScannerReading) { if(self.startReading()) { self.startButton.setTitle("Stop", for:UIControlState()) self.statusLabel.text = "Scanning for QR Code..." } } else{ self.stopReading() self.startButton.setTitle("Start!", for:UIControlState()) self.statusLabel.text = "QR Code Reader is not running..." } self.isScannerReading = !self.isScannerReading } func startReading () -> Bool { var input: AVCaptureDeviceInput let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do { input = try AVCaptureDeviceInput.init(device: captureDevice!) } catch { return false } self.captureSession = AVCaptureSession.init() self.captureSession.addInput(input) let captureMetadataOutput = AVCaptureMetadataOutput.init() self.captureSession.addOutput(captureMetadataOutput) var dispatchQueue: DispatchQueue dispatchQueue = DispatchQueue(label: "myQueue", attributes: DispatchQueueAttributes.serial) captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatchQueue) captureMetadataOutput.metadataObjectTypes = NSArray.init(object: AVMetadataObjectTypeQRCode) as [AnyObject] self.videoPreviewLayer = AVCaptureVideoPreviewLayer.init(session: self.captureSession) self.videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill self.videoPreviewLayer.frame = self.viewPreview.layer.bounds self.viewPreview.layer.addSublayer(self.videoPreviewLayer) self.captureSession.startRunning() return true } func stopReading() { self.captureSession.stopRunning() self.captureSession = nil self.videoPreviewLayer.removeFromSuperlayer() } //MARK: AVCaptureMetadataOutputObjectsDelegate func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, from connection: AVCaptureConnection!) { if(metadataObjects != nil && metadataObjects.count > 0) { let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject if(metadataObj.type == AVMetadataObjectTypeQRCode) { self.statusLabel.performSelector(onMainThread: "setText:", with: "QR Code Reader is not running...", waitUntilDone: false) self.performSelector(onMainThread: "stopReading", with: nil, waitUntilDone: false) DispatchQueue.main.async(execute: { self.startButton.setTitle("Start!", for:UIControlState()) self.hashTextField.text = metadataObj.stringValue }) self.isScannerReading = false } } } }
apache-2.0
7d2e16d4a1e2574305a7197faa3d571c
32.1375
142
0.597322
6.252358
false
false
false
false
eljeff/AudioKit
Sources/AudioKit/Nodes/Effects/Modulation/Flanger.swift
1
4056
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AVFoundation import CAudioKit /// Stereo Flanger /// public class Flanger: Node, AudioUnitContainer, Tappable, Toggleable { /// Unique four-letter identifier "flgr" public static let ComponentDescription = AudioComponentDescription(effect: "flgr") /// Internal type of audio unit for this node public typealias AudioUnitType = InternalAU /// Internal audio unit public private(set) var internalAU: AudioUnitType? // MARK: - Parameters /// Specification for the frequency public static let frequencyDef = NodeParameterDef( identifier: "frequency", name: "Frequency (Hz)", address: ModulatedDelayParameter.frequency.rawValue, range: kFlanger_MinFrequency ... kFlanger_MaxFrequency, unit: .hertz, flags: .default) /// Modulation Frequency (Hz) @Parameter public var frequency: AUValue /// Specification for the depth public static let depthDef = NodeParameterDef( identifier: "depth", name: "Depth 0-1", address: ModulatedDelayParameter.depth.rawValue, range: kFlanger_MinDepth ... kFlanger_MaxDepth, unit: .generic, flags: .default) /// Modulation Depth (fraction) @Parameter public var depth: AUValue /// Specification for the feedback public static let feedbackDef = NodeParameterDef( identifier: "feedback", name: "Feedback 0-1", address: ModulatedDelayParameter.feedback.rawValue, range: kFlanger_MinFeedback ... kFlanger_MaxFeedback, unit: .generic, flags: .default) /// Feedback (fraction) @Parameter public var feedback: AUValue /// Specification for the dry wet mix public static let dryWetMixDef = NodeParameterDef( identifier: "dryWetMix", name: "Dry Wet Mix 0-1", address: ModulatedDelayParameter.dryWetMix.rawValue, range: kFlanger_MinDryWetMix ... kFlanger_MaxDryWetMix, unit: .generic, flags: .default) /// Dry Wet Mix (fraction) @Parameter public var dryWetMix: AUValue // MARK: - Audio Unit /// Internal audio unit for flanger public class InternalAU: AudioUnitBase { /// Get an array of the parameter definitions /// - Returns: Array of parameter definitions /// Get an array of the parameter definitions /// - Returns: Array of parameter definitions public override func getParameterDefs() -> [NodeParameterDef] { return [Flanger.frequencyDef, Flanger.depthDef, Flanger.feedbackDef, Flanger.dryWetMixDef] } /// Create flanger DSP /// - Returns: DSP Reference public override func createDSP() -> DSPRef { return akFlangerCreateDSP() } } // MARK: - Initialization /// Initialize this flanger node /// /// - Parameters: /// - input: Node whose output will be processed /// - frequency: modulation frequency Hz /// - depth: depth of modulation (fraction) /// - feedback: feedback fraction /// - dryWetMix: fraction of wet signal in mix - traditionally 50%, avoid changing this value /// public init( _ input: Node, frequency: AUValue = kFlanger_DefaultFrequency, depth: AUValue = kFlanger_DefaultDepth, feedback: AUValue = kFlanger_DefaultFeedback, dryWetMix: AUValue = kFlanger_DefaultDryWetMix ) { super.init(avAudioNode: AVAudioNode()) instantiateAudioUnit { avAudioUnit in self.avAudioUnit = avAudioUnit self.avAudioNode = avAudioUnit self.internalAU = avAudioUnit.auAudioUnit as? AudioUnitType self.frequency = frequency self.depth = depth self.feedback = feedback self.dryWetMix = dryWetMix } connections.append(input) } }
mit
682b540ff45a1f0a4643fca87c822645
31.190476
106
0.638314
4.794326
false
false
false
false
Shivol/Swift-CS333
playgrounds/uiKit/UIKitCatalog.playground/Pages/UIStackView.xcplaygroundpage/Contents.swift
2
1010
//: # UIStackView //:The UIStackView class provides a streamlined interface for laying out a collection of views in either a column or a row. //: //: [UIStackView API Reference](https://developer.apple.com/reference/uikit/uistackview) import UIKit import PlaygroundSupport let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: 250, height: 250)) for i in 1...5 { let column = UIStackView(frame: CGRect(x: 0, y: 0, width: 50, height: 250)) for j in 1...3 { let subview = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) subview.backgroundColor = UIColor(displayP3Red: 0.2 * CGFloat(i), green: 0.2 * CGFloat(j), blue: 0.2 * CGFloat(i + j), alpha: 1) column.addArrangedSubview(subview) } column.distribution = .fillEqually column.axis = .vertical column.spacing = 1 stackView.addArrangedSubview(column) } stackView.distribution = .fillEqually stackView.axis = .horizontal stackView.spacing = 1 PlaygroundPage.current.liveView = stackView
mit
f664087002a85829a54c42bbf888d063
36.407407
136
0.69703
3.726937
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/TextFormattingTableViewController.swift
1
9981
class TextFormattingTableViewController: TextFormattingProvidingTableViewController { override var titleLabelText: String? { return WMFLocalizedString("edit-text-formatting-table-view-title", value: "Text formatting", comment: "Title for text formatting menu in the editing interface") } private struct Content { let type: ContentType let title: String? let detailText: String? let customView: (UIView & Themeable)? var isEnabled: Bool = true init(type: ContentType, title: String? = nil, detailText: String? = nil, customView: (UIView & Themeable)? = nil) { self.type = type self.title = title self.detailText = detailText self.customView = customView } } private enum ContentType { case customView case detail case destructiveAction } private struct Item { let cell: TextFormattingTableViewCell.Type var content: Content let onSelection: (() -> Void)? init(with content: Content, onSelection: (() -> Void)? = nil) { switch content.type { case .customView: self.cell = TextFormattingCustomViewTableViewCell.self case .detail: self.cell = TextFormattingDetailTableViewCell.self case .destructiveAction: self.cell = TextFormattingDetailTableViewCell.self } self.content = content self.onSelection = onSelection } } // MARK: - Items // Some are lazy, some need to be updated so they can't all be in a lazy array let textStyleFormattingTableViewController = TextStyleFormattingTableViewController.wmf_viewControllerFromStoryboardNamed("TextFormatting") let textSizeFormattingTableViewController = TextSizeFormattingTableViewController.wmf_viewControllerFromStoryboardNamed("TextFormatting") private var textStyle: Item { let showTextStyleFormattingTableViewController = { self.textStyleFormattingTableViewController.delegate = self.delegate self.textStyleFormattingTableViewController.selectedTextStyleType = self.selectedTextStyleType self.textStyleFormattingTableViewController.apply(theme: self.theme) self.navigationController?.pushViewController(self.textStyleFormattingTableViewController, animated: true) } return Item(with: Content(type: .detail, title: textStyleFormattingTableViewController.titleLabelText, detailText: selectedTextStyleType.name), onSelection: showTextStyleFormattingTableViewController) } private var textSize: Item { let showTextSizeFormattingTableViewController = { self.textSizeFormattingTableViewController.delegate = self.delegate self.textSizeFormattingTableViewController.selectedTextSizeType = self.selectedTextSizeType self.textSizeFormattingTableViewController.apply(theme: self.theme) self.navigationController?.pushViewController(self.textSizeFormattingTableViewController, animated: true) } return Item(with: Content(type: .detail, title: textSizeFormattingTableViewController.titleLabelText, detailText: selectedTextSizeType.name), onSelection: showTextSizeFormattingTableViewController) } private func didSelectClearFormatting() { guard clearFormatting.content.isEnabled else { return } delegate?.textFormattingProvidingDidTapClearFormatting() } private lazy var clearFormatting: Item = { let content = Content(type: .destructiveAction, title: WMFLocalizedString("edit-text-clear-formatting", value: "Clear formatting", comment: "Title for the button that clears formatting from the selected range"), detailText: nil, customView: nil) let clearFormatting: () -> Void = { [weak self] in self?.didSelectClearFormatting() } return Item(with: content, onSelection: clearFormatting) }() private let textFormattingPlainToolbarView = TextFormattingPlainToolbarView.wmf_viewFromClassNib() private let textFormattingGroupedToolbarView = TextFormattingGroupedToolbarView.wmf_viewFromClassNib() weak override var delegate: TextFormattingDelegate? { didSet { textFormattingPlainToolbarView?.delegate = delegate textFormattingGroupedToolbarView?.delegate = delegate } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private lazy var staticItems: [Item] = { let plainToolbar = Item(with: Content(type: .customView, customView: textFormattingPlainToolbarView)) let groupedToolbar = Item(with: Content(type: .customView, customView: textFormattingGroupedToolbarView)) return [plainToolbar, groupedToolbar] }() private var items: [Item] { var allItems = staticItems allItems.append(textStyle) allItems.append(clearFormatting) return allItems } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let configuredCell = configuredCell(for: indexPath) else { assertionFailure("Expected a subclass of TextFormattingTableViewCell") return UITableViewCell() } return configuredCell } private func configuredCell(for indexPath: IndexPath) -> UITableViewCell? { let item = items[indexPath.row] let content = item.content let contentType = content.type switch contentType { case .customView: guard let cell = tableView.dequeueCell(ofType: TextFormattingCustomViewTableViewCell.self, for: indexPath) else { break } guard let customView = content.customView else { break } cell.configure(with: customView) cell.apply(theme: theme) cell.selectionStyle = .none return cell case .detail: guard let cell = tableView.dequeueCell(ofType: TextFormattingDetailTableViewCell.self, for: indexPath) else { break } guard let title = content.title, let detailText = content.detailText else { break } cell.apply(theme: theme) cell.configure(with: title, detailText: detailText) cell.accessoryType = .disclosureIndicator cell.selectionStyle = .none cell.accessibilityTraits = .button return cell case .destructiveAction: guard let cell = tableView.dequeueCell(ofType: TextFormattingDetailTableViewCell.self, for: indexPath) else { break } guard let title = content.title else { break } cell.apply(theme: theme) cell.configure(with: title, detailText: content.detailText) cell.textLabel?.textColor = content.isEnabled ? theme.colors.destructive : theme.colors.secondaryText cell.accessoryType = .none cell.selectionStyle = .none cell.accessibilityTraits = content.isEnabled ? .button : [.button, .notEnabled] return cell } return nil } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = items[indexPath.row] item.onSelection?() } override func textSelectionDidChange(isRangeSelected: Bool) { super.textSelectionDidChange(isRangeSelected: isRangeSelected) textFormattingPlainToolbarView?.enableAllButtons() textFormattingGroupedToolbarView?.enableAllButtons() textStyleFormattingTableViewController.textSelectionDidChange(isRangeSelected: isRangeSelected) textSizeFormattingTableViewController.textSelectionDidChange(isRangeSelected: isRangeSelected) textFormattingPlainToolbarView?.deselectAllButtons() textFormattingGroupedToolbarView?.deselectAllButtons() clearFormatting.content.isEnabled = true tableView.reloadRows(at: [IndexPath(row: 3, section: 0)], with: .none) } override func buttonSelectionDidChange(button: SectionEditorButton) { super.buttonSelectionDidChange(button: button) textStyleFormattingTableViewController.buttonSelectionDidChange(button: button) textSizeFormattingTableViewController.buttonSelectionDidChange(button: button) textFormattingPlainToolbarView?.selectButton(button) textFormattingGroupedToolbarView?.selectButton(button) } override func disableButton(button: SectionEditorButton) { super.disableButton(button: button) textStyleFormattingTableViewController.disableButton(button: button) textSizeFormattingTableViewController.disableButton(button: button) textFormattingPlainToolbarView?.disableButton(button) textFormattingGroupedToolbarView?.disableButton(button) if button.kind == .clearFormatting { clearFormatting.content.isEnabled = false tableView.reloadRows(at: [IndexPath(row: 3, section: 0)], with: .none) } } } private extension UITableView { func dequeueCell<T: UITableViewCell>(ofType type: T.Type, for indexPath: IndexPath) -> T? { guard let cell = dequeueReusableCell(withIdentifier: type.identifier, for: indexPath) as? T else { assertionFailure("Could not dequeue cell of type \(T.self)") return nil } return cell } }
mit
d24b66644bc14ef77dbb1b3a24a9a545
41.653846
253
0.677988
5.626268
false
false
false
false
Pluto-tv/jsonjam
Example/Tests/Tests.swift
1
8681
import UIKit import XCTest import JSONJam import JSONJam_Example class Tests: XCTestCase { override func setUp() { super.setUp() } func testSerializeAndDeserialize() { var randomProduct = self.createRandomProduct() var serializedProduct = randomProduct.parameterize() XCTAssertNotNil(serializedProduct, "serialized product can't be nil") var rebuiltProduct: Product? rebuiltProduct <-- (serializedProduct as AnyObject?) XCTAssertNotNil(rebuiltProduct, "rebuilt product can't be nil") if let rebuiltProduct = rebuiltProduct { XCTAssertNotNil(rebuiltProduct.productDescription, "product description can't be nil") if let productDescription = randomProduct.productDescription, let rebuiltProductDescription = rebuiltProduct.productDescription { XCTAssertEqual(productDescription, rebuiltProductDescription, "product description must match") } XCTAssertNotNil(rebuiltProduct.tags, "tags can't be nil") if let tags = randomProduct.tags, let rebuiltTags = rebuiltProduct.tags { XCTAssertEqual(tags, rebuiltTags, "tags must match") } XCTAssertNotNil(rebuiltProduct.price, "price can't be nil") if let price = randomProduct.price, let rebuildPrice = rebuiltProduct.price { XCTAssertEqual(price, rebuildPrice, "price must match") } XCTAssertNotNil(rebuiltProduct.creationDate, "creationDate can't be nil") if let creationDate = randomProduct.creationDate, let rebuiltCreationDate = rebuiltProduct.creationDate { XCTAssertEqualWithAccuracy(creationDate.timeIntervalSinceReferenceDate, rebuiltCreationDate.timeIntervalSinceReferenceDate, 1, "creationDate must match") } XCTAssertNotNil(rebuiltProduct.creationDate, "creationDate can't be nil") if let transactionDates = randomProduct.transactionDates, let rebuiltTransactionDates = rebuiltProduct.transactionDates { for i in 0..<transactionDates.count { XCTAssertEqualWithAccuracy(transactionDates[i].timeIntervalSinceReferenceDate, rebuiltTransactionDates[i].timeIntervalSinceReferenceDate, 1, "transactionDates must match") } } XCTAssertNotNil(rebuiltProduct.detailURL, "detailURL can't be nil") if let detailURL = randomProduct.detailURL, let rebuildDetailURL = rebuiltProduct.detailURL { XCTAssertEqual(detailURL, rebuildDetailURL, "detailURL must match") } XCTAssertNotNil(rebuiltProduct.photoURLs, "photoURLs can't be nil") if let photoURLs = randomProduct.photoURLs, let rebuildPhotoURLs = rebuiltProduct.photoURLs { XCTAssertEqual(photoURLs, rebuildPhotoURLs, "photoURLs must match") } XCTAssertNotNil(rebuiltProduct.owner, "owner can't be nil") if let owner = randomProduct.owner, let rebuiltOwner = rebuiltProduct.owner { XCTAssertNotNil(rebuiltOwner.name, "owner name can't be nil") if let name = owner.name, let rebuiltName = rebuiltOwner.name { XCTAssertEqual(name, rebuiltName, "owner name must match") } XCTAssertNotNil(rebuiltOwner.shoeSize, "owner shoeSize can't be nil") if let shoeSize = owner.shoeSize, let rebuiltShoeSize = rebuiltOwner.shoeSize { XCTAssertNotNil(rebuiltShoeSize.size, "shoeSize size can't be nil") if let size = shoeSize.size, let rebuiltSize = rebuiltShoeSize.size { XCTAssertEqual(size, rebuiltSize, "shoeSize size must match") } XCTAssertNotNil(rebuiltShoeSize.sizeSystem?.rawValue, "shoeSize sizeSystem can't be nil") if let sizeSystem = shoeSize.sizeSystem, let rebuiltSizeSystem = rebuiltShoeSize.sizeSystem { XCTAssertEqual(sizeSystem, rebuiltSizeSystem, "shoeSize sizeSystem must match") } } } XCTAssertEqual(randomProduct.buyers![0].shoeSize!.size!, rebuiltProduct.buyers![0].shoeSize!.size!, "first buyer's shoe size must match") } } func testDeserializeAndSerialize() { var jsonObject: JSONDictionary = ["product_description": "This is a wonderful thing.", "tags": ["imaginary", "terrific"], "price": 35.50, "creation_date": "1985-11-05 04:30:15", "transaction_dates": ["1987-05-03 04:15:30", "2005-09-20 08:45:52"], "owner": ["name": "Coleman Francis", "shoe_size": ["size": 9, "system": "AUS"]], "buyers": [["name": "Coleman Francis", "shoe_size": ["size": 9, "system": "AUS"]], ["name": "Mateo Mateo", "shoe_size": ["size": 8, "system": "UK"]]], "url": "http://www.mattluedke.com", "photos": ["http://www.mattluedke.com/wp-content/uploads/2013/08/cropped-IMG_2495.jpg", "http://www.mattluedke.com/wp-content/uploads/2013/08/cropped-IMG_24971.jpg"]] var deserializedProduct: Product? deserializedProduct <-- (jsonObject as AnyObject?) XCTAssertNotNil(deserializedProduct, "deserialized product can't be nil") var reserializedProduct = deserializedProduct?.parameterize() XCTAssertNotNil(reserializedProduct, "reserialized product can't be nil") XCTAssertEqual(reserializedProduct!["product_description"] as! String, jsonObject["product_description"] as! String, "product description must match") XCTAssertEqual((reserializedProduct!["owner"] as! JSONDictionary)["name"] as! String, (jsonObject["owner"] as! JSONDictionary)["name"] as! String, "owner name must match") XCTAssertEqual(((reserializedProduct!["buyers"] as! [JSONDictionary])[0]["shoe_size"] as! JSONDictionary)["size"] as! Int, ((jsonObject["buyers"] as! [JSONDictionary])[0]["shoe_size"] as! JSONDictionary)["size"] as! Int, "first buyer's shoe size must match") } func createRandomShoeSize() -> ShoeSize { var shoeSize = ShoeSize() shoeSize.size = Int(arc4random_uniform(15)) var randomNumber = Int(arc4random_uniform(4)) switch randomNumber { case 0: shoeSize.sizeSystem = .UnitedStates case 1: shoeSize.sizeSystem = .Europe case 2: shoeSize.sizeSystem = .UnitedKingdom default: shoeSize.sizeSystem = .Australia } return shoeSize } func createRandomUser() -> User { var user = User() var randomNumber = Int(arc4random_uniform(2)) switch randomNumber { case 0: user.name = "Mateo" default: user.name = "Matthias" } user.shoeSize = self.createRandomShoeSize() return user } func createRandomProduct() -> Product { var product = Product() var randomDescNumber = Int(arc4random_uniform(2)) switch randomDescNumber { case 0: product.productDescription = "This item will change your life." default: product.productDescription = "This item is best enjoyed with green tea." } var randomTagNumber = Int(arc4random_uniform(2)) switch randomTagNumber { case 0: product.tags = ["timid", "interstellar", "quiet"] default: product.tags = ["tempestuous", "populist"] } product.price = Double(arc4random_uniform(200)) product.creationDate = Date() product.transactionDates = [Date(), Date()] product.owner = createRandomUser() product.buyers = [createRandomUser(), createRandomUser(), createRandomUser()] product.detailURL = URL(string: "http://mattluedke.com/") product.photoURLs = [URL(string: "http://www.mattluedke.com/wp-content/uploads/2013/08/cropped-IMG_2495.jpg")!, URL(string: "http://www.mattluedke.com/wp-content/uploads/2013/08/cropped-IMG_24971.jpg")!] return product } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } }
mit
19ce750f8090b4aa4715043f5764eeaf
47.227778
689
0.617901
4.822778
false
false
false
false
EurekaCommunity/FloatLabelRow
Sources/FloatLabelTextField.swift
1
6852
// FloatLabelRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.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 @IBDesignable public class FloatLabelTextField: UITextField { let animationDuration = 0.3 var title = UILabel() // MARK:- Properties override public var accessibilityLabel:String! { get { if text?.isEmpty ?? true { return title.text } else { return text } } set { self.accessibilityLabel = newValue } } override public var placeholder:String? { didSet { title.text = placeholder title.sizeToFit() } } override public var attributedPlaceholder:NSAttributedString? { didSet { title.text = attributedPlaceholder?.string title.sizeToFit() } } public var titleFont: UIFont = .systemFont(ofSize: 12.0) { didSet { title.font = titleFont title.sizeToFit() } } @IBInspectable public var hintYPadding:CGFloat = 0.0 @IBInspectable public var titleYPadding:CGFloat = 0.0 { didSet { var r = title.frame r.origin.y = titleYPadding title.frame = r } } @IBInspectable public var titleTextColor:UIColor = .gray { didSet { if !isFirstResponder { title.textColor = titleTextColor } } } @IBInspectable public var titleActiveTextColor:UIColor! { didSet { if isFirstResponder { title.textColor = titleActiveTextColor } } } // MARK:- Init required public init?(coder aDecoder:NSCoder) { super.init(coder:aDecoder) setup() } override init(frame:CGRect) { super.init(frame:frame) setup() } // MARK:- Overrides override public func layoutSubviews() { super.layoutSubviews() setTitlePositionForTextAlignment() let isResp = isFirstResponder if isResp && !(text?.isEmpty ?? true) { title.textColor = titleActiveTextColor } else { title.textColor = titleTextColor } // Should we show or hide the title label? if text?.isEmpty ?? true { // Hide hideTitle(isResp) } else { // Show showTitle(isResp) } } override public func textRect(forBounds bounds:CGRect) -> CGRect { var r = super.textRect(forBounds: bounds) if !(text?.isEmpty ?? true){ var top = ceil(title.font.lineHeight + hintYPadding) top = min(top, maxTopInset()) r = r.inset(by: UIEdgeInsets(top: top, left: 0.0, bottom: 0.0, right: 0.0)) } return r.integral } override public func editingRect(forBounds bounds:CGRect) -> CGRect { var r = super.editingRect(forBounds: bounds) if !(text?.isEmpty ?? true) { var top = ceil(title.font.lineHeight + hintYPadding) top = min(top, maxTopInset()) r = r.inset(by: UIEdgeInsets(top: top, left: 0.0, bottom: 0.0, right: 0.0)) } return r.integral } override public func clearButtonRect(forBounds bounds:CGRect) -> CGRect { var r = super.clearButtonRect(forBounds: bounds) if !(text?.isEmpty ?? true) { var top = ceil(title.font.lineHeight + hintYPadding) top = min(top, maxTopInset()) r = CGRect(x:r.origin.x, y:r.origin.y + (top * 0.5), width:r.size.width, height:r.size.height) } return r.integral } // MARK:- Private Methods private func setup() { borderStyle = UITextField.BorderStyle.none titleActiveTextColor = tintColor // Set up title label title.alpha = 0.0 title.font = titleFont title.textColor = titleTextColor if let str = placeholder, !str.isEmpty { title.text = str title.sizeToFit() } self.addSubview(title) } private func maxTopInset()->CGFloat { return max(0, floor(bounds.size.height - (font?.lineHeight ?? 0) - 4.0)) } private func setTitlePositionForTextAlignment() { let r = textRect(forBounds: bounds) var x = r.origin.x if textAlignment == .center { x = r.origin.x + (r.size.width * 0.5) - title.frame.size.width } else if textAlignment == .right { x = r.origin.x + r.size.width - title.frame.size.width } title.frame = CGRect(x:x, y:title.frame.origin.y, width:title.frame.size.width, height:title.frame.size.height) } private func showTitle(_ animated:Bool) { let dur = animated ? animationDuration : 0 UIView.animate(withDuration: dur, delay:0, options: UIView.AnimationOptions.beginFromCurrentState.union(.curveEaseOut), animations:{ // Animation self.title.alpha = 1.0 var r = self.title.frame r.origin.y = self.titleYPadding self.title.frame = r }) } private func hideTitle(_ animated:Bool) { let dur = animated ? animationDuration : 0 UIView.animate(withDuration: dur, delay:0, options: UIView.AnimationOptions.beginFromCurrentState.union(.curveEaseIn), animations:{ // Animation self.title.alpha = 0.0 var r = self.title.frame r.origin.y = self.title.font.lineHeight + self.hintYPadding self.title.frame = r }) } }
mit
02217dc5d9c3dc03070560042d009fa5
32.262136
140
0.591798
4.52576
false
false
false
false
khillman84/music-social
music-social/music-social/DataService.swift
1
1572
// // DataService.swift // music-social // // Created by Kyle Hillman on 4/24/17. // Copyright © 2017 Kyle Hillman. All rights reserved. // import Foundation import Firebase import SwiftKeychainWrapper // Store the Firebase reference URL stored in the GoogleService-Info.plist let gDataBase = FIRDatabase.database().reference() let gStorageBase = FIRStorage.storage().reference() class DataService { static let dataService = DataService() // Database References private var _ref_base = gDataBase private var _ref_posts = gDataBase.child("posts") private var _ref_users = gDataBase.child("users") // Storage References private var _ref_post_images = gStorageBase.child("post-pics") private var _ref_profile_images = gStorageBase.child("profile-pics") var ref_base: FIRDatabaseReference { return _ref_base } var ref_posts: FIRDatabaseReference { return _ref_posts } var ref_users: FIRDatabaseReference { return _ref_users } var ref_post_images: FIRStorageReference { return _ref_post_images } var ref_profile_images: FIRStorageReference { return _ref_profile_images } var ref_user_current: FIRDatabaseReference { let uid = KeychainWrapper.standard.string(forKey: gKeyUID) let user = ref_users.child(uid!) return user } func createFirebaseDBUser(uid: String, userData: Dictionary<String, String>) { ref_users.child(uid).updateChildValues(userData) } }
mit
439d2b2d4afde53becfe0b0f8c762bfc
25.183333
82
0.665818
4.280654
false
false
false
false
RickieL/learn-swift
swift-initialization.playground/section-1.swift
1
9041
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // setting initial values for stored properties // initializers struct Fahrenheit { var temperature: Double init() { // perform some initialization here temperature = 32.0 } } var f = Fahrenheit() println("The default temperature is \(f.temperature)° Fahrenheit") struct Celsius { var temperatureInCelsius: Double init(fromFahrenheit fahrenheit: Double) { temperatureInCelsius = (fahrenheit - 32.0) / 1.8 } init(fromKelvin kelvin: Double) { temperatureInCelsius = kelvin - 273.15 } init(_ celsius: Double) { temperatureInCelsius = celsius } } let boilingPointOfWater = Celsius(fromFahrenheit: 212.0) let freezingPointOfWater = Celsius(fromKelvin: 273.15) let bodyTemperature = Celsius(37.5) struct Color { let red, green, blue: Double init(red: Double, green: Double, blue: Double) { self.red = red self.green = green self.blue = blue } init(white: Double) { red = white green = white blue = white } } let magenta = Color(red: 1.0, green: 0.0, blue: 1.0) let halfGray = Color(white: 0.5) // optional property types class SurveyQuestion { var text: String let text2: String class var text3: String { return "test" } var response: String? init(text: String) { self.text = text self.text2 = text } func ask() { println(text2) } } let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?") cheeseQuestion.ask() cheeseQuestion.response = "Yes, I do like cheese." println(cheeseQuestion.text) println(cheeseQuestion.text2) let beetsQuestion = SurveyQuestion(text: "How about beets?") beetsQuestion.ask() // prints "How about beets?" beetsQuestion.response = "I also like beets. (But not with cheese.)" println(SurveyQuestion.text3) println(cheeseQuestion.text2) // Modifying Constant Properties During Initialization // default initializers class ShoppingListItem1 { var name: String? var quntity = 1 var purchased = false } var item = ShoppingListItem1() // memberwise initializers for structure types struct Size { var width = 0.0, height = 0.0 } let twoByTwo = Size(width: 2.0, height: 2.0) struct Point { var x = 0.0, y = 0.0 } struct Rect { var origin = Point() var size = Size() init() {} init(origin: Point, size: Size) { self.origin = origin self.size = size } init(center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) } } let basicRect = Rect() let originRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0)) let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0)) // class inheritance and initialization // initializer delegation for class types // initializer inheritance and overriding class Vehicle { var numberOfWheels = 0 var description: String { return "\(numberOfWheels) wheels" } } let vehicle = Vehicle() vehicle.numberOfWheels = 3 println("Vehicle: \(vehicle.description)") class Bicycle: Vehicle { var gear = 1 override init() { super.init() numberOfWheels = 2 } } let bicycle = Bicycle() bicycle.gear = 2 println("Bicycle: \(bicycle.description)") // automatic initializer inheritance // designated and convenience initializers in action class Food { var name: String init(name: String) { self.name = name } convenience init() { self.init(name: "[Unnamed]") } } let namedMeat = Food(name: "Bacon") let mysteryMeat = Food() class RecipeIngredient: Food { var quantity: Int init(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) } override convenience init(name: String) { self.init(name: name, quantity: 1) } } let oneMysteryItem = RecipeIngredient() let oneBacon = RecipeIngredient(name: "Bacon") let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6) class ShoppingListItem: RecipeIngredient { var purchased = false var description: String { var output = "\(quantity) x \(name)" output += purchased ? " ✔" : " ✘" return output } } var breakfastList = [ ShoppingListItem(), ShoppingListItem(name: "Bacon"), ShoppingListItem(name: "Eggs", quantity: 6), ] breakfastList[0].name = "Orange juice" breakfastList[0].purchased = true for item in breakfastList { println(item.description) } // Failable initializers struct Animal { let species: String init?(species: String) { if species.isEmpty { return nil } self.species = species } } let someCreature = Animal(species: "Giraffe") if let giraffe = someCreature { println("An animal was initialized with a species of \(giraffe.species)") } let anonymousCreature = Animal(species: "") if anonymousCreature == nil { println("The anonymous creature could not be initialized") } // failable initializers for enumerations enum TemperatureUnit { case Kelvin, Celsius, Fahrenheit init?(symbol: Character) { switch symbol { case "K": self = .Kelvin case "C": self = .Celsius case "F": self = .Fahrenheit default: return nil } } } let fahrenheitUnit = TemperatureUnit(symbol: "F") if fahrenheitUnit != nil { println("This is a defined temperature unit, so initialization succeeded.") } let unknowUnit = TemperatureUnit(symbol: "X") if unknowUnit == nil { println("This is not a defined temperature unit, so initialization failed") } // failable initializers for Enumerations with row values /* enum TemperatureUnit: Character { case Kelvin = "K", Celsius = "C", Fahrenheit = "F" } let fahrenheitUnit = TemperatureUnit(rawValue: "F") if fahrenheitUnit != nil { println("This is a defined temperature unit, so initialization succeeded.") } // prints "This is a defined temperature unit, so initialization succeeded." let unknownUnit = TemperatureUnit(rawValue: "X") if unknownUnit == nil { println("This is not a defined temperature unit, so initialization failed.") } // prints "This is not a defined temperature unit, so initialization failed." */ // failable initializers for classes class Product { let name: String! init?(name: String) { if name.isEmpty {return nil} self.name = name } } if let bowTie = Product(name: "bow tie") { // no need to check if bowTie.name == nil println("The product's name is \(bowTie.name)") } // propagation of initialization failure class CartItem: Product { let quantity: Int! init?(name: String, quantity: Int) { super.init(name: name) if quantity < 1 { return nil } self.quantity = quantity } } if let twoSocks = CartItem(name: "sock", quantity: 2) { println("Item: \(twoSocks.name), quantity: \(twoSocks.quantity)") } else { println("Unable to initialize zero shirts") } if let zeroShirts = CartItem(name: "shirt", quantity: 0) { println("Item: \(zeroShirts.name), quantity: \(zeroShirts.quantity)") } else { println("Unable to initialize zero shirts") } // override a failable initializer class Document { var name: String? init() {} init?(name: String) { if name.isEmpty { return nil } self.name = name } } class AutomaticalNamedDocument: Document { override init() { super.init() self.name = "[Untitled]" } override init(name: String) { super.init() if name.isEmpty { self.name = "[Untitled]" } else { self.name = name } } } // the init! failable initializer // required initializers // Write the required modifier before the definition of a class initializer to indicate that every subclass of the class must implement that initializer: class SomeClass { required init() { // initializer implementation goes here } } class SomeSubclass: SomeClass { required init() { // subclass implementation of the required initializer goes here } } // setting a default property value with a closure or function struct Checkerboard { let boardColor: [Bool] = { var temporaryBoard = [Bool]() var isBlack = false for i in 1...10 { for j in 1...10 { temporaryBoard.append(isBlack) isBlack = !isBlack } isBlack = !isBlack } return temporaryBoard }() func squareIsBlackAtRow(row: Int, column: Int) -> Bool { return boardColor[(row * 10) + column] } } let board = Checkerboard() println(board.squareIsBlackAtRow(0, column: 1)) println(board.squareIsBlackAtRow(9, column: 9))
bsd-3-clause
4e4fe54b843febb98ecb75dbf9b8c1d4
23.355795
153
0.64575
3.915078
false
false
false
false
wordpress-mobile/WordPress-Aztec-iOS
Aztec/Classes/Formatters/Implementations/CodeFormatter.swift
2
2258
import Foundation import UIKit /// Formatter to apply simple value (NSNumber, UIColor) attributes to an attributed string. class CodeFormatter: AttributeFormatter { var placeholderAttributes: [NSAttributedString.Key: Any]? let monospaceFont: UIFont let backgroundColor: UIColor let htmlRepresentationKey: NSAttributedString.Key // MARK: - Init init(monospaceFont: UIFont = FontProvider.shared.monospaceFont, backgroundColor: UIColor = ColorProvider.shared.codeBackgroungColor) { self.monospaceFont = monospaceFont self.backgroundColor = backgroundColor self.htmlRepresentationKey = .codeHtmlRepresentation } func applicationRange(for range: NSRange, in text: NSAttributedString) -> NSRange { return range } func apply(to attributes: [NSAttributedString.Key: Any], andStore representation: HTMLRepresentation?) -> [NSAttributedString.Key: Any] { var resultingAttributes = attributes resultingAttributes[.font] = monospaceFont resultingAttributes[.backgroundColor] = self.backgroundColor var representationToUse = HTMLRepresentation(for: .element(HTMLElementRepresentation.init(name: "code", attributes: []))) if let requestedRepresentation = representation { representationToUse = requestedRepresentation } resultingAttributes[htmlRepresentationKey] = representationToUse return resultingAttributes } func remove(from attributes: [NSAttributedString.Key: Any]) -> [NSAttributedString.Key: Any] { var resultingAttributes = attributes resultingAttributes.removeValue(forKey: .font) resultingAttributes.removeValue(forKey: .backgroundColor) resultingAttributes.removeValue(forKey: htmlRepresentationKey) if let placeholderAttributes = self.placeholderAttributes { resultingAttributes[.font] = placeholderAttributes[.font] resultingAttributes[.backgroundColor] = placeholderAttributes[.backgroundColor] } return resultingAttributes } func present(in attributes: [NSAttributedString.Key: Any]) -> Bool { return attributes[NSAttributedString.Key.codeHtmlRepresentation] != nil } }
gpl-2.0
fd7969eaab74ac726c33bf1276317b9d
37.271186
141
0.725864
5.575309
false
false
false
false
YunsChou/LovePlay
LovePlay-Swift3/LovePlay/Class/News/View/NewsCommentFooterView.swift
1
2404
// // NewsCommentFooterView.swift // LovePlay // // Created by Yuns on 2017/5/21. // Copyright © 2017年 yuns. All rights reserved. // import UIKit typealias NewsCommentFooterClickBlock = () -> () class NewsCommentFooterView: UITableViewHeaderFooterView { var footerClickBlock : NewsCommentFooterClickBlock? class func sectionHeaderWithTableView(tableView : UITableView) -> NewsCommentFooterView { let ID = NSStringFromClass(self) var sectionFooter : NewsCommentFooterView? = tableView.dequeueReusableHeaderFooterView(withIdentifier: ID) as? NewsCommentFooterView if sectionFooter == nil { sectionFooter = NewsCommentFooterView(reuseIdentifier: ID) } return sectionFooter! } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) self.contentView.backgroundColor = UIColor.white self.addSubViews() self.snp_subViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - private private func addSubViews() { self.addSubview(self.titleButton) } private func snp_subViews() { self.titleButton.snp.makeConstraints { (make) in make.edges.equalToSuperview() } } fileprivate var _titleText : String? var titleText : String? { set { _titleText = newValue titleButton.setTitle(newValue, for: .normal) } get { return _titleText } } //MARK: - publick public func commentFooterClickBlock(didClickedBlock : @escaping NewsCommentFooterClickBlock) { self.footerClickBlock = didClickedBlock } //MARK: - target-action @objc func footerButtonClick() { if self.footerClickBlock != nil { self.footerClickBlock!() } } // MARK: - lazy load lazy var titleButton : UIButton = { let titleButton = UIButton() titleButton .setTitle("footer", for: .normal) titleButton.titleLabel?.font = UIFont.systemFont(ofSize: 14) titleButton.setTitleColor(RGB(r: 215, g: 84, b: 107), for: .normal) titleButton.addTarget(self, action: #selector(self.footerButtonClick), for: .touchUpInside) return titleButton }() }
mit
272bf20c015169d77d6c20fef434b06e
28.280488
140
0.635152
4.782869
false
false
false
false
einsteinx2/iSub
Classes/Server Loading/Video Streams/Models/HLSPlaylist.swift
1
9063
// // HLSPlaylist.swift // iSub // // Created by Benjamin Baron on 9/10/17. // Copyright © 2017 Benjamin Baron. All rights reserved. // // Loosely based on the example code here: https://github.com/kencool/KSHLSPlayer // import Foundation final class HLSPlaylist { struct Schema { static let header = "#EXTM3U" static let playlistType = "#EXT-X-PLAYLIST-TYPE" static let targetDuration = "#EXT-X-TARGETDURATION" static let version = "#EXT-X-VERSION" static let mediaSequence = "#EXT-X-MEDIA-SEQUENCE" static let discontinuity = "#EXT-X-DISCONTINUITY" static let streamInf = "#EXT-X-STREAM-INF" static let inf = "#EXTINF" static let endList = "#EXT-X-ENDLIST" // EXT-X-STREAM-INF properties static let programId = "PROGRAM-ID" static let bandwidth = "BANDWIDTH" static let averageBandwidth = "AVERAGE-BANDWIDTH" static let resolution = "RESOLUTION" static let codecs = "CODECS" } enum StreamType: String { case live = "LIVE" case event = "EVENT" case vod = "VOD" } // Unique identifier to create segment and playlist URLs let uuid = UUID() // Input URL var url: URL // Schema var type: StreamType? var targetDuration: Int? var version: Int? var mediaSequence: Int? var hasEnd = false // Optional EXT-X-STREAM-INF properties var programId: Int? var bandwidth: Int? var averageBandwidth: Int? var resolution: String? var codecs: String? var playlists = [HLSPlaylist]() var segments = [HLSSegment]() var segmentNames = [String: HLSSegment]() init(url: URL) { self.url = url } init(url: URL, data: Data) { self.url = url if let text = String(data: data, encoding: .utf8) { parseText(text) } } fileprivate func parseText(_ text: String) { var segCount = 0 let lines = text.components(separatedBy: "\n") for (i, line) in lines.enumerated() { // Target Duration if line.hasPrefix(Schema.targetDuration) { let value = line.substring(from: Schema.targetDuration.count + 1) targetDuration = Int(value) } // Version else if line.hasPrefix(Schema.version) { version = Int(line.substring(from: Schema.version.count + 1)) } // Media Sequence else if line.hasPrefix(Schema.mediaSequence) { let value = line.substring(from: Schema.mediaSequence.count + 1) mediaSequence = Int(value) } // Playlists else if line.hasPrefix(Schema.streamInf) { if let url = processUrlString(lines[i + 1]) { let playlist = HLSPlaylist(url: url) let value = line.substring(from: Schema.streamInf.count + 1) let components = value.components(separatedBy: CharacterSet(charactersIn: ",")) for pair in components { let split = pair.components(separatedBy: CharacterSet(charactersIn: "=")) if split.count == 2 { switch split[0] { case Schema.programId: playlist.programId = Int(split[1]) case Schema.bandwidth: playlist.bandwidth = Int(split[1]) case Schema.averageBandwidth: playlist.averageBandwidth = Int(split[1]) case Schema.resolution: playlist.resolution = split[1] case Schema.codecs: playlist.codecs = split[1] default: break } } } playlists.append(playlist) } } // Segments else if line.hasPrefix(Schema.inf) { // Find the duration let sequence = (mediaSequence ?? 0) + segments.count var value = line.substring(from: Schema.inf.count + 1) // Remove optional title data from duration if let commaIndex = value.index(of: Character(",")) { value = value.substring(to: commaIndex.encodedOffset) } // Create and store the segment if let url = processUrlString(lines[i + 1]) { let fileName = "segment\(segCount).ts" let duration = Double(value) ?? 10.0 let ts = HLSSegment(url: url, fileName: fileName, duration: duration, sequence: sequence) segments.append(ts) segmentNames[ts.fileName] = ts segCount += 1 } } // End List else if line.hasPrefix(Schema.endList) { hasEnd = true } } } fileprivate func processUrlString(_ urlString: String) -> URL? { if let scheme = url.scheme, let host = url.host, urlString.hasPrefix("/") { var finalUrlString = scheme + "://" + host if let port = url.port { finalUrlString += ":\(port)" } finalUrlString += urlString return URL(string: finalUrlString) } return URL(string: urlString) } func generate(_ baseUrl: String?, overrideType: StreamType? = nil, overrideTargetDuration: Int? = nil, overrideVersion: Int? = nil, overrideMediaSequence: Int? = nil) -> String { // Header var string = Schema.header + "\n" if let type = (overrideType ?? type) { string += Schema.playlistType + ":\(type.rawValue)\n" } if let targetDuration = (overrideTargetDuration ?? targetDuration) { string += Schema.targetDuration + ":\(targetDuration)\n" } if let version = (overrideVersion ?? version) { string += Schema.version + ":\(version)\n" } if let mediaSequence = (overrideMediaSequence ?? mediaSequence) { string += Schema.mediaSequence + ":\(mediaSequence)\n" } // Playlists for playlist in playlists { var properties = "" if let programId = playlist.programId { properties += ",\(Schema.programId)=\(programId)" } if let bandwidth = playlist.bandwidth { properties += ",\(Schema.bandwidth)=\(bandwidth)" } if let averageBandwidth = playlist.averageBandwidth { properties += ",\(Schema.averageBandwidth)=\(averageBandwidth)" } if let resolution = playlist.resolution { properties += ",\(Schema.resolution)=\(resolution)" } if let codecs = playlist.codecs { properties += ",\(Schema.codecs)=\(codecs)" } if properties.count > 0 { // Remove the leading comma properties = properties.substring(from: 1) } string += "\(Schema.streamInf):\(properties)\n" // Either use the local URL if provided or the original URL if let base = baseUrl { string += "\(base)/playlist/\(playlist.uuid.uuidString).m3u8\n" } else { string += "\(url.absoluteString)\n" } } // Segments for segment in segments { // Floating point durations are only supported in version 3 let duration: Any = version == 3 ? segment.duration : Int(segment.duration) string += Schema.inf + ":\(duration),\n" // Either use the local URL if provided or the original URL if let base = baseUrl { string += "\(base)/segment/\(uuid.uuidString)/\(segment.fileName)\n" } else { string += "\(segment.url)\n" } } // End List if hasEnd { string += Schema.endList } return string } func playlist(withUuidString uuidString: String) -> HLSPlaylist? { // Check if it matches the root playlist if uuid.uuidString == uuidString { return self } // Check if it matches any sub-playlist let index = playlists.index(where: { playlist -> Bool in return playlist.uuid.uuidString == uuidString }) if let index = index { return playlists[index] } return nil } }
gpl-3.0
f92cfa3eb77daac877c3ab0677b33d07
35.837398
182
0.510925
4.930359
false
false
false
false
blitzagency/amigo-swift
Amigo/ThreadLocalEngineFactory.swift
1
1017
// // ThreadLocalEngineFactory.swift // Amigo // // Created by Adam Venturella on 7/22/15. // Copyright © 2015 BLITZ. All rights reserved. // import Foundation public protocol ThreadLocalEngineFactory: EngineFactory{ func createEngine() -> Engine } extension ThreadLocalEngineFactory{ func engineForCurrentThread() -> Engine? { let dict = NSThread.currentThread().threadDictionary let obj = dict["amigo.threadlocal.engine"] as? Engine if let obj = obj{ return obj } else { return nil } } func createEngineForCurrentThread() -> Engine { let engine = createEngine() let dict = NSThread.currentThread().threadDictionary dict["amigo.threadlocal.engine"] = engine as? AnyObject return engine } public func connect() -> Engine { if let engine = engineForCurrentThread(){ return engine } else { return createEngineForCurrentThread() } } }
mit
1ca09e1a072b12aca7cda00503ff5ec3
22.627907
63
0.624016
4.576577
false
false
false
false
keith/radars
TestCompilerError/Pods/Nimble/Nimble/DSL+Wait.swift
59
2247
import Foundation /// Only classes, protocols, methods, properties, and subscript declarations can be /// bridges to Objective-C via the @objc keyword. This class encapsulates callback-style /// asynchronous waiting logic so that it may be called from Objective-C and Swift. internal class NMBWait: NSObject { internal class func until(timeout timeout: NSTimeInterval, file: String = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void { var completed = false var token: dispatch_once_t = 0 let result = pollBlock(pollInterval: 0.01, timeoutInterval: timeout) { dispatch_once(&token) { dispatch_async(dispatch_get_main_queue()) { action() { completed = true } } } return completed } switch (result) { case .Failure: let pluralize = (timeout == 1 ? "" : "s") fail("Waited more than \(timeout) second\(pluralize)", file: file, line: line) case .Timeout: fail("Stall on main thread - too much enqueued on main run loop before waitUntil executes.", file: file, line: line) case let .ErrorThrown(error): // Technically, we can never reach this via a public API call fail("Unexpected error thrown: \(error)", file: file, line: line) case .Success: break } } @objc(untilFile:line:action:) internal class func until(file: String = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void { until(timeout: 1, file: file, line: line, action: action) } } /// Wait asynchronously until the done closure is called. /// /// This will advance the run loop. public func waitUntil(timeout timeout: NSTimeInterval, file: String = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void { NMBWait.until(timeout: timeout, file: file, line: line, action: action) } /// Wait asynchronously until the done closure is called. /// /// This will advance the run loop. public func waitUntil(file: String = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void { NMBWait.until(timeout: 1, file: file, line: line, action: action) }
mit
8dada1b8d382e58f6d7d943bbd1b0471
43.96
150
0.611482
4.231638
false
false
false
false
SSamanta/SSHTTPClient
SSHTTPClient/SSHTTPClient/SSHTTPClient.swift
1
2513
// // SSHTTPClient.swift // SSHTTPClient // // Created by Susim on 11/17/14. // Copyright (c) 2014 Susim. All rights reserved. // import Foundation public typealias SSHTTPResponseHandler = (_ responseObject : Any? , _ error : Error?) -> Void open class SSHTTPClient : NSObject { var httpMethod,url,httpBody: String? var headerFieldsAndValues : [String:String]? //Initializer Method with url string , method, body , header field and values public init(url:String?, method:String?, httpBody: String?, headerFieldsAndValues: [String:String]?) { self.url = url self.httpMethod = method self.httpBody = httpBody self.headerFieldsAndValues = headerFieldsAndValues } //Get formatted JSON public func getJsonData(_ httpResponseHandler : @escaping SSHTTPResponseHandler) { getResponseData { (data, error) in if error != nil { httpResponseHandler(nil,error) }else if let datObject = data as? Data { let json = try? JSONSerialization.jsonObject(with: datObject, options: []) httpResponseHandler(json,nil) } } } //Get Response in Data format public func getResponseData(_ httpResponseHandler : @escaping SSHTTPResponseHandler) { var request: URLRequest? if let urlString = self.url { if let url = URL(string: urlString) { request = URLRequest(url: url) } } if let method = self.httpMethod { request?.httpMethod = method } if let headerKeyValues = self.headerFieldsAndValues { for key in headerKeyValues.keys { request?.setValue(headerKeyValues[key] , forHTTPHeaderField: key) } } if let body = self.httpBody { request?.httpBody = body.data(using: String.Encoding.utf8) } if let requestObject = request { let session = URLSession.shared let task = session.dataTask(with: requestObject, completionHandler: { (data, response, error) in if error != nil { httpResponseHandler(nil,error) }else { httpResponseHandler (data as Any?, nil) } }) task.resume() } } //Cancel Request open func cancelRequest()->Void{ let session = URLSession.shared session.invalidateAndCancel() } }
mit
26083c5c21c5afd87abb029bc86fe392
33.424658
108
0.590131
4.842004
false
false
false
false
iaagg/Saturn
Saturn/Classes/SaturnPsychic.swift
1
2677
// // SaturnPsychic.swift // Pods // // Created by Alexey Getman on 22/10/2016. // // import UIKit class SaturnPsychic: NSObject { class func saveSyncPoint(_ time: Double) { syncTimeWithGlobalWebTime(time) } class func syncTimeWithGlobalWebTime(_ time: Double) { SaturnJustice.justice().verdict = .DeviceWasNotRebooted let atomicTime = SaturnTimeMine.getAtomicTime() let saturnData = SaturnStorage.storage().saturnData saturnData.syncPoint.serverTime = time; saturnData.syncPoint.atomicTime = atomicTime; saturnData.lastSyncedBootAtomicTime = atomicTime; saturnData.arrayOfUnsyncedBootsAtomicTime = NSArray() SaturnStorage.saveSaturnData(saturnData) } class func tryToSyncTimeWithGlobalWeb() { // Send HTTP GET Request // Define server side script URL let URL = "http://api.geonames.org/timezoneJSON?formatted=true&lat=47.01&lng=10.2&username=demo&style=full" // Add one parameter // Create NSURL Ibject let myUrl = NSURL(string: URL) // Creaste URL Request let request = NSMutableURLRequest(url:myUrl! as URL) // Set request HTTP method to GET. It could be POST as well request.httpMethod = "GET" DispatchQueue.global(qos: .background).async { // Excute HTTP Request let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in // Check for error if error != nil { print("error=\(error)") return } if let httpResponse: HTTPURLResponse = response as? HTTPURLResponse { let headers = httpResponse.allHeaderFields let dateString: String = headers["Date"] as! String let formatter = DateFormatter() formatter.dateFormat = "EEE',' dd MMM yyyy HH:mm:ss z" formatter.locale = Locale(identifier: "en_US") let date = formatter.date(from: dateString) if let time: TimeInterval = date?.timeIntervalSince1970 { DispatchQueue.main.async { //SUCCESS: Perform synchronization SaturnPsychic.syncTimeWithGlobalWebTime(time) } } } } task.resume() } } }
mit
8b4f0f4d00f3c9b9f9b20c7ab3325963
32.886076
115
0.54053
5.089354
false
false
false
false
tsolomko/SWCompression
Sources/swcomp/Benchmarks/BenchmarkMetadata.swift
1
2948
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation struct BenchmarkMetadata: Codable, Equatable { var timestamp: TimeInterval? var osInfo: String var swiftVersion: String var swcVersion: String var description: String? private static func run(command: URL, arguments: [String] = []) throws -> String { let task = Process() let pipe = Pipe() task.standardOutput = pipe task.standardError = pipe task.executableURL = command task.arguments = arguments task.standardInput = nil try task.run() task.waitUntilExit() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = String(data: data, encoding: .utf8)! return output } private static func getExecURL(for command: String) throws -> URL { let args = ["-c", "which \(command)"] #if os(Windows) swcompExit(.benchmarkCannotGetSubcommandPathWindows) #else let output = try BenchmarkMetadata.run(command: URL(fileURLWithPath: "/bin/sh"), arguments: args) #endif return URL(fileURLWithPath: String(output.dropLast())) } private static func getOsInfo() throws -> String { #if os(Linux) return try BenchmarkMetadata.run(command: BenchmarkMetadata.getExecURL(for: "uname"), arguments: ["-a"]) #else #if os(Windows) return "Unknown Windows OS" #else return try BenchmarkMetadata.run(command: BenchmarkMetadata.getExecURL(for: "sw_vers")) #endif #endif } init(_ description: String?, _ preserveTimestamp: Bool) throws { self.timestamp = preserveTimestamp ? Date.timeIntervalSinceReferenceDate : nil self.osInfo = try BenchmarkMetadata.getOsInfo() #if os(Windows) self.swiftVersion = "Unknown Swift version on Windows" #else self.swiftVersion = try BenchmarkMetadata.run(command: BenchmarkMetadata.getExecURL(for: "swift"), arguments: ["-version"]) #endif self.swcVersion = _SWC_VERSION self.description = description } func print() { Swift.print("OS Info: \(self.osInfo)", terminator: "") Swift.print("Swift version: \(self.swiftVersion)", terminator: "") Swift.print("SWC version: \(self.swcVersion)") if let timestamp = self.timestamp { Swift.print("Timestamp: " + DateFormatter.localizedString(from: Date(timeIntervalSinceReferenceDate: timestamp), dateStyle: .short, timeStyle: .short)) } if let description = self.description { Swift.print("Description: \(description)") } Swift.print() } }
mit
bcc7c4e01903df42ea7556ca98aa55b5
34.518072
116
0.602442
4.840722
false
false
false
false
ozgur/TestApp
TestApp/External/BubbleTransition.swift
1
6464
// // BubbleTransition.swift // BubbleTransition // // Created by Andrea Mazzini on 04/04/15. // Copyright (c) 2015 Fancy Pixel. All rights reserved. // import UIKit /** A custom modal transition that presents and dismiss a controller with an expanding bubble effect. - Prepare the transition: ```swift override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let controller = segue.destination controller.transitioningDelegate = self controller.modalPresentationStyle = .custom } ``` - Implement UIViewControllerTransitioningDelegate: ```swift func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.transitionMode = .present transition.startingPoint = someButton.center transition.bubbleColor = someButton.backgroundColor! return transition } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.transitionMode = .dismiss transition.startingPoint = someButton.center transition.bubbleColor = someButton.backgroundColor! return transition } ``` */ open class BubbleTransition: NSObject { /** The point that originates the bubble. The bubble starts from this point and shrinks to it on dismiss */ open var startingPoint = CGPoint.zero { didSet { bubble.center = startingPoint } } /** The transition duration. The same value is used in both the Present or Dismiss actions Defaults to `0.5` */ open var duration = 0.5 /** The transition direction. Possible values `.present`, `.dismiss` or `.pop` Defaults to `.Present` */ open var transitionMode: BubbleTransitionMode = .present /** The color of the bubble. Make sure that it matches the destination controller's background color. */ open var bubbleColor: UIColor = .white open fileprivate(set) var bubble = UIView() /** The possible directions of the transition. - Present: For presenting a new modal controller - Dismiss: For dismissing the current controller - Pop: For a pop animation in a navigation controller */ @objc public enum BubbleTransitionMode: Int { case present, dismiss, pop } } extension BubbleTransition: UIViewControllerAnimatedTransitioning { // MARK: - UIViewControllerAnimatedTransitioning /** Required by UIViewControllerAnimatedTransitioning */ public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } /** Required by UIViewControllerAnimatedTransitioning */ public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView let fromViewController = transitionContext.viewController(forKey: .from) let toViewController = transitionContext.viewController(forKey: .to) fromViewController?.beginAppearanceTransition(false, animated: true) if transitionMode == .present { let presentedControllerView = transitionContext.view(forKey: UITransitionContextViewKey.to)! let finalFrame = transitionContext.finalFrame(for: toViewController!) let originalCenter = CGPoint(x: finalFrame.width / 2, y: finalFrame.height / 2) let originalSize = finalFrame.size bubble = UIView() bubble.frame = frameForBubble(originalCenter, size: originalSize, start: startingPoint) bubble.layer.cornerRadius = bubble.frame.size.height / 2 bubble.center = startingPoint bubble.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) bubble.backgroundColor = bubbleColor containerView.addSubview(bubble) presentedControllerView.center = startingPoint presentedControllerView.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) presentedControllerView.alpha = 0 containerView.addSubview(presentedControllerView) UIView.animate(withDuration: duration, animations: { self.bubble.transform = CGAffineTransform.identity presentedControllerView.transform = CGAffineTransform.identity presentedControllerView.alpha = 1 presentedControllerView.center = originalCenter presentedControllerView.frame = finalFrame }, completion: { (_) in fromViewController?.endAppearanceTransition() transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } else { let key = (transitionMode == .pop) ? UITransitionContextViewKey.to : UITransitionContextViewKey.from let returningControllerView = transitionContext.view(forKey: key)! let originalCenter = returningControllerView.center let originalSize = returningControllerView.frame.size bubble.frame = frameForBubble(originalCenter, size: originalSize, start: startingPoint) bubble.layer.cornerRadius = bubble.frame.size.height / 2 bubble.center = startingPoint UIView.animate(withDuration: duration, animations: { self.bubble.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) returningControllerView.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) returningControllerView.center = self.startingPoint returningControllerView.alpha = 0 if self.transitionMode == .pop { containerView.insertSubview(returningControllerView, belowSubview: returningControllerView) containerView.insertSubview(self.bubble, belowSubview: returningControllerView) } }, completion: { (_) in returningControllerView.center = originalCenter returningControllerView.removeFromSuperview() self.bubble.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled) fromViewController?.endAppearanceTransition() }) } } } private extension BubbleTransition { func frameForBubble(_ originalCenter: CGPoint, size originalSize: CGSize, start: CGPoint) -> CGRect { let lengthX = fmax(start.x, originalSize.width - start.x) let lengthY = fmax(start.y, originalSize.height - start.y) let offset = sqrt(lengthX * lengthX + lengthY * lengthY) * 2 let size = CGSize(width: offset, height: offset) return CGRect(origin: CGPoint.zero, size: size) } }
gpl-3.0
23efcbfb02f813dd5893e319f6cf75c1
35.937143
167
0.7319
5.395659
false
false
false
false
LoopKit/LoopKit
MockKitUI/MockPumpManager+UI.swift
1
3475
// // MockPumpManager+UI.swift // LoopKitUI // // Created by Michael Pangburn on 11/20/18. // Copyright © 2018 LoopKit Authors. All rights reserved. // import Foundation import SwiftUI import LoopKit import LoopKitUI import MockKit extension MockPumpManager: PumpManagerUI { private var appName: String { return Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String } public static var onboardingImage: UIImage? { return UIImage(named: "Pump Simulator", in: Bundle(for: MockPumpManagerSettingsViewController.self), compatibleWith: nil) } public var smallImage: UIImage? { return UIImage(named: "Pump Simulator", in: Bundle(for: MockPumpManagerSettingsViewController.self), compatibleWith: nil) } public static func setupViewController(initialSettings settings: PumpManagerSetupSettings, bluetoothProvider: BluetoothProvider, colorPalette: LoopUIColorPalette, allowDebugFeatures: Bool, allowedInsulinTypes: [InsulinType]) -> SetupUIResult<PumpManagerViewController, PumpManagerUI> { let mockPumpManager = MockPumpManager() mockPumpManager.setMaximumTempBasalRate(settings.maxBasalRateUnitsPerHour) mockPumpManager.syncBasalRateSchedule(items: settings.basalSchedule.items, completion: { _ in }) return .createdAndOnboarded(mockPumpManager) } public func settingsViewController(bluetoothProvider: BluetoothProvider, colorPalette: LoopUIColorPalette, allowDebugFeatures: Bool, allowedInsulinTypes: [InsulinType]) -> PumpManagerViewController { let settings = MockPumpManagerSettingsViewController(pumpManager: self, supportedInsulinTypes: allowedInsulinTypes) let nav = PumpManagerSettingsNavigationViewController(rootViewController: settings) return nav } public func deliveryUncertaintyRecoveryViewController(colorPalette: LoopUIColorPalette, allowDebugFeatures: Bool) -> (UIViewController & CompletionNotifying) { return DeliveryUncertaintyRecoveryViewController(appName: appName, uncertaintyStartedAt: Date()) { self.state.deliveryCommandsShouldTriggerUncertainDelivery = false self.state.deliveryIsUncertain = false } } public func hudProvider(bluetoothProvider: BluetoothProvider, colorPalette: LoopUIColorPalette, allowedInsulinTypes: [InsulinType]) -> HUDProvider? { return MockHUDProvider(pumpManager: self, allowedInsulinTypes: allowedInsulinTypes) } public static func createHUDView(rawValue: HUDProvider.HUDViewRawState) -> BaseHUDView? { return MockHUDProvider.createHUDView(rawValue: rawValue) } } public enum MockPumpStatusBadge: DeviceStatusBadge { case timeSyncNeeded public var image: UIImage? { switch self { case .timeSyncNeeded: return UIImage(systemName: "clock.fill") } } public var state: DeviceStatusBadgeState { switch self { case .timeSyncNeeded: return .warning } } } // MARK: - PumpStatusIndicator extension MockPumpManager { public var pumpStatusHighlight: DeviceStatusHighlight? { return buildPumpStatusHighlight(for: state) } public var pumpLifecycleProgress: DeviceLifecycleProgress? { return buildPumpLifecycleProgress(for: state) } public var pumpStatusBadge: DeviceStatusBadge? { return isClockOffset ? MockPumpStatusBadge.timeSyncNeeded : nil } }
mit
4280cae2108b7b2cda555b606c4a3863
38.033708
289
0.744099
4.991379
false
false
false
false
gottesmm/swift
test/decl/func/throwing_functions_without_try.swift
5
1426
// RUN: %target-typecheck-verify-swift -enable-throw-without-try // Test the -enable-throw-without-try option. Throwing function calls should // not require annotation with 'try'. // rdar://21444103 - only at the top level func foo() throws -> Int { return 0 } // That applies to global "script" code. var global: Int = 0 global = foo() // no error global = try foo() // still no error var global2: Int = foo() // no error var global3: Int = try foo() // no error // That includes autoclosures. func doLazy(_ fn: @autoclosure () throws -> Int) {} doLazy(foo()) // It doesn't include explicit closures. var closure: () -> () = { var x = foo() // expected-error {{call can throw, but it is not marked with 'try' and the error is not handled}} doLazy(foo()) // expected-error {{call can throw but is not marked with 'try'}} } // Or any other sort of structure. struct A { static var lazyCache: Int = foo() // expected-error {{call can throw, but errors cannot be thrown out of a global variable initializer}} } func baz() throws -> Int { var x: Int = 0 x = foo() // expected-error{{call can throw but is not marked with 'try'}} x = try foo() // no error return x } func baz2() -> Int { var x: Int = 0 x = foo() // expected-error{{call can throw, but it is not marked with 'try' and the error is not handled}} x = try foo() // expected-error{{errors thrown from here are not handled}} return x }
apache-2.0
cbcb04de94118ae607e4541a582a02c7
29.340426
138
0.661992
3.478049
false
false
false
false
Fenrikur/ef-app_ios
Eurofurence/Modules/Announcements/Presenter/AnnouncementsPresenter.swift
1
2174
import Foundation class AnnouncementsPresenter: AnnouncementsSceneDelegate, AnnouncementsListViewModelDelegate { private struct Binder: AnnouncementsBinder { var viewModel: AnnouncementsListViewModel func bind(_ component: AnnouncementComponent, at index: Int) { let announcement = viewModel.announcementViewModel(at: index) component.setAnnouncementTitle(announcement.title) component.setAnnouncementDetail(announcement.detail) component.setAnnouncementReceivedDateTime(announcement.receivedDateTime) if announcement.isRead { component.hideUnreadIndicator() } else { component.showUnreadIndicator() } } } private let scene: AnnouncementsScene private let interactor: AnnouncementsInteractor private let delegate: AnnouncementsModuleDelegate private var viewModel: AnnouncementsListViewModel? init(scene: AnnouncementsScene, interactor: AnnouncementsInteractor, delegate: AnnouncementsModuleDelegate) { self.scene = scene self.interactor = interactor self.delegate = delegate scene.setAnnouncementsTitle(.announcements) scene.setDelegate(self) } func announcementsSceneDidLoad() { interactor.makeViewModel(completionHandler: viewModelPrepared) } func announcementsSceneDidSelectAnnouncement(at index: Int) { scene.deselectAnnouncement(at: index) guard let identifier = viewModel?.identifierForAnnouncement(at: index) else { return } delegate.announcementsModuleDidSelectAnnouncement(identifier) } func announcementsViewModelDidChangeAnnouncements() { guard let viewModel = viewModel else { return } scene.bind(numberOfAnnouncements: viewModel.numberOfAnnouncements, using: Binder(viewModel: viewModel)) } private func viewModelPrepared(_ viewModel: AnnouncementsListViewModel) { self.viewModel = viewModel viewModel.setDelegate(self) scene.bind(numberOfAnnouncements: viewModel.numberOfAnnouncements, using: Binder(viewModel: viewModel)) } }
mit
2e6dc7ad85b94d9c5de700a22bb0fe68
34.639344
113
0.721251
5.939891
false
false
false
false
ziryanov/CCInfiniteScrolling
SwiftExample/InfiniteScrollingExample/FirstViewController.swift
1
3510
// // FirstViewController.swift // InfiniteScrollingExample // // Created by ziryanov on 14/09/16. // Copyright © 2016 Cloud Castle. All rights reserved. // import UIKit import CCInfiniteScrolling import UIView_TKGeometry final class Cell: UICollectionViewCell { override func awakeFromNib() { super.awakeFromNib() layer.borderColor = UIColor.purpleColor().CGColor layer.borderWidth = 1 layer.cornerRadius = 5 layer.masksToBounds = true } } class FirstViewController: UIViewController, UICollectionViewDataSource { @IBOutlet private var collectionView: UICollectionView! let maxOfCells = 100 var numOfCells = 0 var cellOffset = 0 override func viewDidLoad() { super.viewDidLoad() UIScrollView.setInfinityScrollingTriggerOffset(100) refreshPressed() setupLoadMore() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) collectionView.scrollToBottom() } @IBAction func refreshPressed() { cellOffset = maxOfCells / 2 numOfCells = 20 collectionView.reloadData() collectionView.infiniteScrollingDisabled = false delay { self.collectionView.setContentOffsetY((self.collectionView.contentHeight() - self.collectionView.height()) / 2) } } func setupLoadMore() { collectionView.addTopInfiniteScrollingWithActionHandler { [unowned self] in delay(1) { let additional = min(20, self.cellOffset) self.cellOffset -= additional self.numOfCells += additional if self.cellOffset == 0 { self.collectionView.infiniteScrollingDisabled = true } self.collectionView.reloadDataKeepBottomOffset() } } } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return numOfCells } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) (cell.viewWithTag(1) as? UILabel)?.text = "cell \(cellOffset + indexPath.row + 1)" return cell } } final class ThirdController: FirstViewController { private var refresh = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() self.collectionView.addSubview(refresh) refresh.addTarget(self, action: "refreshAction", forControlEvents: .ValueChanged) } var jj = 0 override func setupLoadMore() { self.collectionView.addBottomInfiniteScrollingWithActionHandler { if ++self.jj % 2 == 0 { delay(1) { self.numOfCells += 20 if self.numOfCells > self.maxOfCells { self.collectionView.infiniteScrollingDisabled = true } self.collectionView.reloadData() } } else { delay(1) { self.collectionView.infiniteScrollingBlockFailed = true } } } } func refreshAction() { delay(1) { self.refreshPressed() self.refresh.endRefreshing() } } }
mit
d614275ac0e3562523c490a869f27298
29.25
130
0.61043
5.474259
false
false
false
false