repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dathtcheapgo/Jira-Demo
refs/heads/master
Driver/Extension/HexColorExtension.swift
mit
1
// // HexColorExtension.swift // Demo // // Created by Tien Dat on 10/24/16. // Copyright © 2016 Tien Dat. All rights reserved. // import Foundation import UIKit extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(netHex:Int) { self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff) } }
ce81556b241e08dd74d57c458b1384c1
30.173913
116
0.599162
false
false
false
false
CartoDB/mobile-ios-samples
refs/heads/master
AdvancedMap.Swift/Feature Demo/StylePopupContent.swift
bsd-2-clause
1
// // StylePopupContent.swift // Feature Demo // // Created by Aare Undo on 20/06/2017. // Copyright © 2017 CARTO. All rights reserved. // import Foundation import UIKit class StylePopupContent : UIScrollView { static let CartoVectorSource = "carto.streets" static let CartoRasterSource = "carto.osm" static let Bright = "BRIGHT" static let Gray = "GRAY" static let Dark = "DARK" static let Positron = "POSITRON" static let DarkMatter = "DARKMATTER" static let Voyager = "VOYAGER" static let HereSatelliteDaySource = "SATELLITE DAY" static let HereNormalDaySource = "NORMAL DAY" static let VoyagerUrl = "http://{s}.basemaps.cartocdn.com/voyager_all/{z}/{x}/{y}.png"; static let PositronUrl = "http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png"; static let DarkMatterUrl = "http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png"; var cartoVector: StylePopupContentSection! var cartoRaster: StylePopupContentSection! convenience init() { self.init(frame: CGRect.zero) cartoVector = StylePopupContentSection() cartoVector.source = StylePopupContent.CartoVectorSource cartoVector.header.text = "CARTO VECTOR" cartoVector.addItem(text: StylePopupContent.Voyager, imageUrl: "style_image_nutiteq_voyager.png") cartoVector.addItem(text: StylePopupContent.Positron, imageUrl: "style_image_nutiteq_positron.png") cartoVector.addItem(text: StylePopupContent.DarkMatter, imageUrl: "style_image_nutiteq_darkmatter.png") addSubview(cartoVector) cartoRaster = StylePopupContentSection() cartoRaster.source = StylePopupContent.CartoRasterSource cartoRaster.header.text = "HERE RASTER" cartoRaster.addItem(text: StylePopupContent.HereSatelliteDaySource, imageUrl: "style_image_here_satellite.png") cartoRaster.addItem(text: StylePopupContent.HereNormalDaySource, imageUrl: "style_image_here_normal.png") addSubview(cartoRaster) } override func layoutSubviews() { super.layoutSubviews() let padding: CGFloat = 5 let headerPadding: CGFloat = 20 let x: CGFloat = padding var y: CGFloat = 0 let w: CGFloat = frame.width - 2 * padding var h: CGFloat = cartoVector.getHeight() cartoVector.frame = CGRect(x: x, y: y, width: w, height: h) y += h + headerPadding h = cartoRaster.getHeight() cartoRaster.frame = CGRect(x: x, y: y, width: w, height: h) contentSize = CGSize(width: frame.width, height: y + h + padding) } func highlightDefault() { getDefault().highlight() } func normalizeDefaultHighlight() { getDefault().normalize() } func getDefault() -> StylePopupContentSectionItem { return cartoVector.list[0] } } class StylePopupContentSection : UIView { var header: UILabel! var separator: UIView! var list = [StylePopupContentSectionItem]() var delegate: StyleUpdateDelegate! var source: String! convenience init() { self.init(frame: CGRect.zero) header = UILabel() header.font = UIFont(name: "Helvetica-Bold", size: 13) header.textColor = Colors.navy addSubview(header) separator = UIView() separator.backgroundColor = Colors.fromRgba(red: 220, green: 220, blue: 220, alpha: 200) separator.clipsToBounds = false addSubview(separator) let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.itemTapped(_:))) addGestureRecognizer(recognizer) } let headerHeight: CGFloat = 40 let padding: CGFloat = 5 override func layoutSubviews() { separator.frame = CGRect(x: padding, y: -padding, width: frame.width - 2 * padding, height: 1) var x: CGFloat = padding var y: CGFloat = 0 var w: CGFloat = frame.width - 3 * padding var h: CGFloat = headerHeight header.frame = CGRect(x: x, y: y, width: w, height: h) y = headerHeight w = (frame.width - 4 * padding) / 3 h = rowHeight - 2 * padding for item in list { item.frame = CGRect(x: x, y: y, width: w, height: h) x += w + padding if (x == frame.width) { x = padding y += rowHeight } } } let rowHeight: CGFloat = 110 func getHeight() -> CGFloat { let extra = headerHeight - CGFloat(Int(list.count / 3 * 2) * Int(padding)) if (list.count > 6) { return 3 * rowHeight + extra } if (list.count > 3) { return 2 * rowHeight + extra } return rowHeight + extra } @objc func itemTapped(_ sender: UITapGestureRecognizer) { let location = sender.location(in: self) for item in list { if (item.frame.contains(location)) { delegate?.styleClicked(selection: item, source: source) } } } func addItem(text: String, imageUrl: String) { let item = StylePopupContentSectionItem(text: text, imageUrl: imageUrl) list.append(item) addSubview(item) } } class StylePopupContentSectionItem : UIView { var imageView: UIImageView! var label: UILabel! convenience init(text: String, imageUrl: String) { self.init(frame: CGRect.zero) imageView = UIImageView() imageView.image = UIImage(named: imageUrl) imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.layer.borderColor = Colors.appleBlue.cgColor addSubview(imageView) label = UILabel() label.text = text label.textColor = Colors.appleBlue label.font = UIFont(name: "HelveticaNeue", size: 11) addSubview(label) } override func layoutSubviews() { let padding: CGFloat = 5 let x: CGFloat = 0 var y: CGFloat = 0 let w: CGFloat = frame.width var h: CGFloat = frame.height / 3 * 2 imageView.frame = CGRect(x: x, y: y, width: w, height: h) label.sizeToFit() y += h + padding h = label.frame.height label.frame = CGRect(x: x, y: y, width: w, height: h) } func highlight() { imageView.layer.borderWidth = 3 } func normalize() { imageView.layer.borderWidth = 0 } } protocol StyleUpdateDelegate { func styleClicked(selection: StylePopupContentSectionItem, source: String) }
644a28f640be00ed7b585325eb9eff43
27.184739
119
0.585922
false
false
false
false
data-licious/ceddl4swift
refs/heads/master
ceddl4swift/ceddl4swift/Page.swift
bsd-3-clause
1
// // Page.swift // ceddl4swift // // Created by Sachin Vas on 20/10/16. // Copyright © 2016 Sachin Vas. All rights reserved. // import Foundation open class Page: NSObject, JSONProtocol { fileprivate var parent: DigitalData! //JSON id - pageInfo fileprivate var pageInformation: PageInfo! //JSON id - category fileprivate var pageCategory: Category<Page>! //JSON id - attributes fileprivate var pageAttributes: DAttributes<Page>! /// init /// Constructs an `Page` object. public override init() { super.init() } /// init `Page` object. /// - Parameter parent: associated DigitalData. public init(parent p: DigitalData) { parent = p } /// Returns to the parent object. /// - Returns: Parent object open func endPage() -> DigitalData { return parent } /// Provides access to the PageInfo object for this Page. /// /// This object describes the Page. /// /// - Returns: PageInfo Object for this Page open func pageInfo() -> PageInfo { if pageInformation == nil { pageInformation = PageInfo(parent: self) } return pageInformation } /// Provides access to the Category object for the Page. /// /// Because of the wide range of methods for categorization, an object /// literal is provided for page categories. The name primaryCategory is /// RECOMMENDED if you included only one set of categories for pages, or for /// your primary set of categories. All other names are optional and should /// fit the individual implementation needs in both naming and values passed. /// /// - Returns: Category object for this Page open func category() -> Category<Page> { if pageCategory == nil { pageCategory = Category<Page>(parent: self) } return pageCategory } /// Provides access to the Attributes object for the Page. /// /// This object provides extensibility to the Page object. All names are /// optional and should fit the individual implementation needs in both /// naming and values passed. /// /// - Returns: Attributes object for this Page open func attributes() -> DAttributes<Page> { if pageAttributes == nil { pageAttributes = DAttributes<Page>(parent: self) } return pageAttributes } /// Directly adds a new attribute to the Page's attributes /// - Parameter name: Name of the attribute /// - Parameter value: Value for the attribute /// - Returns: current object open func addAttribute(_ name: String, value: AnyObject) -> Page { if pageAttributes == nil { pageAttributes = DAttributes<Page>(parent :self) } if let dateValue = value as? Date { let dateStringValue = dateToString(dateValue) _ = pageAttributes.attribute(name, value: dateStringValue as AnyObject) } else { _ = pageAttributes.attribute(name, value: value) } return self } /// Directly adds the primary category to the Page's categories /// - Parameter primaryCategory: Value for the primary category /// - Returns: current object. open func addPrimaryCategory(_ primaryCategory: String) -> Page { if pageCategory == nil { pageCategory = Category<Page>(parent: self) } _ = pageCategory.primaryCategory(primaryCategory) return self } /// Directly adds a custom category to the Page's categories /// - Parameter name: Name of the category /// - Parameter value: Value for the attribute /// - Returns: current object. open func addCategory(_ name: String, value: AnyObject) -> Page { if pageCategory == nil { pageCategory = Category<Page>(parent: self) } _ = pageCategory.category(name, value: value) return self } open func getMap() -> Dictionary<String, AnyObject> { var dictionary = Dictionary<String, AnyObject>() if pageInformation != nil { dictionary["pageInfo"] = pageInformation.getMap() as AnyObject } if pageCategory != nil { dictionary["category"] = pageCategory.getMap() as AnyObject } if pageAttributes != nil { dictionary["attributes"] = pageAttributes.getMap() as AnyObject } return dictionary } }
906f5cdbbbac597302a4d606d9ab1da9
29.691781
83
0.622629
false
false
false
false
ChrisAU/Locution
refs/heads/master
Papyrus/Views/SliderCell.swift
mit
2
// // SliderCell.swift // Papyrus // // Created by Chris Nevin on 7/07/2016. // Copyright © 2016 CJNevin. All rights reserved. // import UIKit class SliderCell : UITableViewCell, NibLoadable { @IBOutlet private weak var slider: UISlider! @IBOutlet private weak var label: UILabel! private var values: [String]? private var stepValue: Float = 1 private var index: Int = 0 private var onChange: ((Int) -> ())? override func layoutSubviews() { super.layoutSubviews() slider.value = Float(index) changedValue() } func configure(index: Int, values: [String], onChange: @escaping (Int) -> ()) { self.values = values self.index = index slider.maximumValue = Float(values.count - 1) self.onChange = onChange } private func changedValue() { onChange?(index) label.text = values?[index] } @IBAction private func sliderChanged(slider: UISlider) { slider.value = round(slider.value / stepValue) * stepValue index = Int(slider.value) changedValue() } }
421509a0cc21ca8256bc6dbdbbcd3248
24.177778
83
0.60812
false
false
false
false
krzysztofzablocki/Sourcery
refs/heads/master
SourceryRuntime/Sources/AST/TypeName/Generic.swift
mit
1
import Foundation /// Descibes Swift generic type @objcMembers public final class GenericType: NSObject, SourceryModelWithoutDescription { /// The name of the base type, i.e. `Array` for `Array<Int>` public var name: String /// This generic type parameters public let typeParameters: [GenericTypeParameter] /// :nodoc: public init(name: String, typeParameters: [GenericTypeParameter] = []) { self.name = name self.typeParameters = typeParameters } public var asSource: String { let arguments = typeParameters .map({ $0.typeName.asSource }) .joined(separator: ", ") return "\(name)<\(arguments)>" } public override var description: String { asSource } // sourcery:inline:GenericType.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name guard let typeParameters: [GenericTypeParameter] = aDecoder.decode(forKey: "typeParameters") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typeParameters"])); fatalError() }; self.typeParameters = typeParameters } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.typeParameters, forKey: "typeParameters") } // sourcery:end } /// Descibes Swift generic type parameter @objcMembers public final class GenericTypeParameter: NSObject, SourceryModel { /// Generic parameter type name public var typeName: TypeName // sourcery: skipEquality, skipDescription /// Generic parameter type, if known public var type: Type? /// :nodoc: public init(typeName: TypeName, type: Type? = nil) { self.typeName = typeName self.type = type } // sourcery:inline:GenericTypeParameter.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let typeName: TypeName = aDecoder.decode(forKey: "typeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typeName"])); fatalError() }; self.typeName = typeName self.type = aDecoder.decode(forKey: "type") } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.typeName, forKey: "typeName") aCoder.encode(self.type, forKey: "type") } // sourcery:end }
2c95e57aaa0830ea0b4597534f5316b2
35.171053
293
0.652237
false
false
false
false
leonardo-ferreira07/OnTheMap
refs/heads/master
OnTheMap/OnTheMap/Extensions/Extensions.swift
mit
1
// // Extensions.swift // OnTheMap // // Created by Leonardo Vinicius Kaminski Ferreira on 16/10/17. // Copyright © 2017 Leonardo Ferreira. All rights reserved. // import SafariServices extension UIViewController: SFSafariViewControllerDelegate { public func presentWebPageInSafari(withURLString URLString: String) { if let url = URL(string: URLString), UIApplication.shared.canOpenURL(url) { // let vc = SFSafariViewController(url: url) // vc.delegate = self // self.present(vc, animated: true) UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil) } else { showAlert("Opening link error", message: "There was an error trying to open the web link.") } } func showAlert(_ title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } } extension UIView { func startLoadingAnimation() { stopLoadingAnimation() DispatchQueue.main.async { let loadingView = LoadingViewPresenter.newInstance() loadingView.frame = UIScreen.main.bounds UIApplication.shared.keyWindow?.addSubview(loadingView) } } func stopLoadingAnimation() { DispatchQueue.main.async { if let subviews = UIApplication.shared.keyWindow?.subviews { for subview in subviews { if let subview = subview as? LoadingViewPresenter { subview.removeFromSuperview() } } } } } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)}) }
31ccb3d5ca47c18ffabe89872e98823e
35.180328
150
0.650204
false
false
false
false
ryanipete/AmericanChronicle
refs/heads/master
AmericanChronicle/Code/AppWide/Views/TitleValueButton.swift
mit
1
import UIKit final class TitleValueButton: UIControl { // MARK: Properties var value: String? { get { valueLabel.text } set { valueLabel.text = newValue } } private let titleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = AMCColor.darkGray label.highlightedTextColor = .white label.textAlignment = .center label.font = AMCFont.verySmallRegular return label }() private let valueLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = AMCColor.brightBlue label.highlightedTextColor = .white label.font = AMCFont.mediumRegular label.textAlignment = .center return label }() private let button: UIButton = { let btn = UIButton() btn.setBackgroundImage(.imageWithFillColor(.white, cornerRadius: 1.0), for: .normal) btn.setBackgroundImage(.imageWithFillColor(AMCColor.brightBlue, cornerRadius: 1.0), for: .highlighted) return btn }() private var observingToken: NSKeyValueObservation? // MARK: Init methods init(title: String, initialValue: String = "--") { super.init(frame: .zero) layer.shadowColor = AMCColor.darkGray.cgColor layer.shadowOffset = .zero layer.shadowRadius = 0.5 layer.shadowOpacity = 0.4 titleLabel.text = title valueLabel.text = initialValue button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside) observingToken = button.observe(\UIButton.isHighlighted) { [weak self] _, _ in self?.isHighlighted = (self?.button.isHighlighted ?? false) } addSubview(button) button.fillSuperview(insets: .zero) let labelStackView = UIStackView(arrangedSubviews: [titleLabel, valueLabel]) labelStackView.translatesAutoresizingMaskIntoConstraints = false labelStackView.isUserInteractionEnabled = false labelStackView.axis = .vertical addSubview(labelStackView) labelStackView.fillSuperview(horizontalInsets: 8.0, verticalInsets: 5.0) } @available(*, unavailable) override init(frame: CGRect) { fatalError("init(frame:) has not been implemented") } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @available(*, unavailable) init() { fatalError("init() has not been implemented") } // MARK: Internal methods @objc func didTapButton() { sendActions(for: .touchUpInside) } // MARK: UIControl overrides override var isHighlighted: Bool { didSet { titleLabel.isHighlighted = isHighlighted valueLabel.isHighlighted = isHighlighted } } // MARK: UIView overrides override var intrinsicContentSize: CGSize { CGSize(width: UIView.noIntrinsicMetric, height: Dimension.buttonHeight) } }
230e12a00355153f9a02028e8eb6c2a5
29.627451
110
0.650768
false
false
false
false
kaunteya/Linex
refs/heads/master
Standard Extensions/String+Basic.swift
mit
1
// // String+Basic.swift // Linex // // Created by Kaunteya Suryawanshi on 05/05/18. // Copyright © 2018 Kaunteya Suryawanshi. All rights reserved. // import Foundation extension String { /// All multiple whitespaces are replaced by one whitespace var condensedWhitespace: String { let components = self.components(separatedBy: .whitespaces) return components.filter { !$0.isEmpty }.joined(separator: " ") } func index(at offset: Int) -> Index { return index(startIndex, offsetBy: offset) } subscript(i: Int) -> Character { return self[index(at: i)] } subscript(range: Range<Int>) -> Substring { let rangeIndex:Range<Index> = self.indexRangeFor(range: range) return self[rangeIndex] } subscript(range: NSRange) -> String { return (self as NSString).substring(with: range) } func indexRangeFor(range: Range<Int>) -> Range<Index> { return index(at: range.lowerBound)..<index(at: range.upperBound) } func indexRangeFor(range: ClosedRange<Int>) -> ClosedRange<Index> { return index(at: range.lowerBound)...index(at: range.upperBound) } mutating func replace(range: Range<Int>, with replacement: String) { self.replaceSubrange(self.index(at: range.lowerBound)..<self.index(at: range.upperBound), with: replacement) } var trimmedStart: String { return self.replacingOccurrences(of: "^[ \t]+", with: "", options: .regularExpression) } var trimmedEnd: String { return self.replacingOccurrences(of: "[ \t]+$", with: "", options: .regularExpression) } func repeating(count: Int) -> String { return Array<String>(repeating: self, count: count).joined() } func replacedRegex(pattern: String, with template: String) -> String { let regex = try! NSRegularExpression(pattern: pattern) let range = NSMakeRange(0, count) let modString = regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: template) return modString } }
fdf88509e5046898228e876196242fdd
31.092308
116
0.652445
false
false
false
false
TheDarkCode/Example-Swift-Apps
refs/heads/master
Exercises and Basic Principles/azure-search-basics/azure-search-basics/AZLocation.swift
mit
1
// // GeoJSON.swift // azure-search-basics // // Created by Mark Hamilton on 3/10/16. // Copyright © 2016 dryverless. All rights reserved. // import Foundation struct AZSLocation { private var _type: String = "Point" // "Point" private var _coordinates: [Double]! // 0.0, 0.0 private var _crs: CRS = CRS() // type: "name", properties: [name: "EPSG:4326"] var type: String { get { return _type } } var coordinates: [Double] { get { return _coordinates } } var crs: CRS { get { if let CRS: CRS = _crs ?? CRS() { return CRS } } } init(coords: [Double], crs: CRS) { self._coordinates = coords self._crs = crs } init(coords: [Double]) { self._coordinates = coords } init() { self._coordinates = [0.0,0.0] } }
acd44169abbba4eab42dde69faa6ef91
15.507042
82
0.390265
false
false
false
false
PANDA-Guide/PandaGuideApp
refs/heads/master
PandaGuide/HelpRequest.swift
gpl-3.0
1
// // HelpRequest.swift // PandaGuide // // Created by Arnaud Lenglet on 06/05/2017. // Copyright © 2017 ESTHESIX. All rights reserved. // import RealmSwift import os.log enum HelpRequestState { case Pending case Solved case Accepted } final class HelpSolution: Object { // MARK: - Properties dynamic var id: Int = 0 dynamic var answer: String = "" dynamic var userName: String = "" dynamic var validated: Bool = false // MARK: API interface struct apiProperty { static let id = "solution_id" static let help_request_id = "help_request_id" static let answer = "solution_description" static let userName = "username" static let validation = "validation" } } final class HelpRequest: Object, ApiModelProtocol { // MARK: - Properties dynamic var id: Int = 0 dynamic var question: String = "" dynamic var userId: Int = 0 dynamic var picturePath: String = "" let solutions = List<HelpSolution>() override class func primaryKey() -> String? { return "id" } // MARK: API interface struct apiProperty { static let id = "id" static let question = "problem_description" static let userId = "user_id" static let picture = "picture" } // MARK: - Instance methods private class var storageDirectoryURL: URL { return URL(string: "HelpRequests/Images")! } class func buildPictureRelativeFileURL(filename: String) -> String { return storageDirectoryURL.appendingPathComponent(filename).path } class func getPictureStorageURL(relativeFilePath: String) -> URL { let fm = FileManager.default let documentsDirectoryURL = try! fm.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let imagesDirectoryURL = documentsDirectoryURL.appendingPathComponent(storageDirectoryURL.path) try! fm.createDirectory(at: imagesDirectoryURL, withIntermediateDirectories: true, attributes: nil) let imageURL = documentsDirectoryURL.appendingPathComponent(relativeFilePath) return imageURL } func loadPicture() -> UIImage? { let url = type(of: self).getPictureStorageURL(relativeFilePath: picturePath) return UIImage(contentsOfFile: url.path) } var state: HelpRequestState { for sol in solutions { if sol.validated { return .Solved } } return .Pending } // MARK: - ApiModelProtocol func save() { let realm = try! Realm() try! realm.write { realm.add(self) } os_log("💾 HelpRequest saved in Realm. ID: '%@' / Question: '%@'", log: .default, type: .debug, "\(id)", question) } // MARK: - Static methods static func last() -> HelpRequest? { let realm = try! Realm() let helpRequests = realm.objects(HelpRequest.self) let helpRequestsCount = helpRequests.count os_log("💾 %@ HelpRequests loaded from realm found.", log: .default, type: .debug, "\(helpRequestsCount)") if helpRequestsCount > 0 { let helpRequest = helpRequests.last os_log("💾 HelpRequest #%@ loaded. Question: '%@'", log: .default, type: .debug, "\((helpRequest?.id)!)", "\((helpRequest?.question)!)") return helpRequest } else { return nil } } }
7f72297cca3e18f4b32ce85449245ddf
26.539063
147
0.612766
false
false
false
false
Swamii/adventofcode2016
refs/heads/master
Sources/day9.swift
mit
1
struct Day9 { static let repeaterStart = "(" static let repeaterRegex = Regex(pattern: "(\\d+)x(\\d+)\\)") static func expand(input: String, recurse: Bool = false) -> Int { var remainder = input var count = 0 while !remainder.isEmpty { let current = String(remainder.characters.removeFirst()) if current != repeaterStart { count += 1 continue } guard let match = repeaterRegex.firstMatch(input: remainder) else { fatalError("Could not match parens") } // Pop off repeater let timesXLength = remainder.popTo(length: match.range.length) .replacingOccurrences(of: ")", with: "") .components(separatedBy: "x") let times = Int(timesXLength[1])! let length = Int(timesXLength[0])! if recurse { let toRepeatEndIndex = remainder.index(remainder.startIndex, offsetBy: length, limitedBy: remainder.endIndex) ?? remainder.endIndex let toRepeat = remainder.substring(to: toRepeatEndIndex) let repeatedCount = expand(input: toRepeat, recurse: true) _ = remainder.popTo(length: length) count += repeatedCount * times } else { let charsToRepeat = remainder.popTo(length: length) count += charsToRepeat.characters.count * times } } return count } static func run(input: String) { print("Count = \(expand(input: input))") print("Count 2nd pass = \(expand(input: input, recurse: true))") } }
0163cb81382825c8d3c5922c96897bb9
31.75
147
0.550793
false
false
false
false
simonkim/AVCapture
refs/heads/master
AVCapture/AVEncoderVideoToolbox/VTCompressionSession.swift
apache-2.0
1
// // VTCompressionSession.swift // AVCapture // // Created by Simon Kim on 2016. 9. 10.. // Copyright © 2016 DZPub.com. All rights reserved. // import Foundation import VideoToolbox extension VTCompressionSession { /** * Creates a video toolbox compression session * @param width Width of video in pixels * @return Newly created compression session * * Compression Property Keys kVTCompressionPropertyKey_AllowFrameReordering CFBoolean optional default=true kVTCompressionPropertyKey_AverageBitrate optional CFNumber<SInt32> default=0 kVTCompressionPropertyKey_H264EntropyMode CFString optional default=unknown kVTH264EntropyMode_CAVLC kVTH264EntropyMode_CABAC kVTCompressionPropertyKey_RealTime optional CFBoolean default=unknown kVTCompressionPropertyKey_ProfileLevel CFString optional default=unknown kVTProfileLevelH264Main_AutoLevel */ static func create(width: Int32, height: Int32, codecType: CMVideoCodecType = kCMVideoCodecType_H264) -> VTCompressionSession? { let encoderSpecification: CFDictionary? = nil let sourceImageBufferAttributes: CFDictionary? = nil let compressedDataAllocator: CFAllocator? = nil let outputCallbackRefCon: UnsafeMutableRawPointer? = nil var session: VTCompressionSession? = nil let status = VTCompressionSessionCreate(kCFAllocatorDefault, width, height, codecType, encoderSpecification, sourceImageBufferAttributes, compressedDataAllocator, nil, outputCallbackRefCon, &session) if ( status != noErr ) { print("VTCompressionSessionCreate() failed: \(status)") } // else, Sesstion created successfully return session } }
c70aedb6e23e316074f9f4c193e39479
38.181818
132
0.599072
false
false
false
false
deyton/swift
refs/heads/master
stdlib/public/core/StringIndex.swift
apache-2.0
5
//===--- StringIndex.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension String { /// A position of a character or code unit in a string. public struct Index { internal var _compoundOffset : UInt64 @_versioned internal var _cache: _Cache internal typealias _UTF8Buffer = _ValidUTF8Buffer<UInt64> @_versioned internal enum _Cache { case utf16 case utf8(buffer: _UTF8Buffer) case character(stride: UInt16) case unicodeScalar(value: Unicode.Scalar) } } } /// Convenience accessors extension String.Index._Cache { @_versioned var utf16: Void? { if case .utf16 = self { return () } else { return nil } } @_versioned var utf8: String.Index._UTF8Buffer? { if case .utf8(let r) = self { return r } else { return nil } } @_versioned var character: UInt16? { if case .character(let r) = self { return r } else { return nil } } @_versioned var unicodeScalar: UnicodeScalar? { if case .unicodeScalar(let r) = self { return r } else { return nil } } } extension String.Index : Equatable { public static func == (lhs: String.Index, rhs: String.Index) -> Bool { return lhs._compoundOffset == rhs._compoundOffset } } extension String.Index : Comparable { public static func < (lhs: String.Index, rhs: String.Index) -> Bool { return lhs._compoundOffset < rhs._compoundOffset } } extension String.Index { internal typealias _Self = String.Index /// Creates a new index at the specified UTF-16 offset. /// /// - Parameter offset: An offset in UTF-16 code units. public init(encodedOffset offset: Int) { _compoundOffset = UInt64(offset << _Self._strideBits) _cache = .utf16 } @_versioned internal init(encodedOffset o: Int, transcodedOffset: Int = 0, _ c: _Cache) { _compoundOffset = UInt64(o << _Self._strideBits | transcodedOffset) _cache = c } internal static var _strideBits : Int { return 2 } internal static var _mask : UInt64 { return (1 &<< _Self._strideBits) &- 1 } internal mutating func _setEncodedOffset(_ x: Int) { _compoundOffset = UInt64(x << _Self._strideBits) } /// The offset into a string's UTF-16 encoding for this index. public var encodedOffset : Int { return Int(_compoundOffset >> _Self._strideBits) } /// The offset of this index within whatever encoding this is being viewed as @_versioned internal var _transcodedOffset : Int { get { return Int(_compoundOffset & _Self._mask) } set { let extended = UInt64(newValue) _sanityCheck(extended <= _Self._mask) _compoundOffset &= ~_Self._mask _compoundOffset |= extended } } } // SPI for Foundation extension String.Index { @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) init(_position: Int) { self.init(encodedOffset: _position) } @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) init(_offset: Int) { self.init(encodedOffset: _offset) } @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) init(_base: String.Index, in c: String.CharacterView) { self = _base } /// The integer offset of this index in UTF-16 code units. @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) var _utf16Index: Int { return self.encodedOffset } /// The integer offset of this index in UTF-16 code units. @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) var _offset: Int { return self.encodedOffset } } // backward compatibility for index interchange. extension Optional where Wrapped == String.Index { @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices") public static func ..<( lhs: String.Index?, rhs: String.Index? ) -> Range<String.Index> { return lhs! ..< rhs! } @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices") public static func ...( lhs: String.Index?, rhs: String.Index? ) -> ClosedRange<String.Index> { return lhs! ... rhs! } }
6f3f6821f8e585b7f7dbdbfae5ae6a5f
27.933735
104
0.646055
false
false
false
false
folse/Member_iOS
refs/heads/master
member/Charge.swift
mit
1
// // Charge.swift // member // // Created by Jennifer on 7/2/15. // Copyright (c) 2015 Folse. All rights reserved. // import UIKit class Charge: UITableViewController { var chargeQuantity : String = "" var customerUsername : String = "" var vaildQuantityInt : Int = 0 @IBOutlet weak var quantityTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() quantityTextField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func doneButtonAction(sender: UIBarButtonItem) { self.view.endEditing(true) charge(customerUsername, quantity : quantityTextField.text) } func charge(username:String,quantity:String) { var indicator = WIndicator.showIndicatorAddedTo(self.view, animation: true) let manager = AFHTTPRequestOperationManager() manager.responseSerializer.acceptableContentTypes = NSSet().setByAddingObject("text/html") let url = API_ROOT + "order_add" println(url) let shopId : String = NSUserDefaults.standardUserDefaults().objectForKey("shopId") as! String let params:NSDictionary = ["customer_username":username, "shop_id":shopId, "quantity":quantity, "trade_type":"1"] println(params) manager.GET(url, parameters: params as [NSObject : AnyObject], success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in println(responseObject.description) WIndicator.removeIndicatorFrom(self.view, animation: true) let responseDict = responseObject as! Dictionary<String,AnyObject> let responseCode = responseDict["resp"] as! String if responseCode == "0000"{ let data = responseObject["data"] as! Dictionary<String,AnyObject> self.vaildQuantityInt = data["vaild_quantity"] as! Int var indicator = WIndicator.showSuccessInView(self.view, text:" ", timeOut:1) var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "dismissView", userInfo: nil, repeats: false) }else { let message = responseDict["msg"] as! String let alert = UIAlertView() alert.title = "Denna operation kan inte slutföras" alert.message = message alert.addButtonWithTitle("OK") alert.show() } }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in WIndicator.removeIndicatorFrom(self.view, animation: true) let alert = UIAlertView() alert.title = "Denna operation kan inte slutföras" alert.message = "Försök igen eller kontakta vår kundtjänst. För bättre och snabbare service, rekommenderar vi att du skickar oss en skärmdump." + error.localizedDescription + "\(error.code)" alert.addButtonWithTitle("OK") alert.show() }) } func dismissView() { NSNotificationCenter.defaultCenter().postNotificationName("updateVaildQuantity", object:self.vaildQuantityInt) self.navigationController?.popViewControllerAnimated(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. } */ }
84fb32e774cf81443b5a8c21ce9679ef
37.833333
210
0.521674
false
false
false
false
secret-transaction/ScratchPad
refs/heads/master
SwiftCocoa/SwiftCocoa/DetailViewController.swift
mit
1
// // DetailViewController.swift // SwiftCocoa // // Created by Lyndon Michael Bibera on 6/21/14. // Copyright (c) 2014 Secret Transaction Inc. All rights reserved. // import UIKit class DetailViewController: UIViewController, UISplitViewControllerDelegate { @IBOutlet var detailDescriptionLabel: UILabel var masterPopoverController: UIPopoverController? = nil var detailItem: AnyObject? { didSet { // Update the view. self.configureView() if self.masterPopoverController != nil { self.masterPopoverController!.dismissPopoverAnimated(true) } } } func configureView() { // Update the user interface for the detail item. if let detail: AnyObject = self.detailItem { if let label = self.detailDescriptionLabel { label.text = detail.valueForKey("timeStamp").description } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // #pragma mark - Split view func splitViewController(splitController: UISplitViewController, willHideViewController viewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController popoverController: UIPopoverController) { barButtonItem.title = "Master" // NSLocalizedString(@"Master", @"Master") self.navigationItem.setLeftBarButtonItem(barButtonItem, animated: true) self.masterPopoverController = popoverController } func splitViewController(splitController: UISplitViewController, willShowViewController viewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) { // Called when the view is shown again in the split view, invalidating the button and popover controller. self.navigationItem.setLeftBarButtonItem(nil, animated: true) self.masterPopoverController = nil } func splitViewController(splitController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } }
99f9211da7bd6db886f21677a4b92370
37.552239
238
0.713899
false
false
false
false
Nosrac/Dictater
refs/heads/master
Dictater/NSSpeechSynthesizer.swift
mit
1
// // SpeechTimer.swift // Dictater // // Created by Kyle Carson on 9/24/15. // Copyright © 2015 Kyle Carson. All rights reserved. // import Foundation import Cocoa extension NSSpeechSynthesizer { func getSpeechDuration(string: String, callback: @escaping ((_ duration: TimeInterval) -> ())) { let timer = NSSpeechSynthesizerTimer(text: string, synthesizer: self) timer.finished = { if let duration = timer.duration { callback(duration) } } timer.start() } } class NSSpeechSynthesizerTimer : NSObject, NSSpeechSynthesizerDelegate { let synthesizer : NSSpeechSynthesizer let text : String var duration : TimeInterval? var finished : (() -> ())? private var tempFile : String? init(text: String, synthesizer: NSSpeechSynthesizer? = nil) { self.text = text self.synthesizer = synthesizer ?? NSSpeechSynthesizer() } func start() -> Bool { if let tempFile = FileManager.default.getTemporaryFile( fileExtension: "AIFF"), let synthesizer = NSSpeechSynthesizer(voice: self.synthesizer.voice()) { synthesizer.rate = self.synthesizer.rate synthesizer.delegate = self synthesizer.startSpeaking(self.text, to: URL(fileURLWithPath: tempFile)) self.tempFile = tempFile return true } return false } func speechSynthesizer(_ sender: NSSpeechSynthesizer, didFinishSpeaking finishedSpeaking: Bool) { guard let tempFile = self.tempFile else { return } if let sound = NSSound(contentsOfFile: tempFile, byReference: false) { self.duration = sound.duration self.finished?() } try! FileManager.default.removeItem(atPath: tempFile) } }
b0f0628730165c79bcc01728c2202388
21.583333
96
0.712792
false
false
false
false
FengDeng/RxGitHubAPI
refs/heads/master
RxGitHubAPI/RxGitHubAPI/YYReference.swift
apache-2.0
1
// // YYReference.swift // RxGitHubAPI // // Created by 邓锋 on 16/1/28. // Copyright © 2016年 fengdeng. All rights reserved. // import Foundation public class YYReference : NSObject{ public private(set) var ref = "" public private(set) var object_sha = "" public private(set) var object_type = "" public static override func mj_replacedKeyFromPropertyName() -> [NSObject : AnyObject]! { return ["object_sha":"object.sha","object_type":"object.type","object_url":"object.url"] } //api var url = "" var object_url = "" }
e88bc61f29fcca81f6da63b5942a6fbf
23.913043
96
0.632867
false
false
false
false
benlangmuir/swift
refs/heads/master
SwiftCompilerSources/Sources/Optimizer/TestPasses/AccessDumper.swift
apache-2.0
2
//===--- AccessDumper.swift - Dump access information --------------------===// // // 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 Basic import SIL /// Dumps access information for memory accesses (`load` and `store`) /// instructions. /// Also verifies that `AccessPath.isDistinct(from:)` is correct. This does not actually /// dumps anything, but aborts if the result is wrong. /// /// This pass is used for testing `AccessUtils`. let accessDumper = FunctionPass(name: "dump-access", { (function: Function, context: PassContext) in print("Accesses for \(function.name)") for block in function.blocks { for instr in block.instructions { switch instr { case let st as StoreInst: printAccessInfo(address: st.destination) case let load as LoadInst: printAccessInfo(address: load.operand) case let apply as ApplyInst: guard let callee = apply.referencedFunction else { break } if callee.name == "_isDistinct" { checkAliasInfo(forArgumentsOf: apply, expectDistinct: true) } else if callee.name == "_isNotDistinct" { checkAliasInfo(forArgumentsOf: apply, expectDistinct: false) } default: break } } } print("End accesses for \(function.name)") }) private struct AccessStoragePathVisitor : AccessStoragePathWalker { var walkUpCache = WalkerCache<Path>() mutating func visit(access: AccessStoragePath) { print(" Storage: \(access.storage)") print(" Path: \"\(access.path)\"") } } private func printAccessInfo(address: Value) { print("Value: \(address)") var apw = AccessPathWalker() let (ap, scope) = apw.getAccessPathWithScope(of: address) if let beginAccess = scope { print(" Scope: \(beginAccess)") } else { print(" Scope: base") } print(" Base: \(ap.base)") print(" Path: \"\(ap.projectionPath)\"") var arw = AccessStoragePathVisitor() if !arw.visitAccessStorageRoots(of: ap) { print(" no Storage paths") } } private func checkAliasInfo(forArgumentsOf apply: ApplyInst, expectDistinct: Bool) { let address1 = apply.arguments[0] let address2 = apply.arguments[1] var apw = AccessPathWalker() let path1 = apw.getAccessPath(of: address1) let path2 = apw.getAccessPath(of: address2) if path1.isDistinct(from: path2) != expectDistinct { print("wrong isDistinct result of \(apply)") } else if path2.isDistinct(from: path1) != expectDistinct { print("wrong reverse isDistinct result of \(apply)") } else { return } print("in function") print(apply.function) fatalError() }
45cd4a41e547d74324ccca60d0fc068e
30.092784
88
0.653183
false
false
false
false
JGiola/swift
refs/heads/main
test/Generics/superclass_constraint.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift -warn-redundant-requirements // RUN: not %target-swift-frontend -typecheck %s -debug-generic-signatures > %t.dump 2>&1 // RUN: %FileCheck %s < %t.dump class A { func foo() { } } class B : A { func bar() { } } class Other { } func f1<T : A>(_: T) where T : Other {} // expected-error{{no type for 'T' can satisfy both 'T : Other' and 'T : A'}} func f2<T : A>(_: T) where T : B {} // expected-warning@-1{{redundant superclass constraint 'T' : 'A'}} class GA<T> {} class GB<T> : GA<T> {} protocol P {} func f3<T, U>(_: T, _: U) where U : GA<T> {} func f4<T, U>(_: T, _: U) where U : GA<T> {} func f5<T, U : GA<T>>(_: T, _: U) {} func f6<U : GA<T>, T : P>(_: T, _: U) {} func f7<U, T>(_: T, _: U) where U : GA<T>, T : P {} func f8<T : GA<A>>(_: T) where T : GA<B> {} // expected-error{{no type for 'T' can satisfy both 'T : GA<B>' and 'T : GA<A>'}} func f9<T : GA<A>>(_: T) where T : GB<A> {} // expected-warning@-1{{redundant superclass constraint 'T' : 'GA<A>'}} func f10<T : GB<A>>(_: T) where T : GA<A> {} // expected-warning@-1{{redundant superclass constraint 'T' : 'GA<A>'}} func f11<T : GA<T>>(_: T) { } func f12<T : GA<U>, U : GB<T>>(_: T, _: U) { } func f13<T : U, U : GA<T>>(_: T, _: U) { } // expected-error{{type 'T' constrained to non-protocol, non-class type 'U'}} // rdar://problem/24730536 // Superclass constraints can be used to resolve nested types to concrete types. protocol P3 { associatedtype T } protocol P2 { associatedtype T : P3 } class C : P3 { typealias T = Int } class S : P2 { typealias T = C } // CHECK-LABEL: .superclassConformance1(t:)@ // CHECK-NEXT: Generic signature: <T where T : C> func superclassConformance1<T>(t: T) where T : C, T : P3 {} // expected-warning{{redundant conformance constraint 'C' : 'P3'}} // CHECK-LABEL: .superclassConformance2(t:)@ // CHECK-NEXT: Generic signature: <T where T : C> func superclassConformance2<T>(t: T) where T : C, T : P3 {} // expected-warning{{redundant conformance constraint 'C' : 'P3'}} protocol P4 { } class C2 : C, P4 { } // CHECK-LABEL: .superclassConformance3(t:)@ // CHECK-NEXT: Generic signature: <T where T : C2> func superclassConformance3<T>(t: T) where T : C, T : P4, T : C2 {} // expected-warning@-1{{redundant superclass constraint 'T' : 'C'}} // expected-warning@-2{{redundant conformance constraint 'T' : 'P4'}} protocol P5: A { } protocol P6: A, Other { } // expected-error {{no type for 'Self' can satisfy both 'Self : Other' and 'Self : A'}} // expected-error@-1{{multiple inheritance from classes 'A' and 'Other'}} func takeA(_: A) { } func takeP5<T: P5>(_ t: T) { takeA(t) // okay } protocol P7 { // expected-error@-1{{no type for 'Self.Assoc' can satisfy both 'Self.Assoc : Other' and 'Self.Assoc : A'}} associatedtype Assoc: A, Other } // CHECK-LABEL: .superclassConformance4@ // CHECK-NEXT: Generic signature: <T, U where T : P3, U : P3, T.[P3]T : C, T.[P3]T == U.[P3]T> func superclassConformance4<T: P3, U: P3>(_: T, _: U) where T.T: C, // expected-warning{{redundant superclass constraint 'T.T' : 'C'}} U.T: C, T.T == U.T { } // Lookup of superclass associated types from inheritance clause protocol Elementary { associatedtype Element func get() -> Element } class Classical : Elementary { func get() -> Int { return 0 } } // CHECK-LABEL: .genericFunc@ // CHECK-NEXT: Generic signature: <T, U where T : Elementary, U : Classical, T.[Elementary]Element == Int> func genericFunc<T : Elementary, U : Classical>(_: T, _: U) where T.Element == U.Element {} // Lookup within superclass constraints. protocol P8 { associatedtype B } class C8 { struct A { } } // CHECK-LABEL: .superclassLookup1@ // CHECK-NEXT: Generic signature: <T where T : C8, T : P8, T.[P8]B == C8.A> func superclassLookup1<T: C8 & P8>(_: T) where T.A == T.B { } // CHECK-LABEL: .superclassLookup2@ // CHECK-NEXT: Generic signature: <T where T : C8, T : P8, T.[P8]B == C8.A> func superclassLookup2<T: P8>(_: T) where T.A == T.B, T: C8 { } // CHECK-LABEL: .superclassLookup3@ // CHECK-NEXT: Generic signature: <T where T : C8, T : P8, T.[P8]B == C8.A> func superclassLookup3<T>(_: T) where T.A == T.B, T: C8, T: P8 { } // SR-5165 class C9 {} protocol P9 {} class C10 : C9, P9 { } protocol P10 { associatedtype A: C9 } // CHECK-LABEL: .testP10@ // CHECK-NEXT: Generic signature: <T where T : P10, T.[P10]A : C10> func testP10<T>(_: T) where T: P10, T.A: C10 { } // Nested types of generic class-constrained type parameters. protocol Tail { associatedtype E } protocol Rump : Tail { associatedtype E = Self } class Horse<T>: Rump { } func hasRedundantConformanceConstraint<X : Horse<T>, T>(_: X) where X : Rump {} // expected-warning@-1 {{redundant conformance constraint 'Horse<T>' : 'Rump'}} // SR-5862 protocol X { associatedtype Y : A } // CHECK-LABEL: .noRedundancyWarning@ // CHECK: Generic signature: <C where C : X, C.[X]Y == B> func noRedundancyWarning<C : X>(_ wrapper: C) where C.Y == B {} // Qualified lookup bug -- <https://bugs.swift.org/browse/SR-2190> protocol Init { init(x: ()) } class Base { required init(y: ()) {} } class Derived : Base {} func g<T : Init & Derived>(_: T.Type) { _ = T(x: ()) _ = T(y: ()) } // Binding a class-constrained generic parameter to a subclass existential is // not sound. struct G<T : Base> {} // expected-note@-1 2 {{requirement specified as 'T' : 'Base' [with T = Base & P]}} _ = G<Base & P>() // expected-error {{'G' requires that 'any Base & P' inherit from 'Base'}} func badClassConstrainedType(_: G<Base & P>) {} // expected-error@-1 {{'G' requires that 'any Base & P' inherit from 'Base'}} // Reduced from CoreStore in source compat suite public protocol Pony {} public class Teddy: Pony {} public struct Paddock<P: Pony> {} public struct Barn<T: Teddy> { // CHECK-LABEL: Barn.foo@ // CHECK: Generic signature: <T, S where T : Teddy> public func foo<S>(_: S, _: Barn<T>, _: Paddock<T>) {} } public class Animal { } @available(*, unavailable, message: "Not a pony") extension Animal: Pony { } public struct AnimalWrapper<Friend: Animal> { } // FIXME: Generic signature: <Friend where Friend : Animal, Friend : Pony> // Generic signature: <Friend where Friend : Animal> extension AnimalWrapper: Pony where Friend: Pony { } // expected-warning@-1{{redundant conformance constraint 'Animal' : 'Pony'}}
2206c350aa7de1e6821c740b392d8900
26.161017
125
0.625897
false
false
false
false
aidos9/my-notes
refs/heads/master
My notes/descriptionVC.swift
mit
1
// // descriptionVC.swift // My notes // // Created by Aidyn Malojer on 12/12/16. // Copyright © 2016 Aidyn Malojer. All rights reserved. // import UIKit class descriptionVC: UIViewController,UITextViewDelegate { @IBOutlet weak var descriptionText: UITextView! let defaults = UserDefaults.standard let defaultText = "Enter description here" override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Description" descriptionText.addPlaceholderLabel(defaultText) descriptionText.delegate = self descriptionText.becomeFirstResponder() } override func viewWillAppear(_ animated: Bool) { if let descText = defaults.string(forKey: "descriptionText"){ descriptionText.text = descText } textViewDidChange(descriptionText) } func textViewDidChange(_ textView: UITextView) { let placeHolderLabel = textView.viewWithTag(100) if !textView.hasText { // Get the placeholder label placeHolderLabel?.isHidden = false } else { placeHolderLabel?.isHidden = true } } override func viewWillDisappear(_ animated: Bool) { saveDesc() descriptionText.resignFirstResponder() } func saveDesc(){ if let text = descriptionText.text, text != defaultText{ defaults.set(text, forKey: "descriptionText") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
8ba19d04e4020e865636c4f76524ff21
28
106
0.648176
false
false
false
false
tikhop/TPInAppReceipt
refs/heads/master
Sources/InAppPurchase.swift
mit
1
// // InAppPurchase.swift // TPInAppReceipt // // Created by Pavel Tikhonenko on 19/01/17. // Copyright © 2017-2021 Pavel Tikhonenko. All rights reserved. // import Foundation public struct InAppPurchase { public enum `Type`: Int32 { /// Type that we can't recognize for some reason case unknown = -1 /// Type that customers purchase once. They don't expire. case nonConsumable /// Type that are depleted after one use. Customers can purchase them multiple times. case consumable /// Type that customers purchase once and that renew automatically on a recurring basis until customers decide to cancel. case nonRenewingSubscription /// Type that customers purchase and it provides access over a limited duration and don't renew automatically. Customers can purchase them again. case autoRenewableSubscription } /// The product identifier which purchase related to public var productIdentifier: String /// Product type public var productType: Type = .unknown /// Transaction identifier public var transactionIdentifier: String /// Original Transaction identifier public var originalTransactionIdentifier: String /// Purchase Date public var purchaseDate: Date /// Original Purchase Date. Returns `nil` when testing with StoreKitTest public var originalPurchaseDate: Date! = nil /// Subscription Expiration Date. Returns `nil` if the purchase has been expired (in some cases) public var subscriptionExpirationDate: Date? = nil /// Cancellation Date. Returns `nil` if the purchase is not a renewable subscription public var cancellationDate: Date? = nil /// This value is `true`if the customer’s subscription is currently in the free trial period, or `false` if not. public var subscriptionTrialPeriod: Bool = false /// This value is `true` if the customer’s subscription is currently in an introductory price period, or `false` if not. public var subscriptionIntroductoryPricePeriod: Bool = false /// A unique identifier for purchase events across devices, including subscription-renewal events. This value is the primary key for identifying subscription purchases. public var webOrderLineItemID: Int? = nil /// The value is an identifier of the subscription offer that the user redeemed. /// Returns `nil` if the user didn't use any subscription offers. public var promotionalOfferIdentifier: String? = nil /// The number of consumable products purchased /// The default value is `1` unless modified with a mutable payment. The maximum value is 10. public var quantity: Int = 1 } public extension InAppPurchase { /// A Boolean value indicating whether the purchase is renewable subscription. var isRenewableSubscription: Bool { return subscriptionExpirationDate != nil } /// Check whether the subscription is active for a specific date /// /// - Parameter date: The date in which the auto-renewable subscription should be active. /// - Returns: true if the latest auto-renewable subscription is active for the given date, false otherwise. func isActiveAutoRenewableSubscription(forDate date: Date) -> Bool { assert(isRenewableSubscription, "\(productIdentifier) is not an auto-renewable subscription.") if cancellationDate != nil { return false } guard let expirationDate = subscriptionExpirationDate else { return false } return date >= purchaseDate && date < expirationDate } }
868b0cac98a580572192d8cfe5f0d57f
34.732673
172
0.715157
false
false
false
false
RMizin/PigeonMessenger-project
refs/heads/main
FalconMessenger/ChatsControllers/ChatLogViewController+ChatHistoryFetcherDelegate.swift
gpl-3.0
1
// // ChatLogViewController+ChatHistoryFetcherDelegate.swift // FalconMessenger // // Created by Roman Mizin on 8/28/18. // Copyright © 2018 Roman Mizin. All rights reserved. // import UIKit extension ChatLogViewController: ChatLogHistoryDelegate { func chatLogHistory(isEmpty: Bool) { refreshControl.endRefreshing() } func chatLogHistory(updated newMessages: [Message]) { let numberOfMessagesInFirstSectionBeforeUpdate = groupedMessages[0].messages.count let numberOfMessagesInDataSourceBeforeUpdate = groupedMessages.compactMap { (sectionedMessage) -> Int in return sectionedMessage.messages.count }.reduce(0, +) updateRealmMessagesData(newMessages: newMessages) //saved: { let firstSectionTitle = groupedMessages.first?.title ?? "" let dates = newMessages.map({ $0.shortConvertedTimestamp ?? "" }) var datesSet = Set(dates) let rowsRange = updateFirstSection(firstSectionTitle, numberOfMessagesInDataSourceBeforeUpdate, numberOfMessagesInFirstSectionBeforeUpdate) datesSet.remove(firstSectionTitle) let sectionsRange = insertNewSections(datesSet) batchInsertMS(rowsRange: rowsRange, sectionsRange: sectionsRange) } fileprivate func updateRealmMessagesData(newMessages: [Message]) { autoreleasepool { try! realm.safeWrite { for message in newMessages { realm.create(Message.self, value: message, update: .modified) } } } } fileprivate func batchInsertMS(rowsRange: Int, sectionsRange: Int) { UIView.performWithoutAnimation { collectionView.performBatchUpdates({ var indexSet = IndexSet() Array(0..<sectionsRange).forEach({ (index) in indexSet.insert(index) }) var indexPaths = [IndexPath]() Array(0..<rowsRange).forEach({ (index) in indexPaths.append(IndexPath(row: index, section: indexSet.count)) }) globalVariables.contentSizeWhenInsertingToTop = collectionView.contentSize globalVariables.isInsertingCellsToTop = true collectionView.insertSections(indexSet) collectionView.insertItems(at: indexPaths) }, completion: { (_) in DispatchQueue.main.async { self.bottomScrollConainer.isHidden = false self.refreshControl.endRefreshing() } }) } } fileprivate func insertNewSections(_ datesSet: Set<String>) -> Int { var sectionsInserted = 0 let datesArray = Array(datesSet).sorted { (time1, time2) -> Bool in return Date.dateFromCustomString(customString: time1) < Date.dateFromCustomString(customString: time2) } let numberOfMessagesInDataSourceBeforeInsertNewSections = groupedMessages.compactMap { (sectionedMessage) -> Int in return sectionedMessage.messages.count }.reduce(0, +) for date in datesArray.reversed() { guard var messagesInSection = conversation?.messages .filter("shortConvertedTimestamp == %@", date) .sorted(byKeyPath: "timestamp", ascending: true) else { continue } let messagesInSectionCount = messagesInSection.count let maxNumberOfMessagesInChat = numberOfMessagesInDataSourceBeforeInsertNewSections + messagesToLoad let possibleNumberOfMessagesWithInsertedSection = numberOfMessagesInDataSourceBeforeInsertNewSections + messagesInSectionCount let needToLimitSection = possibleNumberOfMessagesWithInsertedSection > maxNumberOfMessagesInChat if needToLimitSection { let indexOfLastMessageToDisplay = possibleNumberOfMessagesWithInsertedSection - maxNumberOfMessagesInChat guard let timestampOfLastMessageToDisplay = messagesInSection[indexOfLastMessageToDisplay].timestamp.value else { continue } let limitedMessagesForSection = messagesInSection.filter("timestamp >= %@", timestampOfLastMessageToDisplay) messagesInSection = limitedMessagesForSection let newSection = MessageSection(messages: messagesInSection, title: date) configureBubblesTails(for: newSection.messages) groupedMessages.insert(newSection, at: 0) sectionsInserted += 1 break } else { let newSection = MessageSection(messages: messagesInSection, title: date) configureBubblesTails(for: newSection.messages) groupedMessages.insert(newSection, at: 0) sectionsInserted += 1 } } return sectionsInserted } fileprivate func updateFirstSection( _ firstSectionTitle: String, _ numberOfMessagesInDataSourceBeforeUpdate: Int, _ numberOfMessagesInFirstSectionBeforeUpdate: Int) -> Int { guard var messagesInFirstSectionAfterUpdate = conversation?.messages .filter("shortConvertedTimestamp == %@", firstSectionTitle) .sorted(byKeyPath: "timestamp", ascending: true) else { return 0 } let numberOfMessagesInFirstSectionAfterUpdate = messagesInFirstSectionAfterUpdate.count let possibleNumberOfMessagesWithUpdatedSection = (numberOfMessagesInDataSourceBeforeUpdate - numberOfMessagesInFirstSectionBeforeUpdate) + numberOfMessagesInFirstSectionAfterUpdate let maxNumberOfMessagesInChat = numberOfMessagesInDataSourceBeforeUpdate + messagesToLoad let needToLimitFirstSection = possibleNumberOfMessagesWithUpdatedSection > maxNumberOfMessagesInChat if needToLimitFirstSection { let indexOfLastMessageToDisplay = possibleNumberOfMessagesWithUpdatedSection - maxNumberOfMessagesInChat guard let timestampOfLastMessageToDisplay = messagesInFirstSectionAfterUpdate[indexOfLastMessageToDisplay].timestamp.value else { return 0 } let limitedMessagesForFirstSection = messagesInFirstSectionAfterUpdate.filter("timestamp >= %@", timestampOfLastMessageToDisplay) messagesInFirstSectionAfterUpdate = limitedMessagesForFirstSection let updatedFirstSection = MessageSection(messages: messagesInFirstSectionAfterUpdate, title: firstSectionTitle) configureBubblesTails(for: updatedFirstSection.messages) groupedMessages[0] = updatedFirstSection let numberOfMessagesInFirstSectionAfterLimiting = groupedMessages[0].messages.count return numberOfMessagesInFirstSectionAfterLimiting - numberOfMessagesInFirstSectionBeforeUpdate } else { let updatedFirstSection = MessageSection(messages: messagesInFirstSectionAfterUpdate, title: firstSectionTitle) configureBubblesTails(for: updatedFirstSection.messages) groupedMessages[0] = updatedFirstSection return numberOfMessagesInFirstSectionAfterUpdate - numberOfMessagesInFirstSectionBeforeUpdate } } }
207b4e0d0a6f738c8e24facf5f599642
42.548611
182
0.794451
false
false
false
false
debugsquad/nubecero
refs/heads/master
nubecero/Model/HomeUpload/MHomeUploadItemStatusReferenced.swift
mit
1
import UIKit class MHomeUploadItemStatusReferenced:MHomeUploadItemStatus { private let kAssetSync:String = "assetHomeSyncUploading" private let kFinished:Bool = false private let kSelectable:Bool = true init(item:MHomeUploadItem?) { let reusableIdentifier:String = VHomeUploadCellActive.reusableIdentifier let color:UIColor = UIColor.black super.init( reusableIdentifier:reusableIdentifier, item:item, assetSync:kAssetSync, finished:kFinished, selectable:kSelectable, color:color) } override init( reusableIdentifier:String, item:MHomeUploadItem?, assetSync:String, finished:Bool, selectable:Bool, color:UIColor) { fatalError() } override func process(controller:CHomeUploadSync) { super.process(controller:controller) guard let userId:MSession.UserId = MSession.sharedInstance.user.userId, let photoId:String = item?.photoId, let imageData:Data = item?.imageData else { let errorName:String = NSLocalizedString("MHomeUploadItemStatusReferenced_errorUser", comment:"") controller.errorSyncing(error:errorName) return } let parentUser:String = FStorage.Parent.user.rawValue let pathPhotos:String = "\(parentUser)/\(userId)/\(photoId)" FMain.sharedInstance.storage.saveData( path:pathPhotos, data:imageData) { [weak self, weak controller] (error:String?) in if let errorStrong:String = error { self?.imageUploadingError(controller:controller, errorName:errorStrong) } else { self?.imageUploaded(controller:controller) } } } //MARK: private private func imageUploaded(controller:CHomeUploadSync?) { guard let controllerStrong:CHomeUploadSync = controller else { return } item?.statusUploaded() controllerStrong.keepSyncing() } private func imageUploadingError(controller:CHomeUploadSync?, errorName:String) { controller?.errorSyncing(error:errorName) } }
22e76fe0a18595dc5305cc260198daed
26.21978
109
0.577715
false
false
false
false
PureSwift/SDL
refs/heads/master
Sources/SDLDemo/main.swift
mit
1
import CSDL2 import SDL print("All Render Drivers:") let renderDrivers = SDLRenderer.Driver.all if renderDrivers.isEmpty == false { print("=======") for driver in renderDrivers { do { let info = try SDLRenderer.Info(driver: driver) print("Driver:", driver.rawValue) print("Name:", info.name) print("Options:") info.options.forEach { print(" \($0)") } print("Formats:") info.formats.forEach { print(" \($0)") } if info.maximumSize.width > 0 || info.maximumSize.height > 0 { print("Maximum Size:") print(" Width: \(info.maximumSize.width)") print(" Height: \(info.maximumSize.height)") } print("=======") } catch { print("Could not get information for driver \(driver.rawValue)") } } } func main() throws { var isRunning = true try SDL.initialize(subSystems: [.video]) defer { SDL.quit() } let windowSize = (width: 600, height: 480) let window = try SDLWindow(title: "SDLDemo", frame: (x: .centered, y: .centered, width: windowSize.width, height: windowSize.height), options: [.resizable, .shown]) let framesPerSecond = try window.displayMode().refreshRate print("Running at \(framesPerSecond) FPS") // renderer let renderer = try SDLRenderer(window: window) var frame = 0 var event = SDL_Event() var needsDisplay = true while isRunning { SDL_PollEvent(&event) // increment ticker frame += 1 let startTime = SDL_GetTicks() let eventType = SDL_EventType(rawValue: event.type) switch eventType { case SDL_QUIT, SDL_APP_TERMINATING: isRunning = false case SDL_WINDOWEVENT: if event.window.event == UInt8(SDL_WINDOWEVENT_SIZE_CHANGED.rawValue) { needsDisplay = true } default: break } if needsDisplay { try renderer.setDrawColor(red: 0xFF, green: 0xFF, blue: 0xFF, alpha: 0xFF) try renderer.clear() let surface = try SDLSurface(rgb: (0, 0, 0, 0), size: (width: 1, height: 1), depth: 32) let color = SDLColor( format: try SDLPixelFormat(format: .argb8888), red: 25, green: 50, blue: .max, alpha: .max / 2 ) try surface.fill(color: color) let surfaceTexture = try SDLTexture(renderer: renderer, surface: surface) try surfaceTexture.setBlendMode([.alpha]) try renderer.copy(surfaceTexture, destination: SDL_Rect(x: 100, y: 100, w: 200, h: 200)) // render to screen renderer.present() print("Did redraw screen") needsDisplay = false } // sleep to save energy let frameDuration = SDL_GetTicks() - startTime if frameDuration < 1000 / UInt32(framesPerSecond) { SDL_Delay((1000 / UInt32(framesPerSecond)) - frameDuration) } } } do { try main() } catch let error as SDLError { print("Error: \(error.debugDescription)") exit(EXIT_FAILURE) } catch { print("Error: \(error)") exit(EXIT_FAILURE) }
c3fe0b78063879c206cc9af930032162
29.232759
119
0.529227
false
false
false
false
BlueTatami/Angle
refs/heads/master
AngleTests/AngleTests.swift
mit
1
// // AngleTests.swift // AngleTests // // Created by Alexandre Lopoukhine on 09/12/2015. // Copyright © 2015 bluetatami. All rights reserved. // import XCTest @testable import Angle class AngleTests: XCTestCase { func testConvertDegreesToRadians() { let degrees = 180.0 let radians = Angle.degreesToRadians(degrees) XCTAssert(radians == Double.pi) } func testConvertRadiansToDegrees() { let radians = Double.pi let degrees = Angle.radiansToDegrees(radians) XCTAssert(degrees == 180.0) } func testDegreesSetter() { var angle = Angle(degrees: 0.0) angle.degrees = 40.0 XCTAssert(angle.degrees == 40.0) } func testRadiansGetter() { let angle = Angle(degrees: 90.0) XCTAssert(angle.radians == Double.pi / 2) } func testRadiansSetter() { var angle = Angle(degrees: 40.0) angle.radians = Double.pi / 2 XCTAssert(angle.degrees == 90.0) } // Tests for correct initialisation from angle less than -360° func testNormaliseBigNegative() { let degrees = -1000.0 var angle = Angle(degrees: degrees) XCTAssert(angle.degrees == 80.0) angle.degrees = degrees XCTAssert(angle.degrees == 80.0) } // Tests for correct initialisation from angle between -360° and 0° func testNormaliseSmallNegative() { let degrees = -200.0 let angle = Angle(degrees: degrees) XCTAssert(angle.degrees == 160.0) } // Tests for correct initialisation from 0° func testNormaliseZero() { let degrees = 0.0 let angle = Angle(degrees: degrees) XCTAssert(angle.degrees == 0.0) } // Tests for correct initialisation from angle less than -360° func testNormaliseWithinRangeNegative() { let degrees = 80.0 let angle = Angle(degrees: degrees) XCTAssert(angle.degrees == 80.0) } // Tests for correct initialisation from 360° func testNormaliseThreeSixty() { let degrees = 360.0 let angle = Angle(degrees: degrees) XCTAssert(angle.degrees == 0.0) } // Tests for correct initialisation from angle larger than or equal to 360° func testNormaliseOutOfRange() { let degrees = 1000.0 let angle = Angle(degrees: degrees) XCTAssert(angle.degrees == 280.0) } // Tests for correct initialisation from pi / 2 radians func testInitialiseFromRadians() { let radians = Double.pi / 2 let angle = Angle(radians: radians) XCTAssert(angle.degrees == 90.0) } // MARK: CustomStringConvertible tests func testDescriptionString() { let angle = Angle(degrees: 40.0) XCTAssert("40.0°" == angle.description) } // MARK: Operator tests // Tests that angle negation works as intended, modulo 360° func testNegateNumber() { let negated = -Angle(degrees: 90.0) XCTAssert(negated.degrees == 270.0) } // Tests for correct result in addition of two constant angles func testAddAngles() { let first = Angle(degrees: 30.0) let second = Angle(degrees: 40.0) let sum = first + second XCTAssert(sum.degrees == 70.0) } func testSubtractAngles() { let first = Angle(degrees: 30.0) let second = Angle(degrees: 40.0) let sum = first - second XCTAssert(sum.degrees == 350.0) } func testMultiplyLeft() { let left = 2.0 let right = Angle(degrees: 20.0) let sum = left * right XCTAssert(sum.degrees == 40.0) } func testMultiplyRight() { let left = Angle(degrees: 20.0) let right = 2.0 let sum = left * right XCTAssert(sum.degrees == 40.0) } func testDivide() { let left = Angle(degrees: 40.0) let right = 2.0 let sum = left / right XCTAssert(sum.degrees == 20.0) } func testIncrementAngle() { var first = Angle(degrees: 40.0) let second = Angle(degrees: 30.0) first += second XCTAssert(first.degrees == 70.0) } func testDecrementAngle() { var first = Angle(degrees: 40.0) let second = Angle(degrees: 30.0) first -= second XCTAssert(first.degrees == 10.0) } func testMultiplyMutateAngle() { var first = Angle(degrees: 40.0) let second = 3.0 first *= second XCTAssert(first.degrees == 120.0) } func testDivideMutateAngle() { var first = Angle(degrees: 40.0) let second = 4.0 first /= second XCTAssert(first.degrees == 10.0) } }
4cbcb2520d6f6634c0e64d54295b5773
24.346341
79
0.540223
false
true
false
false
karivalkama/Agricola-Scripture-Editor
refs/heads/master
TranslationEditor/ScrollViewExtension.swift
mit
1
// // ScrollViewExtension.swift // TranslationEditor // // Created by Mikko Hilpinen on 10.2.2017. // Copyright © 2017 SIL. All rights reserved. // import Foundation // Some code references Alexander Dvornikov's answer at // http://stackoverflow.com/questions/7706152/iphone-knowing-if-a-uiscrollview-reached-the-top-or-bottom extension UIScrollView { // Checks whether the scroll view is at the top var isAtTop: Bool { return contentOffset.y <= verticalOffsetForTop } // Checks whether the scroll view is scrolled to the bottom var isAtBottom: Bool { return contentOffset.y >= verticalOffsetForBottom } // The maximum offset that is considered to be at the top of the scrollview var verticalOffsetForTop: CGFloat { let topInset = contentInset.top return -topInset } // The vertical offset that is considered to be at the bottom of the scroll view var verticalOffsetForBottom: CGFloat { let scrollViewHeight = bounds.height let scrollContentSizeHeight = contentSize.height let bottomInset = contentInset.bottom let scrollViewBottomOffset = scrollContentSizeHeight + bottomInset - scrollViewHeight return scrollViewBottomOffset } // The height of the area in this table view that displays content // (Insets do not count to this height) var visibleContentHeight: CGFloat { return frame.height - contentInset.top - contentInset.bottom } // Scrolls the view to the top func scrollToTop(animated: Bool = true) { setContentOffset(CGPoint(x: contentOffset.x, y: verticalOffsetForTop), animated: animated) } // Scrolls the view to the bottom func scrollToBottom(animated: Bool = true) { setContentOffset(CGPoint(x: contentOffset.x, y: verticalOffsetForBottom), animated: animated) } }
1855db7513bbad8ff7041b0e4171ffb4
27.209677
104
0.759291
false
false
false
false
drscotthawley/add-menu-popover-demo
refs/heads/master
PopUpMenuTest/AppDelegate.swift
gpl-2.0
1
// // AppDelegate.swift // PopUpMenuTest // // Created by Scott Hawley on 8/31/15. // Copyright © 2015 Scott Hawley. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.scotthawley.com.PopUpMenuTest" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("PopUpMenuTest", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
ce155268dd54abd0fb30ea5664b9c39e
54.09009
291
0.72036
false
false
false
false
KyleLeneau/swift-mvvm-examples
refs/heads/master
swift-mvvm-examples/ViewModel/SimpleListViewModel.swift
apache-2.0
1
// // SimpleListViewModel.swift // swift-mvvm-examples // // Created by Kyle LeNeau on 1/24/15. // Copyright (c) 2015 Kyle LeNeau. All rights reserved. // import Foundation import ReactiveSwift import ReactiveCocoa public class SimpleListItemViewModel { public let displayName = MutableProperty<String?>(nil) public init(name: String) { displayName.value = name } } public class SimpleListViewModel { public enum Error: Swift.Error { case badItem } public let items = MutableProperty([SimpleListItemViewModel]()) public let itemToAdd = MutableProperty<String?>(nil) public lazy var addEnabled: Property<Bool> = { return Property(initial: false, then: self.itemToAdd.producer.map { $0 != nil && !$0!.isEmpty }) }() public lazy var addItemAction: Action<(), (), Error> = { return Action<(), (), Error>(enabledIf: self.addEnabled, execute: { x in guard let value = self.itemToAdd.value else { return SignalProducer(error: .badItem) } self.items.value.append(SimpleListItemViewModel(name: value)) self.itemToAdd.value = nil return SignalProducer.empty }) }() }
4d537d75d59d4808ae630bb6536e3ba4
26.543478
104
0.625888
false
false
false
false
midoks/Swift-Learning
refs/heads/master
EampleApp/EampleApp/Controllers/User/UserSudokuViewController.swift
apache-2.0
1
// // UserSudokuViewController.swift // // Created by midoks on 15/8/20. // Copyright © 2015年 midoks. All rights reserved. // import UIKit //九宫格视图 class UserSudokuViewController: UIViewController, SudokuViewDelegate { var tmpBarColor:UIColor? override func viewDidLoad() { super.viewDidLoad() self.title = "九宫格验证" self.view.backgroundColor = UIColor(red: 35/255.0, green: 39/255.0, blue: 54/255.0, alpha: 1) tmpBarColor = UINavigationBar.appearance().barTintColor UINavigationBar.appearance().barTintColor = UIColor(red: 35/255.0, green: 39/255.0, blue: 54/255.0, alpha: 1) let leftButton = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(UserSudokuViewController.close(_:))) self.navigationItem.leftBarButtonItem = leftButton let sudoku = SudokuView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)) sudoku.delegate = self //设置正确的密码 //如果正在设置密码,就不需要填写了 sudoku.setPwd("012345678") self.view.addSubview(sudoku) } func SudokuViewFail(_ pwd: NSString, status: NSString) { NSLog("pwd:%@, status:%@", pwd, status) } func SudokuViewOk(_ pwd: NSString, status: NSString) { NSLog("pwd:%@, status:%@", pwd, status) if("end" == status){ noticeText("您的结果", text: pwd as NSString, time: 2.0) } } //离开本页面 override func viewWillDisappear(_ animated: Bool) { UINavigationBar.appearance().barTintColor = tmpBarColor } //关闭 func close(_ button: UIButton){ self.dismiss(animated: true) { () -> Void in //print("close") } } }
edfcff99a96aab2e5bc0a42d56d99baf
27.106061
157
0.593531
false
false
false
false
CosmicMind/Material
refs/heads/develop
Pods/Material/Sources/iOS/Layout/Layout.swift
gpl-3.0
3
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import Motion /// A protocol that's conformed by UIView and UILayoutGuide. public protocol Constraintable: class { } @available(iOS 9.0, *) extension UILayoutGuide: Constraintable { } extension UIView: Constraintable { } /// Layout extension for UIView. public extension UIView { /** Used to chain layout constraints on a child context. - Parameter child: A child UIView to layout. - Returns: A Layout instance. */ func layout(_ child: UIView) -> Layout { if self != child.superview { addSubview(child) } child.translatesAutoresizingMaskIntoConstraints = false return child.layout } /// Layout instance for the view. var layout: Layout { return Layout(constraintable: self) } /// Anchor instance for the view. var anchor: LayoutAnchor { return LayoutAnchor(constraintable: self) } /** Anchor instance for safeAreaLayoutGuide. Below iOS 11, it will be same as view.anchor. */ var safeAnchor: LayoutAnchor { if #available(iOS 11.0, *) { return LayoutAnchor(constraintable: safeAreaLayoutGuide) } else { return anchor } } } private extension NSLayoutConstraint { /** Checks if the constraint is equal to given constraint. - Parameter _ other: An NSLayoutConstraint. - Returns: A Bool indicating whether constraints are equal. */ func equalTo(_ other: NSLayoutConstraint) -> Bool { return firstItem === other.firstItem && secondItem === other.secondItem && firstAttribute == other.firstAttribute && secondAttribute == other.secondAttribute && relation == other.relation } } /// A memory reference to the lastConstraint of UIView. private var LastConstraintKey: UInt8 = 0 private extension UIView { /** The last consntraint that's created by Layout system. Used to set multiplier/priority on the last constraint. */ var lastConstraint: NSLayoutConstraint? { get { return AssociatedObject.get(base: self, key: &LastConstraintKey) { nil } } set(value) { AssociatedObject.set(base: self, key: &LastConstraintKey, value: value) } } } public struct Layout { /// A weak reference to the constraintable. public weak var constraintable: Constraintable? /// Parent view of the view. var parent: UIView? { return (constraintable as? UIView)?.superview } /// Returns the view that is being laied out. public var view: UIView? { var v = constraintable as? UIView if #available(iOS 9.0, *), v == nil { v = (constraintable as? UILayoutGuide)?.owningView } return v } /** An initializer taking Constraintable. - Parameter view: A Constraintable. */ init(constraintable: Constraintable) { self.constraintable = constraintable } } public extension Layout { /** Sets multiplier of the last created constraint. Not meant for updating the multiplier as it will re-create the constraint. - Parameter _ multiplier: A CGFloat multiplier. - Returns: A Layout instance to allow chaining. */ @discardableResult func multiply(_ multiplier: CGFloat) -> Layout { return resetLastConstraint(multiplier: multiplier) } /** Sets priority of the last created constraint. Not meant for updating the multiplier as it will re-create the constraint. - Parameter _ value: A Float priority. - Returns: A Layout instance to allow chaining. */ @discardableResult func priority(_ value: Float) -> Layout { return priority(.init(rawValue: value)) } /** Sets priority of the last created constraint. Not meant for updating the priority as it will re-create the constraint. - Parameter _ priority: A UILayoutPriority. - Returns: A Layout instance to allow chaining. */ @discardableResult func priority(_ priority: UILayoutPriority) -> Layout { return resetLastConstraint(priority: priority) } /** Removes the last created constraint and creates new one with the new multiplier and/or priority (if provided). - Parameter multiplier: An optional CGFloat. - Parameter priority: An optional UILayoutPriority. - Returns: A Layout instance to allow chaining. */ private func resetLastConstraint(multiplier: CGFloat? = nil, priority: UILayoutPriority? = nil) -> Layout { guard let v = view?.lastConstraint, v.isActive else { return self } v.isActive = false let newV = NSLayoutConstraint(item: v.firstItem as Any, attribute: v.firstAttribute, relatedBy: v.relation, toItem: v.secondItem, attribute: v.secondAttribute, multiplier: multiplier ?? v.multiplier, constant: v.constant) newV.priority = priority ?? v.priority newV.isActive = true view?.lastConstraint = newV return self } } public extension Layout { /** Constraints top of the view to its parent's. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func top(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.top, relationer: relationer, constant: offset) } /** Constraints left of the view to its parent's. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func left(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.left, relationer: relationer, constant: offset) } /** Constraints right of the view to its parent. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func right(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.right, relationer: relationer, constant: -offset) } /** Constraints leading of the view to its parent's. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func leading(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.leading, relationer: relationer, constant: offset) } /** Constraints trailing of the view to its parent. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func trailing(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.trailing, relationer: relationer, constant: -offset) } /** Constraints bottom of the view to its parent's. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottom(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.bottom, relationer: relationer, constant: -offset) } /** Constraints top-left of the view to its parent's. - Parameter top: A CGFloat offset for top. - Parameter left: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func topLeft(top: CGFloat = 0, left: CGFloat = 0) -> Layout { return constraint(.topLeft, constants: top, left) } /** Constraints top-right of the view to its parent's. - Parameter top: A CGFloat offset for top. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func topRight(top: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.topRight, constants: top, -right) } /** Constraints bottom-left of the view to its parent's. - Parameter bottom: A CGFloat offset for bottom. - Parameter left: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomLeft(bottom: CGFloat = 0, left: CGFloat = 0) -> Layout { return constraint(.bottomLeft, constants: -bottom, left) } /** Constraints bottom-right of the view to its parent's. - Parameter bottom: A CGFloat offset for bottom. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomRight(bottom: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.bottomRight, constants: -bottom, -right) } /** Constraints left and right of the view to its parent's. - Parameter left: A CGFloat offset for left. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func leftRight(left: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.leftRight, constants: left, -right) } /** Constraints top-leading of the view to its parent's. - Parameter top: A CGFloat offset for top. - Parameter leading: A CGFloat offset for leading. - Returns: A Layout instance to allow chaining. */ @discardableResult func topLeading(top: CGFloat = 0, leading: CGFloat = 0) -> Layout { return constraint(.topLeading, constants: top, leading) } /** Constraints top-trailing of the view to its parent's. - Parameter top: A CGFloat offset for top. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func topTrailing(top: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.topTrailing, constants: top, -trailing) } /** Constraints bottom-leading of the view to its parent's. - Parameter bottom: A CGFloat offset for bottom. - Parameter leading: A CGFloat offset for leading. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomLeading(bottom: CGFloat = 0, leading: CGFloat = 0) -> Layout { return constraint(.bottomLeading, constants: -bottom, leading) } /** Constraints bottom-trailing of the view to its parent's. - Parameter bottom: A CGFloat offset for bottom. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomTrailing(bottom: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.bottomTrailing, constants: -bottom, -trailing) } /** Constraints leading and trailing of the view to its parent's. - Parameter leading: A CGFloat offset for leading. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func leadingTrailing(leading: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.leadingTrailing, constants: leading, -trailing) } /** Constraints top and bottom of the view to its parent's. - Parameter top: A CGFloat offset for top. - Parameter bottom: A CGFloat offset for bottom. - Returns: A Layout instance to allow chaining. */ @discardableResult func topBottom(top: CGFloat = 0, bottom: CGFloat = 0) -> Layout { return constraint(.topBottom, constants: top, -bottom) } /** Constraints center of the view to its parent's. - Parameter offsetX: A CGFloat offset for horizontal center. - Parameter offsetY: A CGFloat offset for vertical center. - Returns: A Layout instance to allow chaining. */ @discardableResult func center(offsetX: CGFloat = 0, offsetY: CGFloat = 0) -> Layout { return constraint(.center, constants: offsetX, offsetY) } /** Constraints horizontal center of the view to its parent's. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerX(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.centerX, relationer: relationer, constant: offset) } /** Constraints vertical center of the view to its parent's. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerY(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.centerY, relationer: relationer, constant: offset) } /** Constraints width of the view to its parent's. - Parameter offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func width(offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.width, relationer: relationer, constant: offset) } /** Constraints height of the view to its parent's. - Parameter offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func height(offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.height, relationer: relationer, constant: offset) } /** Constraints edges of the view to its parent's. - Parameter top: A CGFloat offset for top. - Parameter left: A CGFloat offset for left. - Parameter bottom: A CGFloat offset for bottom. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func edges(top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.edges, constants: top, left, -bottom, -right) } } public extension Layout { /** Constraints top of the view to its parent's safeArea. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func topSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.top, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints left of the view to its parent's safeArea. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func leftSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.left, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints right of the view to its parent. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func rightSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.right, relationer: relationer, constant: -offset, useSafeArea: true) } /** Constraints leading of the view to its parent's safeArea. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func leadingSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.leading, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints trailing of the view to its parent. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func trailingSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.trailing, relationer: relationer, constant: -offset, useSafeArea: true) } /** Constraints bottom of the view to its parent's safeArea. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.bottom, relationer: relationer, constant: -offset, useSafeArea: true) } /** Constraints top-left of the view to its parent's safeArea. - Parameter top: A CGFloat offset for top. - Parameter left: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func topLeftSafe(top: CGFloat = 0, left: CGFloat = 0) -> Layout { return constraint(.topLeft, constants: top, left, useSafeArea: true) } /** Constraints top-right of the view to its parent's safeArea. - Parameter top: A CGFloat offset for top. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func topRightSafe(top: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.topRight, constants: top, -right, useSafeArea: true) } /** Constraints bottom-left of the view to its parent's safeArea. - Parameter bottom: A CGFloat offset for bottom. - Parameter left: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomLeftSafe(bottom: CGFloat = 0, left: CGFloat = 0) -> Layout { return constraint(.bottomLeft, constants: -bottom, left, useSafeArea: true) } /** Constraints bottom-right of the view to its parent's safeArea. - Parameter bottom: A CGFloat offset for bottom. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomRightSafe(bottom: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.bottomRight, constants: -bottom, -right, useSafeArea: true) } /** Constraints left and right of the view to its parent's safeArea. - Parameter left: A CGFloat offset for left. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func leftRightSafe(left: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.leftRight, constants: left, -right, useSafeArea: true) } /** Constraints top-leading of the view to its parent's safeArea. - Parameter top: A CGFloat offset for top. - Parameter leading: A CGFloat offset for leading. - Returns: A Layout instance to allow chaining. */ @discardableResult func topLeadingSafe(top: CGFloat = 0, leading: CGFloat = 0) -> Layout { return constraint(.topLeading, constants: top, leading, useSafeArea: true) } /** Constraints top-trailing of the view to its parent's safeArea. - Parameter top: A CGFloat offset for top. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func topTrailingSafe(top: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.topTrailing, constants: top, -trailing, useSafeArea: true) } /** Constraints bottom-leading of the view to its parent's safeArea. - Parameter bottom: A CGFloat offset for bottom. - Parameter leading: A CGFloat offset for leading. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomLeadingSafe(bottom: CGFloat = 0, leading: CGFloat = 0) -> Layout { return constraint(.bottomLeading, constants: -bottom, leading, useSafeArea: true) } /** Constraints bottom-trailing of the view to its parent's safeArea. - Parameter bottom: A CGFloat offset for bottom. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomTrailingSafe(bottom: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.bottomTrailing, constants: -bottom, -trailing, useSafeArea: true) } /** Constraints leading and trailing of the view to its parent's safeArea. - Parameter leading: A CGFloat offset for leading. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func leadingTrailingSafe(leading: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.leadingTrailing, constants: leading, -trailing, useSafeArea: true) } /** Constraints top and bottom of the view to its parent's safeArea. - Parameter top: A CGFloat offset for top. - Parameter bottom: A CGFloat offset for bottom. - Returns: A Layout instance to allow chaining. */ @discardableResult func topBottomSafe(top: CGFloat = 0, bottom: CGFloat = 0) -> Layout { return constraint(.topBottom, constants: top, -bottom, useSafeArea: true) } /** Constraints center of the view to its parent's safeArea. - Parameter offsetX: A CGFloat offset for horizontal center. - Parameter offsetY: A CGFloat offset for vertical center. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerSafe(offsetX: CGFloat = 0, offsetY: CGFloat = 0) -> Layout { return constraint(.center, constants: offsetX, offsetY, useSafeArea: true) } /** Constraints horizontal center of the view to its parent's safeArea. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerXSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.centerX, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints vertical center of the view to its parent's safeArea. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerYSafe(_ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.centerY, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints width of the view to its parent's safeArea. - Parameter offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func widthSafe(offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.width, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints height of the view to its parent's safeArea. - Parameter offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func heightSafe(offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.height, relationer: relationer, constant: offset, useSafeArea: true) } /** Constraints edges of the view to its parent's safeArea. - Parameter top: A CGFloat offset for top. - Parameter left: A CGFloat offset for left. - Parameter bottom: A CGFloat offset for bottom. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func edgesSafe(top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.edges, constants: top, left, -bottom, -right, useSafeArea: true) } } public extension Layout { /** Constraints width of the view to a constant value. - Parameter _ width: A CGFloat value. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func width(_ width: CGFloat, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.constantWidth, relationer: relationer, constants: width) } /** Constraints height of the view to a constant value. - Parameter _ height: A CGFloat value. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func height(_ height: CGFloat, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.constantHeight, relationer: relationer, constants: height) } /** The width and height of the view to its parent's. - Parameter _ size: A CGSize offset. - Returns: A Layout instance to allow chaining. */ @discardableResult func size(_ size: CGSize) -> Layout { return width(size.width).height(size.height) } } public extension Layout { /** Constraints top of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func top(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.top, to: anchor, relationer: relationer, constant: offset) } /** Constraints left of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func left(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.left, to: anchor, relationer: relationer, constant: offset) } /** Constraints right of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func right(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.right, to: anchor, relationer: relationer, constant: -offset) } /** Constraints leading of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func leading(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.leading, to: anchor, relationer: relationer, constant: offset) } /** Constraints trailing of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func trailing(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.trailing, to: anchor, relationer: relationer, constant: -offset) } /** Constraints bottom of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottom(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.bottom, to: anchor, relationer: relationer, constant: -offset) } /** Constraints top-leading of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter top: A CGFloat offset for top. - Parameter leading: A CGFloat offset for leading. - Returns: A Layout instance to allow chaining. */ @discardableResult func topLeading(_ anchor: LayoutAnchorable, top: CGFloat = 0, leading: CGFloat = 0) -> Layout { return constraint(.topLeading, to: anchor, constants: top, leading) } /** Constraints top-trailing of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter top: A CGFloat offset for top. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func topTrailing(_ anchor: LayoutAnchorable, top: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.topTrailing, to: anchor, constants: top, -trailing) } /** Constraints bottom-leading of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter bottom: A CGFloat offset for bottom. - Parameter leading: A CGFloat offset for leading. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomLeading(_ anchor: LayoutAnchorable, bottom: CGFloat = 0, leading: CGFloat = 0) -> Layout { return constraint(.bottomLeading, to: anchor, constants: -bottom, leading) } /** Constraints bottom-trailing of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter bottom: A CGFloat offset for bottom. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomTrailing(_ anchor: LayoutAnchorable, bottom: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.bottomTrailing, to: anchor, constants: -bottom, -trailing) } /** Constraints leading and trailing of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter leading: A CGFloat offset for leading. - Parameter trailing: A CGFloat offset for trailing. - Returns: A Layout instance to allow chaining. */ @discardableResult func leadingTrailing(_ anchor: LayoutAnchorable, leading: CGFloat = 0, trailing: CGFloat = 0) -> Layout { return constraint(.leadingTrailing, to: anchor, constants: leading, -trailing) } /** Constraints top-left of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter top: A CGFloat offset for top. - Parameter left: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func topLeft(_ anchor: LayoutAnchorable, top: CGFloat = 0, left: CGFloat = 0) -> Layout { return constraint(.topLeft, to: anchor, constants: top, left) } /** Constraints top-right of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter top: A CGFloat offset for top. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func topRight(_ anchor: LayoutAnchorable, top: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.topRight, to: anchor, constants: top, -right) } /** Constraints bottom-left of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter bottom: A CGFloat offset for bottom. - Parameter left: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomLeft(_ anchor: LayoutAnchorable, bottom: CGFloat = 0, left: CGFloat = 0) -> Layout { return constraint(.bottomLeft, to: anchor, constants: -bottom, left) } /** Constraints bottom-right of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter bottom: A CGFloat offset for bottom. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func bottomRight(_ anchor: LayoutAnchorable, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.bottomRight, to: anchor, constants: -bottom, -right) } /** Constraints left and right of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter left: A CGFloat offset for left. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func leftRight(_ anchor: LayoutAnchorable, left: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.leftRight, to: anchor, constants: left, -right) } /** Constraints top and bottom of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter top: A CGFloat offset for top. - Parameter bottom: A CGFloat offset for bottom. - Returns: A Layout instance to allow chaining. */ @discardableResult func topBottom(_ anchor: LayoutAnchorable, top: CGFloat = 0, bottom: CGFloat = 0) -> Layout { return constraint(.topBottom, to: anchor, constants: top, -bottom) } /** Constraints center of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter offsetX: A CGFloat offset for horizontal center. - Parameter offsetY: A CGFloat offset for vertical center. - Returns: A Layout instance to allow chaining. */ @discardableResult func center(_ anchor: LayoutAnchorable, offsetX: CGFloat = 0, offsetY: CGFloat = 0) -> Layout { return constraint(.center, to: anchor, constants: offsetX, offsetY) } /** Constraints horizontal center of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerX(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.centerX, to: anchor, relationer: relationer, constant: offset) } /** Constraints vertical center of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func centerY(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.centerY, to: anchor, relationer: relationer, constant: offset) } /** Constraints width of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func width(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.width, to: anchor, relationer: relationer, constant: offset) } /** Constraints height of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter _ offset: A CGFloat offset. - Parameter _ relationer: A LayoutRelationer. - Returns: A Layout instance to allow chaining. */ @discardableResult func height(_ anchor: LayoutAnchorable, _ offset: CGFloat = 0, _ relationer: LayoutRelationer = LayoutRelationerStruct.equal) -> Layout { return constraint(.height, to: anchor, relationer: relationer, constant: offset) } /** Constraints edges of the view to the given anchor. - Parameter _ anchor: A LayoutAnchorable. - Parameter top: A CGFloat offset for top. - Parameter left: A CGFloat offset for left. - Parameter bottom: A CGFloat offset for bottom. - Parameter right: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func edges(_ anchor: LayoutAnchorable, top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout { return constraint(.edges, to: anchor, constants: top, left, -bottom, -right) } } public extension Layout { /** Constraints the object and sets it's anchor to `bottom`. - Parameter _ view: A UIView. - Parameter offset: A CGFloat offset for top. - Returns: A Layout instance to allow chaining. */ @discardableResult func below(_ view: UIView, _ offset: CGFloat = 0) -> Layout { return top(view.anchor.bottom, offset) } /** Constraints the object and sets it's anchor to `top`. - Parameter _ view: A UIView. - Parameter offset: A CGFloat offset for bottom. - Returns: A Layout instance to allow chaining. */ @discardableResult func above(_ view: UIView, _ offset: CGFloat = 0) -> Layout { return bottom(view.anchor.top, offset) } /** Constraints the object and sets it's anchor to `before/left`. - Parameter _ view: A UIView. - Parameter offset: A CGFloat offset for right. - Returns: A Layout instance to allow chaining. */ @discardableResult func before(_ view: UIView, _ offset: CGFloat = 0) -> Layout { return right(view.anchor.left, offset) } /** Constraints the object and sets it's anchor to `after/right`. - Parameter _ view: A UIView. - Parameter offset: A CGFloat offset for left. - Returns: A Layout instance to allow chaining. */ @discardableResult func after(_ view: UIView, _ offset: CGFloat = 0) -> Layout { return left(view.anchor.right, offset) } /** Constraints the object and sets it's aspect. - Parameter ratio: A CGFloat ratio multiplier. - Returns: A Layout instance to allow chaining. */ @discardableResult func aspect(_ ratio: CGFloat = 1) -> Layout { return height(view!.anchor.width).multiply(ratio) } } private extension Layout { /** Constraints the view to its parent according to the provided attribute. If the constraint already exists, will update its constant. - Parameter _ attribute: A LayoutAttribute. - Parameter _ relationer: A LayoutRelationer. - Parameter constant: A CGFloat. - Returns: A Layout instance to allow chaining. */ func constraint(_ attribute: LayoutAttribute, relationer: LayoutRelationer = LayoutRelationerStruct.equal, constant: CGFloat, useSafeArea: Bool = false) -> Layout { return constraint([attribute], relationer: relationer, constants: constant, useSafeArea: useSafeArea) } /** Constraints the view to its parent according to the provided attributes. If any of the constraints already exists, will update its constant. - Parameter _ attributes: An array of LayoutAttribute. - Parameter _ relationer: A LayoutRelationer. - Parameter constants: A list of CGFloat. - Returns: A Layout instance to allow chaining. */ func constraint(_ attributes: [LayoutAttribute], relationer: LayoutRelationer = LayoutRelationerStruct.equal, constants: CGFloat..., useSafeArea: Bool = false) -> Layout { var attributes = attributes var anchor: LayoutAnchor! if attributes == .constantHeight || attributes == .constantWidth { attributes.removeLast() anchor = LayoutAnchor(constraintable: nil, attributes: [.notAnAttribute]) } else { guard parent != nil else { fatalError("[Material Error: Constraint requires view to have parent.") } anchor = LayoutAnchor(constraintable: useSafeArea ? parent?.safeAnchor.constraintable : parent, attributes: attributes) } return constraint(attributes, to: anchor, relationer: relationer, constants: constants) } /** Constraints the view to the given anchor according to the provided attribute. If the constraint already exists, will update its constant. - Parameter _ attribute: A LayoutAttribute. - Parameter to anchor: A LayoutAnchorable. - Parameter relation: A LayoutRelation between anchors. - Parameter constant: A CGFloat. - Returns: A Layout instance to allow chaining. */ func constraint(_ attribute: LayoutAttribute, to anchor: LayoutAnchorable, relationer: LayoutRelationer = LayoutRelationerStruct.equal, constant: CGFloat) -> Layout { return constraint([attribute], to: anchor, relationer: relationer, constants: constant) } /** Constraints the view to the given anchor according to the provided attributes. If any of the constraints already exists, will update its constant. - Parameter _ attributes: An array of LayoutAttribute. - Parameter to anchor: A LayoutAnchorable. - Parameter relation: A LayoutRelation between anchors. - Parameter constants: A list of CGFloat. - Returns: A Layout instance to allow chaining. */ func constraint(_ attributes: [LayoutAttribute], to anchor: LayoutAnchorable, relationer: LayoutRelationer = LayoutRelationerStruct.equal, constants: CGFloat...) -> Layout { return constraint(attributes, to: anchor, relationer: relationer, constants: constants) } /** Constraints the view to the given anchor according to the provided attributes. If any of the constraints already exists, will update its constant. - Parameter _ attributes: An array of LayoutAttribute. - Parameter to anchor: A LayoutAnchorable. - Parameter relation: A LayoutRelation between anchors. - Parameter constants: An array of CGFloat. - Returns: A Layout instance to allow chaining. */ func constraint(_ attributes: [LayoutAttribute], to anchor: LayoutAnchorable, relationer: LayoutRelationer, constants: [CGFloat]) -> Layout { let from = LayoutAnchor(constraintable: constraintable, attributes: attributes) var to = anchor as? LayoutAnchor if to?.attributes.isEmpty ?? true { let v = (anchor as? UIView) ?? (anchor as? LayoutAnchor)?.constraintable to = LayoutAnchor(constraintable: v, attributes: attributes) } let constraint = LayoutConstraint(fromAnchor: from, toAnchor: to!, relation: relationer(.nil, .nil), constants: constants) let constraints = (view?.constraints ?? []) + (view?.superview?.constraints ?? []) let newConstraints = constraint.constraints for newConstraint in newConstraints { guard let activeConstraint = constraints.first(where: { $0.equalTo(newConstraint) }) else { newConstraint.isActive = true view?.lastConstraint = newConstraint continue } activeConstraint.constant = newConstraint.constant } return self } } /// A closure typealias for relation operators. public typealias LayoutRelationer = (LayoutRelationerStruct, LayoutRelationerStruct) -> LayoutRelation /// A dummy struct used in creating relation operators (==, >=, <=). public struct LayoutRelationerStruct { /// Passed as an unused argument to the LayoutRelationer closures. static let `nil` = LayoutRelationerStruct() /** A method used as a default parameter for LayoutRelationer closures. Swift does not allow using == operator directly, so we had to create this. */ public static func equal(left: LayoutRelationerStruct, right: LayoutRelationerStruct) -> LayoutRelation { return .equal } } /// A method returning `LayoutRelation.equal` public func ==(left: LayoutRelationerStruct, right: LayoutRelationerStruct) -> LayoutRelation { return .equal } /// A method returning `LayoutRelation.greaterThanOrEqual` public func >=(left: LayoutRelationerStruct, right: LayoutRelationerStruct) -> LayoutRelation { return .greaterThanOrEqual } /// A method returning `LayoutRelation.lessThanOrEqual` public func <=(left: LayoutRelationerStruct, right: LayoutRelationerStruct) -> LayoutRelation { return .lessThanOrEqual }
25a6299d31cba8634b06763a845f3de9
36.714521
175
0.70256
false
false
false
false
mickeyckm/nanodegree-mememe
refs/heads/master
MemeMe/SentMemesTableViewController.swift
mit
1
// // SentMemesTableViewController.swift // MemeMe // // Created by Mickey Cheong on 21/10/16. // Copyright © 2016 CHEO.NG. All rights reserved. // import UIKit class SentMemesTableViewController: UITableViewController { var memes: [Meme] { return (UIApplication.shared.delegate as! AppDelegate).memes } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return memes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "memeCell", for: indexPath) let meme = memes[indexPath.row] cell.textLabel?.text = "\(meme.topText!)...\(meme.bottomText!)" cell.imageView?.image = meme.memedImage cell.imageView?.contentMode = .scaleAspectFit return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailViewController = storyboard?.instantiateViewController(withIdentifier: "memeDetailsVC") as! MemeDetailsViewController detailViewController.meme = memes[indexPath.row] self.navigationController?.pushViewController(detailViewController, animated: true) } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCellEditingStyle.delete { let object = UIApplication.shared.delegate let appDelegate = object as! AppDelegate appDelegate.memes.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade) } } }
84e0fe24ca2df435d92d0476a92a5077
34.393443
136
0.695229
false
false
false
false
dtycoon/twitterfly
refs/heads/master
twitterfly/UserViewController.swift
mit
1
// // ViewController.swift // twitterfly // // Created by Deepak Agarwal on 10/3/14. // Copyright (c) 2014 Deepak Agarwal. All rights reserved. // import UIKit class UserViewController: UIViewController, UserViewControllerDelegate { @IBOutlet weak var userSN: UILabel! @IBOutlet weak var userImage: UIImageView! @IBOutlet weak var profileButton: UIButton! @IBOutlet weak var homeButton: UIButton! @IBOutlet weak var mentionsButton: UIButton! @IBOutlet weak var composeButton: UIButton! @IBOutlet weak var contentView: UIView! @IBOutlet weak var onLogoutButton: UIButton! var viewContollerDict:[String:UIViewController] = [:] @IBOutlet weak var logoutButton: UIButton! var profileViewController: ProfileViewController! var timelineViewController: HometimelineViewController! var tweetDetailViewController: TweetDetailViewController! var composeViewController: ComposeViewController! @IBOutlet weak var contentViewCenterXConstraint: NSLayoutConstraint! var activeViewController: UIViewController? { didSet(oldViewControllerOrNil) { if let oldVC = oldViewControllerOrNil { oldVC.willMoveToParentViewController(nil) oldVC.view.removeFromSuperview() oldVC.removeFromParentViewController() } if let newVC = activeViewController { self.addChildViewController(newVC) newVC.view.autoresizingMask = .FlexibleWidth | .FlexibleHeight newVC.view.frame = self.contentView.bounds self.contentView.addSubview(newVC.view) newVC.didMoveToParentViewController(self) } } } /* var animationActiveViewController: UIViewController? { didSet(oldViewControllerOrNil) { if let oldVC = oldViewControllerOrNil { oldVC.willMoveToParentViewController(nil) oldVC.view.removeFromSuperview() oldVC.removeFromParentViewController() } if let newVC = activeViewController { self.addChildViewController(newVC) newVC.view.autoresizingMask = .FlexibleWidth | .FlexibleHeight if(oldVC == nil) { newVC.view.frame = self.contentView.bounds self.contentView.addSubview(newVC.view) newVC.didMoveToParentViewController(self) } } } } func transitionCustomAnimationViewController( oldVC: UIViewController?, newVC: UIViewController?) { UIApplication.sharedApplication().beginIgnoringInteractionEvents() if (oldVC? != nil) { oldVC!.willMoveToParentViewController(nil) } if (newVC? != nil) { self.addChildViewController(newVC!) newVC!.view.autoresizingMask = .FlexibleWidth | .FlexibleHeight if(oldVC? == nil) { newVC!.view.frame = self.contentView.bounds self.contentView.addSubview(newVC!.view) newVC!.didMoveToParentViewController(self) println("oldVC is nil") return } } else { println("newVC is nil") return } self.addChildViewController(newVC!) newVC!.view.autoresizingMask = .FlexibleWidth | .FlexibleHeight transitionFromViewController( oldVC!, toViewController:newVC!, duration:0.4, options:.TransitionNone, animations: { newVC!.view.frame = self.contentView.bounds self.contentView.addSubview(newVC!.view) }, completion:{ _ in newVC!.didMoveToParentViewController(self) oldVC!.view.removeFromSuperview() oldVC!.removeFromParentViewController() UIApplication.sharedApplication().endIgnoringInteractionEvents() }) } */ override func viewDidLoad() { super.viewDidLoad() if(User.currentUser != nil) { var tweetUrl = User.currentUser?.profileImageUrl if(tweetUrl != nil) { self.userImage.setImageWithURL(NSURL(string: tweetUrl!)) } var sn = "@" + (User.currentUser?.screenname)! self.userSN.text = sn } self.contentViewCenterXConstraint.constant = 0 var storyboard = UIStoryboard(name: "Main", bundle: nil) profileViewController = storyboard.instantiateViewControllerWithIdentifier("ProfileViewController") as ProfileViewController profileViewController.segueDelegate = self viewContollerDict["ProfileViewController"] = profileViewController timelineViewController = storyboard.instantiateViewControllerWithIdentifier("HometimelineViewController") as HometimelineViewController viewContollerDict["HometimelineViewController"] = timelineViewController viewContollerDict["MentiontimelineViewController"] = timelineViewController timelineViewController.segueDelegate = self timelineViewController.profileDelegate = profileViewController tweetDetailViewController = storyboard.instantiateViewControllerWithIdentifier("TweetDetailViewController") as TweetDetailViewController viewContollerDict["TweetDetailViewController"] = tweetDetailViewController tweetDetailViewController.segueDelegate = self tweetDetailViewController.hometimelineDelegate = timelineViewController tweetDetailViewController.profileDelegate = profileViewController composeViewController = storyboard.instantiateViewControllerWithIdentifier("ComposeViewController") as ComposeViewController composeViewController.segueDelegate = self viewContollerDict["ComposeViewController"] = composeViewController profileViewController.tweetDetailDelegate = tweetDetailViewController timelineViewController.tweetDetailDelegate = tweetDetailViewController // transitionCustomAnimationViewController(self.activeViewController, newVC: timelineViewController) self.activeViewController = timelineViewController } @IBAction func onTapSidebarButton(sender: UIButton) { if(sender == profileButton) { println("Profile Menu Item") var curUser = User.currentUser?.userId if(profileViewController.userId == nil || profileViewController.userId != curUser!) { profileViewController.reloadViews = true } profileViewController.userId = curUser! println("Profile Menu Item currentUser selected = \(curUser!)") // transitionCustomAnimationViewController(self.activeViewController, newVC: profileViewController) self.activeViewController = profileViewController } else if (sender == homeButton) { println("Home Menu Item") if(timelineViewController.homeOrMentionTimelineUrl != "1.1/statuses/home_timeline.json") { timelineViewController.homeOrMentionTimelineUrl = "1.1/statuses/home_timeline.json" timelineViewController.headerText = "Home" timelineViewController.reloadViews = true } // transitionCustomAnimationViewController(self.activeViewController, newVC: timelineViewController) self.activeViewController = timelineViewController } else if (sender == mentionsButton) { println("Mentions Menu Item") if(timelineViewController.homeOrMentionTimelineUrl != "1.1/statuses/mentions_timeline.json") { timelineViewController.homeOrMentionTimelineUrl = "1.1/statuses/mentions_timeline.json" timelineViewController.headerText = "Mentions" timelineViewController.reloadViews = true } // transitionCustomAnimationViewController(self.activeViewController, newVC: timelineViewController) self.activeViewController = timelineViewController } else if(sender == composeButton) { var curUser = User.currentUser?.userId println("Compose Menu Item") profileViewController.userId = curUser! println("Compose Menu Item currentUser selected = \(curUser!)") // transitionCustomAnimationViewController(self.activeViewController, newVC: composeViewController) self.activeViewController = composeViewController } else if(sender == onLogoutButton) { User.currentUser?.logout() } else { println("Unknown Menu Item") } UIView.animateWithDuration(0.35, animations: { () -> Void in self.contentViewCenterXConstraint.constant = 0 self.view.layoutIfNeeded() }) } @IBAction func didSwipe(sender: UISwipeGestureRecognizer) { if(sender.state == .Ended) { UIView.animateWithDuration(0.35, animations: { () -> Void in self.contentViewCenterXConstraint.constant = -160 self.view.layoutIfNeeded() }) } } @IBAction func didSwipeBack(sender: UISwipeGestureRecognizer) { if(sender.state == .Ended) { UIView.animateWithDuration(0.35, animations: { () -> Void in self.contentViewCenterXConstraint.constant = 0 self.view.layoutIfNeeded() }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onLogout(sender: AnyObject) { User.currentUser?.logout() } func RequestSegueToViewController (viewControllerName:String) { println("RequestSegueToViewController: requesting transition to viewControllerName = \(viewControllerName)") // transitionCustomAnimationViewController(self.activeViewController, newVC: self.viewContollerDict[viewControllerName]) self.activeViewController = self.viewContollerDict[viewControllerName] } }
0cf6445a78dd5988f3cc590889985343
35.147368
144
0.656669
false
false
false
false
exchangegroup/Dodo
refs/heads/master
Dodo/Utils/DodoColor.swift
mit
2
import UIKit /** Creates a UIColor object from a string. Examples: DodoColor.fromHexString('#340f9a') // With alpha channel DodoColor.fromHexString('#f1a2b3a6') */ public class DodoColor { /** Creates a UIColor object from a string. - parameter rgba: a RGB/RGBA string representation of color. It can include optional alpha value. Example: "#cca213" or "#cca21312" (with alpha value). - returns: UIColor object. */ public class func fromHexString(_ rgba: String) -> UIColor { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if !rgba.hasPrefix("#") { print("Warning: DodoColor.fromHexString, # character missing") return UIColor() } let index = rgba.index(rgba.startIndex, offsetBy: 1) let hex = String(rgba.suffix(from: index)) let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if !scanner.scanHexInt64(&hexValue) { print("Warning: DodoColor.fromHexString, error scanning hex value") return UIColor() } if hex.count == 6 { red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 } else if hex.count == 8 { red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 } else { print("Warning: DodoColor.fromHexString, invalid rgb string, length should be 7 or 9") return UIColor() } return UIColor(red: red, green: green, blue: blue, alpha: alpha) } }
e6dcd4ec40047a5ed59209bedb188aaa
27.870968
153
0.622905
false
false
false
false
silence0201/Swift-Study
refs/heads/master
Note/Day 03/03-类的使用.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit // 1.如何定义类 /* OC类的定义 @interface Person : NSObject @end @impelment @end */ class Person { // 如果属性是值类型, 则初始化为空值 // 如果属性是对象类型, 则初始化为nil值 var name : String = "" var age : Int = 0 var view : UIView? } // 2.创建类的对象 let view = UIView() let p = Person() p.name = "why" p.age = 18 p.view = view
47f0deb402a1f30d14ccdef6c34c1001
11.833333
52
0.602597
false
false
false
false
NoryCao/zhuishushenqi
refs/heads/master
zhuishushenqi/TXTReader/Category/QSCategoryPresenter.swift
mit
1
// // QSCategoryPresenter.swift // zhuishushenqi // // Created Nory Cao on 2017/4/13. // Copyright © 2017年 QS. All rights reserved. // // Template generated by Juanpe Catalán @JuanpeCMiOS // import UIKit class QSCategoryPresenter: QSCategoryPresenterProtocol { weak var view: QSCategoryViewProtocol? private let interactor: QSCategoryInteractorProtocol let router: QSCategoryWireframeProtocol var ranks:[QSHotComment] = [] var show:Bool = false init(interface: QSCategoryViewProtocol, interactor: QSCategoryInteractorProtocol, router: QSCategoryWireframeProtocol) { self.view = interface self.interactor = interactor self.router = router } func viewDidLoad() { view?.showActivityView() interactor.showDetail() interactor.show() } } extension QSCategoryPresenter:QSCategoryInteractorOutputProtocol{ func show(titles:[String]){ view?.hideActivityView() view?.show(titles: titles) } func showDetail(book: BookDetail) { view?.showDetail(book: book) // func fetchBookSuccess(bookDetail:BookDetail,ranks:[QSHotComment]){ // self.ranks = ranks view?.hideActivityView() } func fetchRankFailed() { view?.hideActivityView() } func fetchContent(show: Bool) { } func fetchAllChapterSuccess(bookDetail:BookDetail,res:[ResourceModel]){ router.presentReading(model: res, booDetail: bookDetail) view?.hideActivityView() } func fetchAllChapterFailed(){ view?.hideActivityView() } }
affb371021dccf40870dc97d612b9d78
23.833333
124
0.660769
false
false
false
false
moysklad/ios-remap-sdk
refs/heads/master
Sources/MoyskladiOSRemapSDK/Mapping/Serialization/MSContract+Serialize.swift
mit
1
// // MSContract+Serialize.swift // MoyskladiOSRemapSDK // // Created by Антон Ефименко on 21.09.2018. // Copyright © 2018 Andrey Parshakov. All rights reserved. // import Foundation extension MSContract { public func dictionary(metaOnly: Bool = true) -> Dictionary<String, Any> { var dict = [String: Any]() if meta.href.count > 0 { dict["meta"] = meta.dictionary() } guard !metaOnly else { return dict } dict.merge(info.dictionary()) dict["owner"] = serialize(entity: owner, metaOnly: true) dict["shared"] = shared dict["group"] = serialize(entity: group, metaOnly: true) dict["code"] = code dict["externalCode"] = externalCode ?? "" dict["archived"] = archived dict["ownAgent"] = serialize(entity: ownAgent, metaOnly: true) dict["agent"] = serialize(entity: agent, metaOnly: true) dict["state"] = serialize(entity: state, metaOnly: true) dict["rate"] = rate?.dictionary(metaOnly: true) ?? NSNull() dict["moment"] = moment?.toLongDate() dict["attributes"] = attributes?.compactMap { $0.value()?.dictionary(metaOnly: false) } if let agentAccount = agentAccount { dict["agentAccount"] = serialize(entity: agentAccount, metaOnly: true) } if let organizationAccount = organizationAccount { dict["organizationAccount"] = serialize(entity: organizationAccount, metaOnly: true) } dict["rewardPercent"] = rewardPercent dict["rewardType"] = rewardType?.rawValue dict["contractType"] = contractType?.rawValue dict["sum"] = sum.minorUnits return dict } }
0907da36683d69766b8feb8601820072
33.647059
96
0.596491
false
false
false
false
movabletype/mt-data-api-sdk-swift
refs/heads/master
Example/MTDataAPI/Classes/Controller/EntryTableViewController.swift
mit
1
// // EntryTableViewController.swift // MTDataAPI // // Created by CHEEBOW on 2015/04/14. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit import SwiftyJSON import SVProgressHUD class EntryTableViewController: UITableViewController { var items = [JSON]() var blogID = "" var fetching = false var total = 0 func fetch(_ more:Bool) { if !more { SVProgressHUD.show() } self.fetching = true let api = DataAPI.sharedInstance let app = UIApplication.shared.delegate as! AppDelegate api.authentication(app.username, password: app.password, remember: true, success:{_ in var params = ["limit":"15"] if more { params["offset"] = "\(self.items.count)" } api.listEntries(siteID: self.blogID, options: params, success: {(result: [JSON]?, total: Int?)-> Void in if let result = result, let total = total { if more { self.items += result } else { self.items = result } self.total = total self.tableView.reloadData() } SVProgressHUD.dismiss() self.fetching = false }, failure: {(error: JSON?)-> Void in SVProgressHUD.showError(withStatus: error?["message"].stringValue ?? "") self.fetching = false } ) }, failure: {(error: JSON?)-> Void in SVProgressHUD.showError(withStatus: error?["message"].stringValue ?? "") self.fetching = false } ) } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.add, target: self, action: #selector(EntryTableViewController.createEntry(_:))) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.fetch(false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - func showDetailView(_ entry: JSON) { let storyboard = UIStoryboard(name: "EntryDetail", bundle: nil) let vc: EntryDetailViewController = storyboard.instantiateInitialViewController() as! EntryDetailViewController vc.entry = entry self.navigationController?.pushViewController(vc, animated: true) } func createEntry(_ sender: UIBarButtonItem) { let entry = JSON(["blog":["id":blogID]]) self.showDetailView(entry) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) // Configure the cell... let item = items[indexPath.row] cell.textLabel?.text = item["title"].stringValue cell.detailTextLabel?.text = item["excerpt"].stringValue return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO 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 NO 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. } */ override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let entry = items[indexPath.row] self.showDetailView(entry) } override func scrollViewDidScroll(_ scrollView: UIScrollView) { if (self.tableView.contentOffset.y >= (self.tableView.contentSize.height - self.tableView.bounds.size.height)) { if self.fetching {return} if self.total <= self.items.count {return} self.fetch(true) } } }
9ef5c55de17337b0795ce30a4926e3f8
35.226519
187
0.604087
false
false
false
false
jeesmon/varamozhi-ios
refs/heads/master
varamozhi/DefaultSettings.swift
gpl-2.0
1
// // DefaultSettings.swift // TastyImitationKeyboard // // Created by Alexei Baboulevitch on 11/2/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit class DefaultSettings: ExtraView, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView? @IBOutlet var effectsView: UIVisualEffectView? @IBOutlet var backButton: UIButton? @IBOutlet var settingsLabel: UILabel? @IBOutlet var pixelLine: UIView? override var darkMode: Bool { didSet { self.updateAppearance(darkMode) } } let cellBackgroundColorDark = UIColor.white.withAlphaComponent(CGFloat(0.25)) let cellBackgroundColorLight = UIColor.white.withAlphaComponent(CGFloat(1)) let cellLabelColorDark = UIColor.white let cellLabelColorLight = UIColor.black let cellLongLabelColorDark = UIColor.lightGray let cellLongLabelColorLight = UIColor.gray // TODO: these probably don't belong here, and also need to be localized var settingsList: [(String, [String])] { get { let isPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad //+20141231 if isPad { return [ ("General Settings", [kPeriodShortcut, kKeyboardClicks]), ("Extra Settings", [kDisablePopupKeys]) //+20150401 ] }else { return [ ("General Settings", [kPeriodShortcut, kKeyboardClicks]), ("Extra Settings", [kDisablePopupKeys]) ] } } } var settingsNames: [String:String] { get { return [ //kAutoCapitalization: "Auto-Capitalization", kPeriodShortcut: "“.” Shortcut", kKeyboardClicks: "Keyboard Clicks", kDisablePopupKeys: "Remove Top Banner"//+20141231 ] } } var settingsNotes: [String: String] { get { let isPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad //+20150401 if isPad { return [ kKeyboardClicks: "Please note that keyboard clicks will work only if “Allow Full Access” is enabled in the keyboard settings. Unfortunately, this is a limitation of the operating system.", kDisablePopupKeys: "This will remove top banner of the keyboard and disable the dictionary suppport. You need to switch keyboard by tapping globe icon to see the change." ] }else { return [ kKeyboardClicks: "Please note that keyboard clicks will work only if “Allow Full Access” is enabled in the keyboard settings. Unfortunately, this is a limitation of the operating system.", kDisablePopupKeys: "This will remove top banner of the keyboard and disable key popup on tap. You need to switch keyboard by tapping globe icon to see the change." ] } } } required init(globalColors: GlobalColors.Type?, darkMode: Bool, solidColorMode: Bool) { super.init(globalColors: globalColors, darkMode: darkMode, solidColorMode: solidColorMode) self.loadNib() } required init?(coder aDecoder: NSCoder) { fatalError("loading from nib not supported") } func loadNib() { let assets = Bundle(for: type(of: self)).loadNibNamed("DefaultSettings", owner: self, options: nil) if (assets?.count)! > 0 { if let rootView = assets?.first as? UIView { rootView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(rootView) let left = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0) let right = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0) let top = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0) let bottom = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0) self.addConstraint(left) self.addConstraint(right) self.addConstraint(top) self.addConstraint(bottom) } } self.tableView?.register(DefaultSettingsTableViewCell.self, forCellReuseIdentifier: "cell") self.tableView?.estimatedRowHeight = 44; self.tableView?.rowHeight = UITableViewAutomaticDimension; // XXX: this is here b/c a totally transparent background does not support scrolling in blank areas self.tableView?.backgroundColor = UIColor.white.withAlphaComponent(0.01) self.updateAppearance(self.darkMode) } func numberOfSections(in tableView: UITableView) -> Int { return self.settingsList.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.settingsList[section].1.count } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 35 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == self.settingsList.count - 1 { return 50 } else { return 0 } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.settingsList[section].0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? DefaultSettingsTableViewCell { let key = self.settingsList[indexPath.section].1[indexPath.row] if cell.sw.allTargets.count == 0 { cell.sw.addTarget(self, action: #selector(DefaultSettings.toggleSetting(_:)), for: UIControlEvents.valueChanged) } cell.sw.isOn = UserDefaults.standard.bool(forKey: key) cell.label.text = self.settingsNames[key] cell.longLabel.text = self.settingsNotes[key] cell.backgroundColor = (self.darkMode ? cellBackgroundColorDark : cellBackgroundColorLight) cell.label.textColor = (self.darkMode ? cellLabelColorDark : cellLabelColorLight) cell.longLabel.textColor = (self.darkMode ? cellLongLabelColorDark : cellLongLabelColorLight) cell.changeConstraints() return cell } else { assert(false, "this is a bad thing that just happened") return UITableViewCell() } } func updateAppearance(_ dark: Bool) { if dark { self.effectsView?.effect let blueColor = UIColor(red: 135/CGFloat(255), green: 206/CGFloat(255), blue: 250/CGFloat(255), alpha: 1) self.pixelLine?.backgroundColor = blueColor.withAlphaComponent(CGFloat(0.5)) self.backButton?.setTitleColor(blueColor, for: UIControlState()) self.settingsLabel?.textColor = UIColor.white if let visibleCells = self.tableView?.visibleCells { for cell in visibleCells { //let cell = cell as UITableViewCell cell.backgroundColor = cellBackgroundColorDark let label = cell.viewWithTag(2) as? UILabel label?.textColor = cellLabelColorDark let longLabel = cell.viewWithTag(3) as? UITextView longLabel?.textColor = cellLongLabelColorDark } } } else { let blueColor = UIColor(red: 0/CGFloat(255), green: 122/CGFloat(255), blue: 255/CGFloat(255), alpha: 1) self.pixelLine?.backgroundColor = blueColor.withAlphaComponent(CGFloat(0.5)) self.backButton?.setTitleColor(blueColor, for: UIControlState()) self.settingsLabel?.textColor = UIColor.gray if let visibleCells = self.tableView?.visibleCells { for cell in visibleCells { //if let cell = cell as? UITableViewCell { cell.backgroundColor = cellBackgroundColorLight let label = cell.viewWithTag(2) as? UILabel label?.textColor = cellLabelColorLight let longLabel = cell.viewWithTag(3) as? UITextView longLabel?.textColor = cellLongLabelColorLight // } } } } } @objc func toggleSetting(_ sender: UISwitch) { if let cell = sender.superview as? UITableViewCell { if let indexPath = self.tableView?.indexPath(for: cell) { let key = self.settingsList[indexPath.section].1[indexPath.row] UserDefaults.standard.set(sender.isOn, forKey: key) } } } } class DefaultSettingsTableViewCell: UITableViewCell { var sw: UISwitch var label: UILabel var longLabel: UITextView var constraintsSetForLongLabel: Bool var cellConstraints: [NSLayoutConstraint] override init(style: UITableViewCellStyle, reuseIdentifier: String?) { self.sw = UISwitch() self.label = UILabel() self.longLabel = UITextView() self.cellConstraints = [] self.constraintsSetForLongLabel = false super.init(style: style, reuseIdentifier: reuseIdentifier) self.sw.translatesAutoresizingMaskIntoConstraints = false self.label.translatesAutoresizingMaskIntoConstraints = false self.longLabel.translatesAutoresizingMaskIntoConstraints = false self.longLabel.text = nil self.longLabel.isScrollEnabled = false self.longLabel.isSelectable = false self.longLabel.backgroundColor = UIColor.clear self.sw.tag = 1 self.label.tag = 2 self.longLabel.tag = 3 self.addSubview(self.sw) self.addSubview(self.label) self.addSubview(self.longLabel) self.addConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addConstraints() { let margin: CGFloat = 8 let sideMargin = margin * 2 let hasLongText = self.longLabel.text != nil && !self.longLabel.text.isEmpty if hasLongText { let switchSide = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.right, multiplier: 1, constant: -sideMargin) let switchTop = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1, constant: margin) let labelSide = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.left, multiplier: 1, constant: sideMargin) let labelCenter = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: sw, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) self.addConstraint(switchSide) self.addConstraint(switchTop) self.addConstraint(labelSide) self.addConstraint(labelCenter) let left = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.left, multiplier: 1, constant: sideMargin) let right = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.right, multiplier: 1, constant: -sideMargin) let top = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: sw, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: margin) let bottom = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -margin) self.addConstraint(left) self.addConstraint(right) self.addConstraint(top) self.addConstraint(bottom) self.cellConstraints += [switchSide, switchTop, labelSide, labelCenter, left, right, top, bottom] self.constraintsSetForLongLabel = true } else { let switchSide = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.right, multiplier: 1, constant: -sideMargin) let switchTop = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1, constant: margin) let switchBottom = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -margin) let labelSide = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.left, multiplier: 1, constant: sideMargin) let labelCenter = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: sw, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) self.addConstraint(switchSide) self.addConstraint(switchTop) self.addConstraint(switchBottom) self.addConstraint(labelSide) self.addConstraint(labelCenter) self.cellConstraints += [switchSide, switchTop, switchBottom, labelSide, labelCenter] self.constraintsSetForLongLabel = false } } // XXX: not in updateConstraints because it doesn't play nice with UITableViewAutomaticDimension for some reason func changeConstraints() { let hasLongText = self.longLabel.text != nil && !self.longLabel.text.isEmpty if hasLongText != self.constraintsSetForLongLabel { self.removeConstraints(self.cellConstraints) self.cellConstraints.removeAll() self.addConstraints() } } }
de0df3403fe52de0f33f2664505c00fe
47.139319
218
0.637469
false
false
false
false
CodaFi/swift
refs/heads/main
validation-test/IDE/crashers_fixed/061-swift-constraints-solution-coercetotype.swift
apache-2.0
71
// RUN: %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s protocol P{ protocol A{ let t={ protocol c{ let:n class A{ func c let s=c protocol e{ typealias f=#^A^#
b595192aef32426e76bb88582b6eb714
16.909091
92
0.715736
false
true
false
false
debugsquad/metalic
refs/heads/master
metalic/Model/Store/MStorePurchaseItem.swift
mit
1
import Foundation import StoreKit class MStorePurchaseItem:NSObject { private var dbFilter:DObjectPurchase! let title:String var price:String? var skProduct:SKProduct? var status:MStorePurchaseItemStatus var asset:String private let kEmpty:String = "" init(dbFilter:DObjectPurchase) { self.dbFilter = dbFilter if dbFilter.purchased { status = MStorePurchaseItemStatusPurchased() } else { status = MStorePurchaseItemStatusNew() } guard let className:String = dbFilter.purchaseClass, let filterItem:MFiltersItem = MFiltersItem.Factory(className:className) else { asset = kEmpty title = kEmpty return } title = filterItem.name asset = filterItem.asset } //MARK: public func purchased() { status = MStorePurchaseItemStatusPurchased() dbFilter.purchased = true DManager.sharedInstance.save() } }
4066419cd6acc979232b0a760f6c75bb
20.698113
83
0.556522
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/WMFContentGroup+DetailViewControllers.swift
mit
1
import Foundation extension WMFContentGroup { @objc(detailViewControllerForPreviewItemAtIndex:dataStore:theme:) public func detailViewControllerForPreviewItemAtIndex(_ index: Int, dataStore: MWKDataStore, theme: Theme) -> UIViewController? { switch detailType { case .page: guard let articleURL = previewArticleURLForItemAtIndex(index) else { return nil } return ArticleViewController(articleURL: articleURL, dataStore: dataStore, theme: theme) case .pageWithRandomButton: guard let articleURL = previewArticleURLForItemAtIndex(index) else { return nil } return RandomArticleViewController(articleURL: articleURL, dataStore: dataStore, theme: theme) case .gallery: guard let date = self.date else { return nil } return WMFPOTDImageGalleryViewController(dates: [date], theme: theme, overlayViewTopBarHidden: false) case .story, .event: return detailViewControllerWithDataStore(dataStore, theme: theme) default: return nil } } @objc(detailViewControllerWithDataStore:theme:) public func detailViewControllerWithDataStore(_ dataStore: MWKDataStore, theme: Theme) -> UIViewController? { var vc: UIViewController? = nil switch moreType { case .pageList: guard let articleURLs = contentURLs else { break } vc = ArticleURLListViewController(articleURLs: articleURLs, dataStore: dataStore, contentGroup: self, theme: theme) vc?.title = moreTitle case .pageListWithLocation: guard let articleURLs = contentURLs else { break } vc = ArticleLocationCollectionViewController(articleURLs: articleURLs, dataStore: dataStore, contentGroup: self, theme: theme) case .news: guard let stories = fullContent?.object as? [WMFFeedNewsStory] else { break } vc = NewsViewController(stories: stories, dataStore: dataStore, contentGroup: self, theme: theme) case .onThisDay: guard let date = midnightUTCDate, let events = fullContent?.object as? [WMFFeedOnThisDayEvent] else { break } vc = OnThisDayViewController(events: events, dataStore: dataStore, midnightUTCDate: date, contentGroup: self, theme: theme) case .pageWithRandomButton: guard let siteURL = siteURL else { break } let firstRandom = WMFFirstRandomViewController(siteURL: siteURL, dataStore: dataStore, theme: theme) (firstRandom as Themeable).apply(theme: theme) vc = firstRandom default: break } if let customVC = vc as? ViewController { customVC.navigationMode = .detail } if let customVC = vc as? ColumnarCollectionViewController { customVC.headerTitle = headerTitle customVC.footerButtonTitle = WMFLocalizedString("explore-detail-back-button-title", value: "Back to Explore feed", comment: "Title for button that allows users to exit detail view and return to Explore.") customVC.headerSubtitle = moreType != .onThisDay ? headerSubTitle : nil } return vc } }
93f3d259104a3a2760a63163295c2ea5
45.391892
216
0.632974
false
false
false
false
linhaosunny/smallGifts
refs/heads/master
小礼品/小礼品/Classes/Categories/UIViewController+Extension.swift
mit
1
// // UIViewController+Extension.swift // 椰海雅客微博 // // Created by 李莎鑫 on 2017/4/7. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit import QorumLogs extension UIViewController{ //: 通过类名称创建控制器 class func controller(withName controllerName:String?) -> UIViewController? { //: 获取命名空间 guard let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else { QL4("获取命名空间失败") return nil } guard let className = NSClassFromString(nameSpace + "." + (controllerName ?? "")) else { QL4("\(ToControllerKey):控制器名称\(controllerName)找不到!") return nil } //: 获取类型 guard let classType = className as? UIViewController.Type else { QL3("获取类型失败,不能创建控制器") return nil } return classType.init() } func hideNavigationBar(isHiden hide:Bool) { navigationController?.navigationBar.isTranslucent = true navigationController?.navigationBar.setBackgroundImage(hide ? UIImage() : UIImage.image(withColor: SystemNavgationBarTintColor, withSize: CGSize.zero), for: .default) if hide { navigationController?.navigationBar.shadowImage = UIImage() } } }
5a5da74418bfc183102524750f919f0b
27.361702
174
0.60165
false
false
false
false
myTargetSDK/mytarget-ios
refs/heads/master
myTargetDemoSwift/myTargetDemo/Controllers/Native/NativeCloseManuallyViewController.swift
lgpl-3.0
1
// // NativeCloseManuallyViewController.swift // myTargetDemo // // Created by igor.sorokin on 11.10.2022. // Copyright © 2022 Mail.ru Group. All rights reserved. // import UIKit import MyTargetSDK final class NativeCloseManuallyViewController: UIViewController { private let slotId: UInt private let query: [String: String]? private lazy var notificationView: NotificationView = .create(view: view) private lazy var reloadButton: CustomButton = .init(title: "Reload") private let adViewMaxSize: CGSize = .init(width: 300, height: 250) private let reloadButtonInsets: UIEdgeInsets = .init(top: 0, left: 16, bottom: 16, right: 16) private let buttonHeight: CGFloat = 40 // Use this flag for customize hide behavoir // See MTRGNativeAd's adChoicesOptionDelegate property and MTRGNativeAdChoicesOptionDelegate protocol for more details private var shouldHideAdManually = true private var isLoading: Bool = false { didSet { reloadButton.isEnabled = !isLoading } } // Current ad private var adContainerView: UIView? private var nativeAd: MTRGNativeAd? init(slotId: UInt, query: [String: String]? = nil) { self.slotId = slotId self.query = query super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Native Ads" reloadButton.addTarget(self, action: #selector(reloadTapped(_:)), for: .touchUpInside) view.backgroundColor = .backgroundColor() view.addSubview(reloadButton) loadAd() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let safeAreaInsets = supportSafeAreaInsets if let adContainerView = adContainerView { let adContainerSize = adContainerView.sizeThatFits(adViewMaxSize) adContainerView.frame = CGRect(x: view.bounds.width / 2 - adContainerSize.width / 2, y: view.bounds.height / 2 - adContainerSize.height / 2, width: adContainerSize.width, height: adContainerSize.height) } reloadButton.frame = CGRect(x: safeAreaInsets.left + reloadButtonInsets.left, y: view.bounds.height - safeAreaInsets.bottom - reloadButtonInsets.bottom - buttonHeight, width: view.bounds.width - safeAreaInsets.left - safeAreaInsets.right - reloadButtonInsets.left - reloadButtonInsets.right, height: buttonHeight) } private func loadAd() { let nativeAd = MTRGNativeAd(slotId: slotId, adChoicesMenuFactory: AlertMenuFactory()) query?.forEach { nativeAd.customParams.setCustomParam($0.value, forKey: $0.key) } nativeAd.delegate = self nativeAd.adChoicesOptionDelegate = self nativeAd.load() self.nativeAd = nativeAd isLoading = true notificationView.showMessage("Loading...") } private func cleanup() { nativeAd?.unregisterView() nativeAd = nil adContainerView?.removeFromSuperview() adContainerView = nil } func render(nativeAd: MTRGNativeAd) { isLoading = false guard let promoBanner = nativeAd.banner else { notificationView.showMessage("No banner info") return } let nativeAdContainer = createNativeView(from: promoBanner) nativeAd.register(nativeAdContainer, with: self) view.addSubview(nativeAdContainer) self.adContainerView = nativeAdContainer } private func createNativeView(from promoBanner: MTRGNativePromoBanner?) -> UIView { let nativeAdView = MTRGNativeViewsFactory.createNativeAdView() nativeAdView.banner = promoBanner let nativeAdContainer = MTRGNativeAdContainer.create(withAdView: nativeAdView) nativeAdContainer.ageRestrictionsView = nativeAdView.ageRestrictionsLabel nativeAdContainer.advertisingView = nativeAdView.adLabel nativeAdContainer.titleView = nativeAdView.titleLabel nativeAdContainer.descriptionView = nativeAdView.descriptionLabel nativeAdContainer.iconView = nativeAdView.iconAdView nativeAdContainer.mediaView = nativeAdView.mediaAdView nativeAdContainer.domainView = nativeAdView.domainLabel nativeAdContainer.categoryView = nativeAdView.categoryLabel nativeAdContainer.disclaimerView = nativeAdView.disclaimerLabel nativeAdContainer.ratingView = nativeAdView.ratingStarsLabel nativeAdContainer.votesView = nativeAdView.votesLabel nativeAdContainer.ctaView = nativeAdView.buttonView return nativeAdContainer } @objc private func reloadTapped(_ sender: UIButton) { cleanup() loadAd() } } // MARK: - MTRGNativeAdChoicesOptionDelegate extension NativeCloseManuallyViewController: MTRGNativeAdChoicesOptionDelegate { // SDK use this method to decide, should it close ad or not // Return true for closing by SDK or false for manually // Method is optional and returns true by default func shouldCloseAutomatically() -> Bool { return !shouldHideAdManually } // Calls when SDK hides ad (when `shouldCloseAutomatically` returns true) func onCloseAutomatically(_ nativeAd: MTRGNativeAd!) { notificationView.showMessage("onCloseAutomatically() called") } // This method calls when you should hide ad manually (when `shouldCloseAutomatically` returns false) func closeIfAutomaticallyDisabled(_ nativeAd: MTRGNativeAd!) { adContainerView?.isHidden = true notificationView.showMessage("closeIfAutomaticallyDisabled() called") } } // MARK: - MTRGNativeAdDelegate extension NativeCloseManuallyViewController: MTRGNativeAdDelegate { func onLoad(with promoBanner: MTRGNativePromoBanner, nativeAd: MTRGNativeAd) { render(nativeAd: nativeAd) notificationView.showMessage("onLoad() called") } func onNoAd(withReason reason: String, nativeAd: MTRGNativeAd) { render(nativeAd: nativeAd) notificationView.showMessage("onNoAd(\(reason)) called") } }
421b043e8a4eb83c07e32c366c1b6e78
30.872222
132
0.769566
false
false
false
false
zjjzmw1/SwiftCodeFragments
refs/heads/master
SwiftCodeFragments/Tabbar/XHTabBar.swift
mit
1
// // XHTabBar.swift // XHTabBarExampleSwift // // Created by xiaohui on 16/8/8. // Copyright © 2016年 qiantou. All rights reserved. // 代码地址:https://github.com/CoderZhuXH/XHTabBarSwift import UIKit //import KDInteractiveNavigationController // 自定义导航栏 /** * RGBA颜色 */ func ColorRGBA(r:CGFloat,g:CGFloat,b:CGFloat,a:CGFloat) -> UIColor { return UIColor(red:r/255.0,green:g/255.0,blue:b/255.0,alpha:a) } /** * RGB颜色 */ func ColorRGB(r:CGFloat,g:CGFloat,b:CGFloat) -> UIColor { return ColorRGBA(r: r, g: g, b: b, a: 1.0) } /** * 随机色 */ func ColorRandom() -> UIColor { return ColorRGB(r: CGFloat(arc4random()%255), g: CGFloat(arc4random()%255), b: CGFloat(arc4random()%255)) } /** * 屏幕宽度 */ private let MWIDTH = UIScreen.main.bounds.size.width /** * 屏幕高度 */ private let MHEIGHT = UIScreen.main.bounds.size.height /** * tabbar背景色 */ private let ColorTabBar = UIColor.white /** * title默认颜色 */ private let ColorTitle = UIColor.gray /** * title选中颜色 */ private let ColorTitleSel = ColorRGB(r: 41,g: 167,b: 245) /** * title字体大小 */ private let titleFontSize : CGFloat = 12.0 /** * 数字角标直径 */ private let numMarkD:CGFloat = 20.0 /** * 小红点直径 */ private let pointMarkD:CGFloat = 12.0 /** * button 图片与文字上下占比 */ private let scale:CGFloat = 0.55 //MARK: - TabBarController public class XHTabBar:UITabBarController { //MARK: - 懒加载 public lazy var cusTabbar: UIView = { let x = CGFloat(0) let y = 49.0 - self.tabBarHeight let width = MWIDTH let height = self.tabBarHeight let view = UIView(frame: CGRect.init(x: x, y: y, width: width, height: height)) view.backgroundColor = ColorTabBar return view }() var seleBtn: UIButton? var tabBarHeight:CGFloat = 49.0 var titleArray = [String]() var imageArray = [String]() var selImageArray = [String]() var controllerArray = [String]() public init(controllerArray: [String], titleArray: [String],imageArray: [String],selImageArray: [String],height: CGFloat?) { self.controllerArray = controllerArray self.titleArray = titleArray self.imageArray = imageArray self.selImageArray = selImageArray if let tempHeight = height { tabBarHeight = tempHeight; } if tabBarHeight < 49.0 { tabBarHeight = 49.0 } super.init(nibName: nil, bundle: nil) } override public func viewDidLoad() { super.viewDidLoad() addController() self.tabBar.addSubview(cusTabbar) addTabBarButton() setupTabbarLine() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** 添加控制器 */ private func addController(){ guard controllerArray.count > 0 else { print("error:控制器数组为nil") return } var navArray = [UIViewController]() //获取命名空间 let ns = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String for className in controllerArray { // 将类名转化为类 let cls: AnyClass? = NSClassFromString(ns + "." + className) //Swift中如果想通过一个Class来创建一个对象, 必须告诉系统这个Class的确切类型 guard let vcCls = cls as? UIViewController.Type else { print("error:cls不能当做UIViewController") return } let vc = vcCls.init() //let nav = UINavigationController(rootViewController:vc) // 自定义导航栏 let nav = KDInteractiveNavigationController(rootViewController: vc) navArray.append(nav) } self.viewControllers = navArray; } /** 添加tabbarButton */ private func addTabBarButton() { let num = controllerArray.count for i in 0..<num { let width = UIScreen.main.bounds.size.width let x = CGFloat(width/CGFloat(num)*CGFloat(i)) let y:CGFloat = 0.0 let w = width/CGFloat(num) let h = tabBarHeight let button = XHTabBarButton(frame: CGRect.init(x: x, y: y, width: w, height: h)) button.tag = 1000+i button.setTitleColor(ColorTitle, for: UIControlState.normal) button.setTitleColor(ColorTitleSel, for: UIControlState.selected) button.titleLabel?.font = UIFont.systemFont(ofSize: titleFontSize) button.setImage(UIImage.init(named:self.imageArray[i]), for: UIControlState.normal) button.setImage(UIImage.init(named: self.selImageArray[i]), for: UIControlState.selected) button.setTitle(self.titleArray[i], for: UIControlState.normal) button.addTarget(self, action:#selector(buttonAction(button:)), for: UIControlEvents.touchUpInside) cusTabbar.addSubview(button) //默认选中 if i == 0 { button.isSelected = true self.seleBtn = button } //角标 let numLabel = UILabel(frame: CGRect.init(x: button.frame.size.width/2.0 + 6, y: 3, width: numMarkD, height: numMarkD)) numLabel.layer.masksToBounds = true numLabel.layer.cornerRadius = 10 numLabel.backgroundColor = UIColor.red numLabel.textColor = UIColor.white numLabel.textAlignment = NSTextAlignment.center numLabel.font = UIFont.systemFont(ofSize: 13) numLabel.tag = 1020+i numLabel.isHidden = true button.addSubview(numLabel) } } /** 处理高度>49 tabbar顶部线 */ private func setupTabbarLine() { //self.tabBar.shadowImage = UIImage.init() //self.tabBar.backgroundImage = UIImage.init() self.tabBar.shadowImage = UIImage.init() self.tabBar.backgroundImage = UIImage.init() //let line = UILabel(frame: CGRect.init(x: 0, y: 0, width: MWIDTH, height: 0.5)) //line.backgroundColor = UIColor.lightGray let line = UILabel(frame: CGRect.init(x: 0, y: 0, width: MWIDTH, height: 0.5)) line.backgroundColor = UIColor.lightGray line.alpha = 0.5 cusTabbar.addSubview(line) } //MARK: - Action @objc private func buttonAction(button: UIButton) { let index: Int = button.tag-1000 self.showControllerIndex(index: index) } } extension XHTabBar{ /** * 切换显示控制器 * * - param: index 位置 */ public func showControllerIndex(index: Int) { guard index < controllerArray.count else { print("error:index="+"\(index)"+"超出范围") return; } self.seleBtn!.isSelected = false let button = (cusTabbar.viewWithTag(1000+index) as? UIButton)! button.isSelected = true self.seleBtn = button self.selectedIndex = index } /** * 设置数字角标 * * - param: num 所要显示数字 * - param: index 位置 */ public func showBadgeMark(badge: Int, index: Int) { guard index < controllerArray.count else { print("error:index="+"\(index)"+"超出范围") return; } let numLabel = (self.view.viewWithTag(1020+index) as? UILabel)! numLabel.isHidden = false var nFrame = numLabel.frame if badge <= 0 { //隐藏角标 self.hideMarkIndex(index: index) } else { if badge > 0 && badge <= 9 { nFrame.size.width = numMarkD } else if badge > 9 && badge <= 19 { nFrame.size.width = numMarkD+5 } else { nFrame.size.width = numMarkD+10 } nFrame.size.height = numMarkD numLabel.frame = nFrame numLabel.layer.cornerRadius = numMarkD/2.0 numLabel.text = "\(badge)" if badge > 99 { numLabel.text = "99+" } } } /** * 设置小红点 * * - param: index 位置 */ public func showPointMarkIndex(index: Int) { guard index < controllerArray.count else { print("error:index="+"\(index)"+"超出范围") return; } let numLabel = (cusTabbar.viewWithTag(1020+index) as? UILabel)! numLabel.isHidden = false var nFrame = numLabel.frame nFrame.size.height = pointMarkD nFrame.size.width = pointMarkD numLabel.frame = nFrame numLabel.layer.cornerRadius = pointMarkD/2.0 numLabel.text = "" } /** * 影藏指定位置角标 * * - param: index 位置 */ public func hideMarkIndex(index: Int) { guard index < controllerArray.count else { print("error:index="+"\(index)"+"超出范围") return; } let numLabel = (cusTabbar.viewWithTag(1020+index) as? UILabel)! numLabel.isHidden = true } } //MARK: - TabBarButton class XHTabBarButton:UIButton { override init(frame: CGRect) { super.init(frame: frame) imageView?.contentMode = UIViewContentMode.scaleAspectFit titleLabel?.textAlignment = NSTextAlignment.center } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func imageRect(forContentRect contentRect: CGRect) -> CGRect { let newX:CGFloat = 0.0 let newY:CGFloat = 5.0 let newWidth:CGFloat = CGFloat(contentRect.size.width) let newHeight:CGFloat = CGFloat(contentRect.size.height)*scale-newY return CGRect.init(x: newX, y: newY, width: newWidth, height: newHeight) } override func titleRect(forContentRect contentRect: CGRect) -> CGRect { let newX: CGFloat = 0 let newY: CGFloat = contentRect.size.height*scale let newWidth: CGFloat = contentRect.size.width let newHeight: CGFloat = contentRect.size.height-contentRect.size.height*scale return CGRect.init(x: newX, y: newY, width: newWidth, height: newHeight) } }
eb3a93dabfc23b40e7f1235680c7c0db
26.502591
131
0.559533
false
false
false
false
luksfarris/SwiftRandomForest
refs/heads/master
SwiftRandomForest/DataStructures/MatrixReference.swift
mit
1
//MIT License // //Copyright (c) 2017 Lucas Farris // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. import Foundation class MatrixReference<T:Numeric> { public private(set) var matrix:Matrix<T> public private(set) var rows:Array<Int> = [] public private(set) var count:Int = 0 public private(set) var maxCount:Int = 0 public private(set) var columns:Int = 0 init (matrix:Matrix<T>) { self.matrix = matrix self.maxCount = matrix.rows self.columns = matrix.columns } init (matrixReference:MatrixReference<T>, count:Int) { self.matrix = matrixReference.matrix self.maxCount = count self.columns = matrixReference.columns } public func elementAt(_ row:Int, _ column:Int) -> T { let realRow = self.rows[row] return self.matrix[realRow,column] } public func rowAtIndex(_ index: Int) -> ArraySlice<T> { let realIndex = self.rows[index] return self.matrix.rowAtIndex(realIndex) } public func remove(_ index:Int) -> Int { let poppedIndex:Int = self.rows.remove(at: index) self.count -= 1 self.maxCount -= 1 return poppedIndex } public func append(index:Int) { self.count += 1 self.rows.append(index) } public func append(otherMatrix:MatrixReference<T>) { self.count += otherMatrix.count for i in 0..<otherMatrix.count { let value = otherMatrix.rows[i] self.rows.append(value) } } public func fill(_ count:Int) { self.count = count for i in 0..<self.count { self.rows.append(i) } } func makeIterator() -> MatrixReferenceIterator<T> { return MatrixReferenceIterator<T>(rows: self.rows, count:self.count, matrix:self.matrix) } } struct MatrixReferenceIterator<T:Numeric> : IteratorProtocol { private var rows:Array<Int> private var matrix:Matrix<T> private var count:Int private var index = 0 init(rows:Array<Int>, count:Int, matrix:Matrix<T>) { self.rows = rows self.count = count self.matrix = matrix } mutating func next() -> ArraySlice<T>? { if self.index < self.count { let realIndex = self.rows[self.index] self.index += 1 return self.matrix.rowAtIndex(realIndex) } else { return nil } } } extension MatrixReference { var outputs: Array<T> { var outputsArray:Array<T> = [] for i in 0..<self.count { let row = self.rows[i] outputsArray.append(self.matrix[row,self.columns - 1]) } return outputsArray } }
be0d523cfbd46c1299cdf53a81c99c29
30.957627
96
0.639883
false
false
false
false
timd/Flashcardr
refs/heads/master
Flashcards/LearnCollectionViewCell.swift
mit
1
// // LearnCollectionViewCell.swift // Flashcards // // Created by Tim on 22/07/15. // Copyright (c) 2015 Tim Duckett. All rights reserved. // import UIKit class LearnCollectionViewCell: UICollectionViewCell { weak var delegate: LearnCellDelegateProtocol? @IBOutlet weak var mainAntwort: UILabel! @IBOutlet weak var antwortWort: UILabel! var showEnglisch: Bool = false var card: Card? { didSet { updateUI() } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func drawRect(rect: CGRect) { super.drawRect(rect) } override func prepareForReuse() { mainAntwort.text = "" antwortWort.text = "" antwortWort.hidden = true } func didTapInCell() { antwortWort.hidden = false delegate?.didRevealAnswerForCell(self) } func updateUI() { let doubleTap = UITapGestureRecognizer(target: self, action: "didTapInCell") doubleTap.numberOfTapsRequired = 2 doubleTap.numberOfTouchesRequired = 1 self.contentView.addGestureRecognizer(doubleTap) if showEnglisch { mainAntwort.text = card?.englisch antwortWort.text = card?.deutsch } else { mainAntwort.text = card?.deutsch antwortWort.text = card?.englisch } antwortWort.hidden = true } }
59ee1d1c1de52ea630bf5a5ca2609dff
22.15625
84
0.60054
false
false
false
false
huangboju/AsyncDisplay_Study
refs/heads/master
AsyncDisplay/Weibo/WeiBoCellNode.swift
mit
1
// // WeiBoCellNode.swift // AsyncDisplay // // Created by 伯驹 黄 on 2017/5/11. // Copyright © 2017年 伯驹 黄. All rights reserved. // import AsyncDisplayKit class WeiBoCellNode: ASCellNode { var weiBoMainNode: WeiBoMainNode! convenience init(item: MainModel) { self.init() selectionStyle = .none backgroundColor = kWBCellBackgroundColor weiBoMainNode = WeiBoMainNode(item: item) addSubnode(weiBoMainNode) } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { return ASInsetLayoutSpec(insets: UIEdgeInsets(top: kWBCellTopMargin, left: 0, bottom: 0, right: 0), child: weiBoMainNode) } } class WeiBoMainNode: ASDisplayNode { var vipBackgroundNode: ASNetworkImageNode! var titleNode: WBStatusTitleNode? var profileNode: WBStatusProfileNode! var textNode: ASTextNode! var retweetTextNode: ASTextNode? var toolBarNode: WBStatusToolbarNode! var cardNode: WBStatusCardNode? var retweetBgNode: ASDisplayNode? lazy var picNodes: [ASInsetLayoutSpec] = [] var linkManager: LinkManager? convenience init(item: MainModel) { self.init() backgroundColor = UIColor.white borderWidth = onePix borderColor = kWBCellLineColor.cgColor vipBackgroundNode = ASNetworkImageNode() vipBackgroundNode.url = item.vipUrl vipBackgroundNode.imageModificationBlock = { image, _ in return UIImage(cgImage: image.cgImage!, scale: 2, orientation: image.imageOrientation) } vipBackgroundNode.isLayerBacked = true vipBackgroundNode.contentMode = .topRight vipBackgroundNode.style.height = ASDimensionMake(14) vipBackgroundNode.style.width = ASDimensionMake(screenW) addSubnode(vipBackgroundNode) if let titleModel = item.titleModel { titleNode = WBStatusTitleNode(item: titleModel) addSubnode(titleNode!) } profileNode = WBStatusProfileNode(item: item.profileModel) addSubnode(profileNode) textNode = ASTextNode() textNode.isUserInteractionEnabled = true textNode.attributedText = item.text linkManager = LinkManager() textNode.delegate = linkManager textNode.linkAttributeNames = [kLinkAttributeName.rawValue] addSubnode(textNode) if let retweetText = item.retweetText { retweetBgNode = ASDisplayNode() retweetBgNode?.isLayerBacked = true retweetBgNode?.backgroundColor = kWBCellBackgroundColor addSubnode(retweetBgNode!) retweetTextNode = ASTextNode() retweetTextNode?.isUserInteractionEnabled = true retweetTextNode?.delegate = linkManager retweetTextNode?.linkAttributeNames = [kLinkAttributeName.rawValue] retweetTextNode?.attributedText = retweetText addSubnode(retweetTextNode!) } if let picsMode = item.pics { let side = ASDimensionMake(picsMode.count > 1 ? 96 : 148) for item in picsMode { let imageNode = WBStatusPicNode(badgeName: item.badgeName) imageNode.backgroundColor = UIColor(white: 0.8, alpha: 1) imageNode.style.width = side imageNode.style.height = side // TODO: 微博的图片是WebP Image imageNode.url = item.url addSubnode(imageNode) picNodes.append(ASInsetLayoutSpec(insets: UIEdgeInsets(top: 4, left: 0, bottom: 0, right: 4), child: imageNode)) } } if let card = item.cardModel, item.pics == nil { cardNode = WBStatusCardNode(item: card) addSubnode(cardNode!) } toolBarNode = WBStatusToolbarNode(item: item.toolBarModel) addSubnode(toolBarNode) } // 这个是控制可点击字符串的高亮 override func didLoad() { // enable highlighting now that self.layer has loaded -- see ASHighlightOverlayLayer.h layer.as_allowsHighlightDrawing = true super.didLoad() } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { var children: [ASLayoutElement] = [vipBackgroundNode] // titleView if let titleView = titleNode { children.append(titleView) } let headerStack = ASStackLayoutSpec(direction: .vertical, spacing: 0, justifyContent: .start, alignItems: .start, children: children) // profileNode textNode textNode.style.spacingBefore = kWBCellPaddingText children = [profileNode, textNode] let profileAndTextStack = ASStackLayoutSpec(direction: .vertical, spacing: 0, justifyContent: .start, alignItems: .start, children: children) let top: CGFloat = titleNode != nil ? 12 : 0 let profileAndTextInset = ASInsetLayoutSpec(insets: UIEdgeInsets(top: top, left: kWBCellPadding, bottom: 0, right: kWBCellPadding), child: profileAndTextStack) children = [] // retweetTextNode if let retweetTextNode = retweetTextNode { children.append(retweetTextNode) } // picNodesStack if !picNodes.isEmpty { // !!!: 当设置为竖直方向时,主轴和交叉轴也会变 let picsStack = ASStackLayoutSpec(direction: .horizontal, spacing: 0, justifyContent: .start, alignItems: .start, children: picNodes) children.append(picsStack) picsStack.style.spacingBefore = 8 picsStack.flexWrap = .wrap } if let cardNode = cardNode { cardNode.style.spacingBefore = 8 children.append(cardNode) } let retweetStack = ASStackLayoutSpec(direction: .vertical, spacing: 0, justifyContent: .start, alignItems: .start, children: children) let retweetInset = ASInsetLayoutSpec(insets: UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12), child: retweetStack) let footerStack = ASStackLayoutSpec(direction: .vertical, spacing: kWBCellPaddingText, justifyContent: .start, alignItems: .start, children: [retweetInset, toolBarNode]) let retweetBgLayout = ASBackgroundLayoutSpec(child: footerStack, background: retweetBgNode ?? ASLayoutSpec()) retweetBgLayout.style.spacingBefore = kWBCellPaddingText children = [headerStack, profileAndTextInset, retweetBgLayout] let mainStack = ASStackLayoutSpec(direction: .vertical, spacing: 0, justifyContent: .start, alignItems: .start, children: children) return mainStack } }
d6e1aff6f2808b4ba0ef7741c51d98da
35.765363
177
0.663425
false
false
false
false
KrishMunot/swift
refs/heads/master
test/Serialization/Inputs/inherited-conformance-base.swift
apache-2.0
4
// Adopt ForwardIndex via BidirectionalIndex. public struct Counter<T: protocol<RandomAccessIndex, IntegerLiteralConvertible>> : BidirectionalIndex { public var value = 0 public func predecessor() -> Counter { return Counter(value: value - 1) } public func successor() -> Counter { return Counter(value: value + 1) } public init(value: Int) { self.value = value } } public func == <T>(lhs: Counter<T>, rhs: Counter<T>) -> Bool { return lhs.value == rhs.value }
cb0f993812a9f0c33515798d10149d19
24.789474
103
0.681633
false
false
false
false
TerryCK/GogoroBatteryMap
refs/heads/master
GogoroMap/Myplayground.playground/Sources/BatteryStationPointAnnotation.swift
mit
1
// // BatteryStationPointAnnotation.swift // GogoroMap // // Created by 陳 冠禎 on 23/02/2019. // Copyright © 2019 陳 冠禎. All rights reserved. // import UIKit import MapKit public protocol BatteryStationPointAnnotationProtocol: Hashable { func merge(newStations: [Self], oldStations: [Self]) -> [Self] } public extension BatteryStationPointAnnotationProtocol where Self: MKPointAnnotation { func merge(newStations: [Self], oldStations: [Self]) -> [Self] { return Array(Set<Self>(oldStations).intersection(newStations).union(newStations)) } } public final class BatteryStationPointAnnotation: MKPointAnnotation, BatteryStationPointAnnotationProtocol { public let image: UIImage, placemark: MKPlacemark, address: String, isOpening: Bool public var checkinCounter: Int? = nil, checkinDay: String? = nil public init(station: ResponseStationProtocol) { let name = station.name.localized() ?? "" let location = CLLocationCoordinate2D(latitude: station.latitude, longitude: station.longitude) placemark = MKPlacemark(coordinate: location, addressDictionary: [name: ""]) image = station.annotationImage address = station.address.localized() ?? "" isOpening = station.isOpening super.init() title = name subtitle = "\("Open hours:") \(station.availableTime ?? "")" coordinate = location } }
646244561d67b6b53e2b968a409c3d80
32.883721
108
0.678106
false
false
false
false
sunny-fish/teamlobo
refs/heads/master
ARPlay/ARPlay/Renderer.swift
unlicense
1
// // Renderer.swift // ARPlay // // Created by Eric Berna on 7/22/17. // Copyright © 2017 Sunny Fish. All rights reserved. // import UIKit import SceneKit class Renderer: NSObject { let cupCount = 3 let cupNode: SCNNode let ballNode: SCNNode let scene = SCNScene(named: "art.scnassets/RedPlasticCup.scn")! var cups = [SCNNode]() var positions = [SCNVector3]() var ballOriginalPosition: SCNVector3 var ballPositionDeltas = [Float]() var cupGame: CupShuffle override init() { cupNode = scene.rootNode.childNode(withName: "Cup", recursively: true)! ballNode = scene.rootNode.childNode(withName: "Ball", recursively: true)! cupGame = CupShuffle(cups: cupCount) ballOriginalPosition = ballNode.position super.init() cupGame.AddBall() cupNode.removeFromParentNode() for i in 0..<cupCount { let cupCopy: SCNNode = cupNode.clone() cups.append(cupCopy) cupCopy.position = SCNVector3(cupCopy.position.x + (0.3 * Float(i)), cupCopy.position.y, cupCopy.position.z) scene.rootNode.addChildNode(cupCopy) } positions = cups.map({ (node) -> SCNVector3 in return node.position }) for i in 0..<cupCount { let first = positions[0] let this = positions[i] ballPositionDeltas.append(this.x - first.x) } } func parentCup(from node: SCNNode) -> SCNNode? { if node.name == "Cup" { return node } guard let parent = node.parent else { return nil } return parentCup(from:parent) } func lift(cup: SCNNode) { guard let parentCup = parentCup(from: cup) else { return } ballNode.isHidden = false let destination = SCNVector3(parentCup.position.x, parentCup.position.y + 0.3, parentCup.position.z) let action = SCNAction.move(to: destination, duration: 0.5) parentCup.runAction(action) } func moveCups() { let move = cupGame.ShuffleCupsOnce() let fromPosition = positions[move.from] let toPosition = positions[move.to] let act1 = moveCup(from: move.from, to: move.to) let act2 = moveCup(from: move.to, to: move.from) self.cups[move.from].runAction(act1) self.cups[move.to].runAction(act2) positions[move.from] = toPosition positions[move.to] = fromPosition if (cupGame.gameCups.cups[move.from].hasBall) { self.moveBall(to: move.to) } if (cupGame.gameCups.cups[move.to].hasBall) { self.moveBall(to: move.from) } } func moveCup(from: Int, to: Int) -> SCNAction { let zDirection: Float = from > to ? -1 : 1 let fromPosition = positions[from] let toPosition = positions[to] let halfPosition = SCNVector3(((toPosition.x - fromPosition.x) / 2.0) + fromPosition.x, toPosition.y, toPosition.z + (0.2 * zDirection)) let first = SCNAction.move(to: halfPosition, duration: 0.5) let second = SCNAction.move(to: toPosition, duration: 0.5) let sequence = SCNAction.sequence([first, second]) return sequence } func moveBall(to position: Int) { ballNode.position = SCNVector3(ballNode.position.x + ballPositionDeltas[position], ballNode.position.y, ballNode.position.z) } func reset() { for i in 0..<cupCount { let cup = cups[i] let position = positions[i] let upPosition = SCNVector3(position.x, position.y + 0.3, position.z) cup.position = upPosition let action = SCNAction.move(to: position, duration: 0.8) cup.runAction(action) } let ballWait = SCNAction.wait(duration: 0.8) let ballHide = SCNAction.hide() let ballSequence = SCNAction.sequence([ballWait, ballHide]) ballNode.runAction(ballSequence) cupGame.AddBall() } }
785bdcd7f81a5802facb32402535a93e
27.175182
126
0.633679
false
false
false
false
pviafore/AdventOfCode2016
refs/heads/master
day19/challenge2/challenge2.swift
mit
1
public class Node { var value: Int init(value: Int) { self.value = value } var next: Node? = nil weak var previous: Node? } func createList(size: Int) -> Node { let head:Node = Node(value: 1) var tail:Node = head for index in 2...size { let node = Node(value:index) node.previous = tail tail.next = node tail = node } head.previous = tail tail.next = head return head } func removeSelf(node: Node) -> Node { let nextNode = node.next! let previousNode = node.previous! previousNode.next = nextNode nextNode.previous = previousNode return nextNode } func josephus(circleSize: Int)-> Int { var list: Node = createList(size: circleSize) for _ in 1...circleSize/2 { list=list.next! } for size in stride(from: circleSize, to: 1, by: -1) { list = removeSelf(node:list) if (size % 2 == 1){ list=list.next! } } return list.value } print(josephus(circleSize: 3014603))
2d36bb9efb657ce32f799646b9074570
21.12766
57
0.584615
false
false
false
false
pdil/PDColorPicker
refs/heads/master
Examples/Tests/PDColorNamedColorsSpec.swift
mit
1
// // PDColorNamedColorsSpec.swift // PDColorPickerTests // // Created by Paolo Di Lorenzo on 8/29/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Quick import Nimble import PDColorPicker class PDColorNamedColorsSpec: QuickSpec { override func spec() { describe("red") { it("produces correct RGB values") { let rgb = PDColor.red.rgba expect(rgb.r).to(equal(1)) expect(rgb.g).to(equal(0)) expect(rgb.b).to(equal(0)) } it("produces correct hex string") { expect(PDColor.red.hex).to(equal("#ff0000")) } } describe("orange") { it("produces correct RGB values") { let rgb = PDColor.orange.rgba expect(rgb.r).to(equal(1)) expect(rgb.g).to(equal(0.5)) expect(rgb.b).to(equal(0)) } it("produces correct hex string") { expect(PDColor.orange.hex).to(equal("#ff7f00")) } } describe("yellow") { it("produces correct RGB values") { let rgb = PDColor.yellow.rgba expect(rgb.r).to(equal(1)) expect(rgb.g).to(equal(1)) expect(rgb.b).to(equal(0)) } it("produces correct hex string") { expect(PDColor.yellow.hex).to(equal("#ffff00")) } } describe("yellowGreen") { it("produces correct RGB values") { let rgb = PDColor.yellowGreen.rgba expect(rgb.r).to(equal(0.5)) expect(rgb.g).to(equal(1)) expect(rgb.b).to(equal(0)) } it("produces correct hex string") { expect(PDColor.yellowGreen.hex).to(equal("#7fff00")) } } describe("green") { it("produces correct RGB values") { let rgb = PDColor.green.rgba expect(rgb.r).to(equal(0)) expect(rgb.g).to(equal(1)) expect(rgb.b).to(equal(0)) } it("produces correct hex string") { expect(PDColor.green.hex).to(equal("#00ff00")) } } describe("cyan") { it("produces correct RGB values") { let rgb = PDColor.cyan.rgba expect(rgb.r).to(equal(0)) expect(rgb.g).to(equal(1)) expect(rgb.b).to(equal(1)) } it("produces correct hex string") { expect(PDColor.cyan.hex).to(equal("#00ffff")) } } describe("azure") { it("produces correct RGB values") { let rgb = PDColor.azure.rgba expect(rgb.r).to(equal(0)) expect(rgb.g).to(equal(0.5)) expect(rgb.b).to(equal(1)) } it("produces correct hex string") { expect(PDColor.azure.hex).to(equal("#007fff")) } } describe("blue") { it("produces correct RGB values") { let rgb = PDColor.blue.rgba expect(rgb.r).to(equal(0)) expect(rgb.g).to(equal(0)) expect(rgb.b).to(equal(1)) } it("produces correct hex string") { expect(PDColor.blue.hex).to(equal("#0000ff")) } } describe("purple") { it("produces correct RGB values") { let rgb = PDColor.purple.rgba expect(rgb.r).to(equal(0.5)) expect(rgb.g).to(equal(0)) expect(rgb.b).to(equal(1)) } it("produces correct hex string") { expect(PDColor.purple.hex).to(equal("#7f00ff")) } } describe("magenta") { it("produces correct RGB values") { let rgb = PDColor.magenta.rgba expect(rgb.r).to(equal(1)) expect(rgb.g).to(equal(0)) expect(rgb.b).to(equal(1)) } it("produces correct hex string") { expect(PDColor.magenta.hex).to(equal("#ff00ff")) } } describe("pink") { it("produces correct RGB values") { let rgb = PDColor.pink.rgba expect(rgb.r).to(equal(1)) expect(rgb.g).to(equal(0)) expect(rgb.b).to(equal(0.5)) } it("produces correct hex string") { expect(PDColor.pink.hex).to(equal("#ff007f")) } } describe("white") { it("produces correct RGB values") { let rgb = PDColor.white.rgba expect(rgb.r).to(equal(1)) expect(rgb.g).to(equal(1)) expect(rgb.b).to(equal(1)) } it("produces correct hex string") { expect(PDColor.white.hex).to(equal("#ffffff")) } } describe("black") { it("produces correct RGB values") { let rgb = PDColor.black.rgba expect(rgb.r).to(equal(0)) expect(rgb.g).to(equal(0)) expect(rgb.b).to(equal(0)) } it("produces correct hex string") { expect(PDColor.black.hex).to(equal("#000000")) } } } }
a7625039b13883bfe458c80a47939262
22.135678
60
0.544309
false
false
false
false
AmitaiB/AmazingAgeTrick
refs/heads/master
AmazingAgeTrick/AATMainViewController.swift
mit
1
// // ViewController.swift // AmazingAgeTrick // // Created by Amitai Blickstein on 12/29/15. // Copyright © 2015 Amitai Blickstein, LLC. All rights reserved. // import UIKit import FlatUIColors ///import iAd class AATMainViewController: UIViewController { @IBOutlet weak var instructionsTextView: UITextView! @IBOutlet weak var startGameButton: UIButton! @IBOutlet weak var creditsSegueButton: UIButton! override func viewDidLoad() { super.viewDidLoad() /// self.canDisplayBannerAds = false originalContentView.backgroundColor = FlatUIColors.cloudsColor() setupTextView() setupStartButton() setupCreditsSegueButton() } func setupCreditsSegueButton() { creditsSegueButton.sizeToFit() } func setupTextView() { instructionsTextView.editable = true instructionsTextView.backgroundColor = FlatUIColors.midnightBlueColor() instructionsTextView.textColor = FlatUIColors.peterRiverColor() setupViewShadow(instructionsTextView.layer) instructionsTextView.layer.borderWidth = 2 instructionsTextView.layer.borderColor = FlatUIColors.sunflowerColor().CGColor instructionsTextView.contentInset = UIEdgeInsets.init(top: -30, left: 10, bottom: 10, right: 10) instructionsTextView.text = "\n Amazing Age Trick\n Instructions\n\n Tap YES/NO if your age does/does not appear on the card, THEN SWIPE TO THE NEXT CARD! 😃" instructionsTextView.textContainer.lineBreakMode = .ByWordWrapping instructionsTextView.textContainerInset = UIEdgeInsets(top: -10, left: 3, bottom: 3, right: 3) instructionsTextView.editable = false // instructionsTextView.font = UIFont(descriptor: , size: <#T##CGFloat#>) } func setupStartButton() { startGameButton.backgroundColor = FlatUIColors.wisteriaColor() startGameButton.titleLabel?.textColor = FlatUIColors.peterRiverColor() startGameButton.titleLabel?.font = UIFont(name: "MarkerFelt-Wide", size: 20) startGameButton.layer.cornerRadius = 10.0 setupViewShadow(startGameButton.layer) } /* func setupViewShadow(layer:CALayer) { layer.shadowColor = UIColor.blackColor().CGColor layer.shadowOpacity = 0.25 layer.shadowOffset = CGSizeMake(0, 1.5) layer.shadowRadius = 4.0 layer.shouldRasterize = true layer.rasterizationScale = UIScreen.mainScreen().scale } */ func createAutolayoutConstraints() { let views = ["textV" : instructionsTextView, "startB" : startGameButton, "creditsB" : creditsSegueButton] let metrics = ["creditsPadding" : creditsButtonPadding(creditsSegueButton)] for view in views.values { prepareForAutolayout(view) } let hTextViewConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textV]-|", options: .AlignAllCenterX, metrics: nil, views: views) let hStartButtonConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[startB]-20-|", options: .AlignAllCenterX, metrics: nil, views: views) let hCreditsButtonConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-creditsPadding-[creditsB]-creditsPadding-|", options: .AlignAllCenterX, metrics: metrics, views: views) let vAllViewsConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-30-[textV]-100-[startB]-[creditsB]-|", options: .AlignAllCenterX, metrics: nil, views: views) view.addConstraints(hTextViewConstraints + hStartButtonConstraints + hCreditsButtonConstraints + vAllViewsConstraints) } func prepareForAutolayout(view:UIView) { view.translatesAutoresizingMaskIntoConstraints = false view.removeConstraints(view.constraints) } func creditsButtonPadding(button:UIButton)->NSNumber { let totalPadding = UIScreen.mainScreen().bounds.width - button.intrinsicContentSize().width let paddingNumber: NSNumber = Float(totalPadding) / 2.0 return paddingNumber } }
29ca76c9f7eb0b4f269f9a042503968b
40.666667
195
0.705455
false
false
false
false
JustinJiaDev/SwiftShell
refs/heads/master
SwiftShell/Internals/Process.swift
mit
1
// // Process.swift // SwiftShell // // Created by Justin Jia on 5/21/16. // Copyright © 2016 SwiftShell. The MIT License (MIT). // import Foundation extension Process { static func run(path: String, arguments: [String] = [], output: Pipe? = nil, input: Pipe? = nil) -> Pipe { let output = output ?? Pipe() let process = Process() process.launchPath = path process.arguments = arguments process.standardOutput = output process.standardInput = input process.launch() return output } static func currentPath(folding: Bool = false, unlessExceeds limit: Int = 0) -> String { var buffer: [Int8] = Array(repeating: 0, count: Int(PATH_MAX)) getcwd(&buffer, buffer.count) var output = String(cString: buffer) guard folding == true, output.characters.count > limit else { return output } let pathComponents = output.characters.split { $0 == "/" }.map(String.init) guard pathComponents.count > 2 else { return output } if let firstComponent = pathComponents.first, let lastComponent = pathComponents.last { output = "/" + firstComponent + "/.../" + lastComponent } return output } }
cbc82d34d129def3f20a67bd5643cdbb
34.542857
110
0.619775
false
false
false
false
shamanskyh/FluidQ
refs/heads/master
FluidQ/Static Magic Sheet/StaticMagicSheetViewController.swift
mit
1
// // StaticMagicSheetViewController.swift // FluidQ // // Created by Harry Shamansky on 12/2/15. // Copyright © 2015 Harry Shamansky. All rights reserved. // // Note: Create magic sheet in Interface Builder (IB) // Use UIButtons of custom class MagicSheetButton. Each button should have a // user-defined key of type string called "gelColor". The value should be a gel // manufacturer's color code, such as "R40", "L201", or "N/C". // The Button's title should be its channel number. Use AutoLayout to define // spacing. Be sure to add all buttons to the buttons IBOutletCollection via // Interface Builder. import UIKit class StaticMagicSheetViewController: UIViewController { // IBOutletCollection of buttons. Make sure all buttons are added to this! @IBOutlet var buttons: [MagicSheetButton]! /// calculated property that returns the color changing channels /// - Complexity: O(N) var colorChangingChannels: [Int] { return buttons.filter({ $0.isColorChanging }).map({ Int($0.titleLabel!.text!)! }) } // MARK: Utility Functions func selectedChannels() -> [Int] { var returnArray: [Int] = [] for button in buttons { if button.selected { if let intRep = Int((button.titleLabel?.text)!) { returnArray.append(intRep) } } } return returnArray } func sendSelection(selection: Selection) { var isColorChanging = true for channel in selection.selectedChannels { if !colorChangingChannels.contains(channel) { isColorChanging = false break } } selection.isColorChangingCapable = isColorChanging (UIApplication.sharedApplication().delegate as! AppDelegate).multipeerManager.sendSelection(selection) } // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() view.multipleTouchEnabled = true } // MARK: IBActions @IBAction func toggleButton(sender: UIButton) { sender.selected = !sender.selected let selection = Selection(withSelectedChannels: selectedChannels()) sendSelection(selection) } // MARK: Rectangular Selection var selectionRectangleView: UIView? var trueOrigin = CGPointZero var additiveSelection = false override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let touchPoint = touches.first!.locationInView(view) additiveSelection = true trueOrigin = touchPoint if !additiveSelection { for button in buttons { button.selected = false } } selectionRectangleView?.removeFromSuperview() selectionRectangleView = UIView() selectionRectangleView?.backgroundColor = UIColor(red: 1.0, green: (65.0 / 255.0), blue: 0.0, alpha: 0.5) selectionRectangleView?.frame = CGRect(origin: touchPoint, size: CGSizeZero) if let rectView = selectionRectangleView { view.addSubview(rectView) } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { let touchPoint = touches.first!.locationInView(view) guard let rect = selectionRectangleView else { return } let xDelta = touchPoint.x - trueOrigin.x let yDelta = touchPoint.y - trueOrigin.y if xDelta >= 0 && yDelta >= 0 { rect.frame = CGRect(origin: rect.frame.origin, size: CGSize(width: xDelta, height: yDelta)) } else if xDelta >= 0 && yDelta < 0 { rect.frame = CGRect(x: trueOrigin.x, y: touchPoint.y, width: abs(xDelta), height: abs(yDelta)) } else if xDelta < 0 && yDelta >= 0 { rect.frame = CGRect(x: touchPoint.x, y: trueOrigin.y, width: abs(xDelta), height: abs(yDelta)) } else { rect.frame = CGRect(origin: touchPoint, size: CGSize(width: abs(xDelta), height: abs(yDelta))) } // selection for button in buttons { let buttonRectInMainView = view.convertRect(button.bounds, fromView: button) if rect.frame.contains(CGPoint(x: buttonRectInMainView.midX, y: buttonRectInMainView.midY)) { if additiveSelection && !button.didToggle { button.selected = !button.selected button.didToggle = true } else { button.selected = true } } else if !additiveSelection { button.selected = false } } } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { for button in buttons { button.didToggle = false } selectionRectangleView?.removeFromSuperview() } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { // if the selection rectangle was small, consider it a deselection if selectionRectangleView!.frame.size.height < 20 && selectionRectangleView!.frame.size.width < 20 { for button in buttons { button.selected = false } } let selection = Selection(withSelectedChannels: selectedChannels()) sendSelection(selection) for button in buttons { button.didToggle = false } selectionRectangleView?.removeFromSuperview() } // MARK: - Rotation override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { coordinator.animateAlongsideTransition({ (context: UIViewControllerTransitionCoordinatorContext) -> Void in //self.buttons.forEach({ $0.invalidateIntrinsicContentSize(); $0.setNeedsDisplay() }) }, completion: nil) } }
7975dc5b1e2ac64775863d47ead3bb99
35.343195
163
0.610387
false
false
false
false
takeo-asai/math-puzzle
refs/heads/master
problems/16.swift
mit
1
let sqrts = (1 ... 125).map {Double($0*$0)} func isCreatable(x2: Double, _ length: Int) -> Bool { for a in 1 ..< length/2 { let b = length/2 - a if a != b && Double(a * b) == x2 { return true } } return false } var count = 0 var list: [[Double]] = [] for length in 8 ... 500 { let c2 = Double(length/4) * Double(length/4) for a2 in sqrts.filter({$0 < c2}) { let b2 = c2 - a2 if a2 < b2 && isCreatable(a2, length) && isCreatable(b2, length) && sqrts.contains(b2) { count++ list += [[a2, b2, c2]] } } } print(list)
54729064c7d835cca54b648f2930d44e
20.68
90
0.555351
false
false
false
false
apple/swift-argument-parser
refs/heads/main
Sources/ArgumentParser/Parsing/CommandParser.swift
apache-2.0
1
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2020 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 // //===----------------------------------------------------------------------===// struct CommandError: Error { var commandStack: [ParsableCommand.Type] var parserError: ParserError } struct HelpRequested: Error { var visibility: ArgumentVisibility } struct CommandParser { let commandTree: Tree<ParsableCommand.Type> var currentNode: Tree<ParsableCommand.Type> var decodedArguments: [DecodedArguments] = [] var rootCommand: ParsableCommand.Type { commandTree.element } var commandStack: [ParsableCommand.Type] { let result = decodedArguments.compactMap { $0.commandType } if currentNode.element == result.last { return result } else { return result + [currentNode.element] } } init(_ rootCommand: ParsableCommand.Type) { do { self.commandTree = try Tree(root: rootCommand) } catch Tree<ParsableCommand.Type>.InitializationError.recursiveSubcommand(let command) { fatalError("The ParsableCommand \"\(command)\" can't have itself as its own subcommand.") } catch { fatalError("Unexpected error: \(error).") } self.currentNode = commandTree // A command tree that has a depth greater than zero gets a `help` // subcommand. if !commandTree.isLeaf { commandTree.addChild(Tree(HelpCommand.self)) } } } extension CommandParser { /// Consumes the next argument in `split` if it matches a subcommand at the /// current node of the command tree. /// /// If a matching subcommand is found, the subcommand argument is consumed /// in `split`. /// /// - Returns: A node for the matched subcommand if one was found; /// otherwise, `nil`. fileprivate func consumeNextCommand(split: inout SplitArguments) -> Tree<ParsableCommand.Type>? { guard let (origin, element) = split.peekNext(), element.isValue, let value = split.originalInput(at: origin), let subcommandNode = currentNode.firstChild(withName: value) else { return nil } _ = split.popNextValue() return subcommandNode } /// Throws a `HelpRequested` error if the user has specified any of the /// built-in flags. /// /// - Parameters: /// - split: The remaining arguments to examine. /// - requireSoloArgument: `true` if the built-in flag must be the only /// one remaining for this to catch it. func checkForBuiltInFlags( _ split: SplitArguments, requireSoloArgument: Bool = false ) throws { guard !requireSoloArgument || split.count == 1 else { return } // Look for help flags guard !split.contains(anyOf: self.commandStack.getHelpNames(visibility: .default)) else { throw HelpRequested(visibility: .default) } // Look for help-hidden flags guard !split.contains(anyOf: self.commandStack.getHelpNames(visibility: .hidden)) else { throw HelpRequested(visibility: .hidden) } // Look for dump-help flag guard !split.contains(Name.long("experimental-dump-help")) else { throw CommandError(commandStack: commandStack, parserError: .dumpHelpRequested) } // Look for a version flag if any commands in the stack define a version if commandStack.contains(where: { !$0.configuration.version.isEmpty }) { guard !split.contains(Name.long("version")) else { throw CommandError(commandStack: commandStack, parserError: .versionRequested) } } } /// Returns the last parsed value if there are no remaining unused arguments. /// /// If there are remaining arguments or if no commands have been parsed, /// this throws an error. fileprivate func extractLastParsedValue(_ split: SplitArguments) throws -> ParsableCommand { try checkForBuiltInFlags(split) // We should have used up all arguments at this point: guard !split.containsNonTerminatorArguments else { // Check if one of the arguments is an unknown option for element in split.elements { if case .option(let argument) = element.value { throw ParserError.unknownOption(InputOrigin.Element.argumentIndex(element.index), argument.name) } } let extra = split.coalescedExtraElements() throw ParserError.unexpectedExtraValues(extra) } guard let lastCommand = decodedArguments.lazy.compactMap({ $0.command }).last else { throw ParserError.invalidState } return lastCommand } /// Extracts the current command from `split`, throwing if decoding isn't /// possible. fileprivate mutating func parseCurrent(_ split: inout SplitArguments) throws -> ParsableCommand { // Build the argument set (i.e. information on how to parse): let commandArguments = ArgumentSet(currentNode.element, visibility: .private, parent: .root) // Parse the arguments, ignoring anything unexpected let values = try commandArguments.lenientParse( split, subcommands: currentNode.element.configuration.subcommands, defaultCapturesAll: currentNode.element.defaultIncludesUnconditionalArguments) // Decode the values from ParsedValues into the ParsableCommand: let decoder = ArgumentDecoder(values: values, previouslyDecoded: decodedArguments) var decodedResult: ParsableCommand do { decodedResult = try currentNode.element.init(from: decoder) } catch let error { // If decoding this command failed, see if they were asking for // help before propagating that parsing failure. try checkForBuiltInFlags(split) throw error } // Decoding was successful, so remove the arguments that were used // by the decoder. split.removeAll(in: decoder.usedOrigins) // Save the decoded results to add to the next command. let newDecodedValues = decoder.previouslyDecoded .filter { prev in !decodedArguments.contains(where: { $0.type == prev.type })} decodedArguments.append(contentsOf: newDecodedValues) decodedArguments.append(DecodedArguments(type: currentNode.element, value: decodedResult)) return decodedResult } /// Starting with the current node, extracts commands out of `split` and /// descends into subcommands as far as possible. internal mutating func descendingParse(_ split: inout SplitArguments) throws { while true { var parsedCommand = try parseCurrent(&split) // after decoding a command, make sure to validate it do { try parsedCommand.validate() var lastArgument = decodedArguments.removeLast() lastArgument.value = parsedCommand decodedArguments.append(lastArgument) } catch { try checkForBuiltInFlags(split) throw CommandError(commandStack: commandStack, parserError: ParserError.userValidationError(error)) } // Look for next command in the argument list. if let nextCommand = consumeNextCommand(split: &split) { currentNode = nextCommand continue } // Look for the help flag before falling back to a default command. try checkForBuiltInFlags(split, requireSoloArgument: true) // No command was found, so fall back to the default subcommand. if let defaultSubcommand = currentNode.element.configuration.defaultSubcommand { guard let subcommandNode = currentNode.firstChild(equalTo: defaultSubcommand) else { throw ParserError.invalidState } currentNode = subcommandNode continue } // No more subcommands to parse. return } } /// Returns the fully-parsed matching command for `arguments`, or an /// appropriate error. /// /// - Parameter arguments: The array of arguments to parse. This should not /// include the command name as the first argument. mutating func parse(arguments: [String]) -> Result<ParsableCommand, CommandError> { do { try handleCustomCompletion(arguments) } catch { return .failure(CommandError(commandStack: [commandTree.element], parserError: error as! ParserError)) } var split: SplitArguments do { split = try SplitArguments(arguments: arguments) } catch let error as ParserError { return .failure(CommandError(commandStack: [commandTree.element], parserError: error)) } catch { return .failure(CommandError(commandStack: [commandTree.element], parserError: .invalidState)) } do { try checkForCompletionScriptRequest(&split) try descendingParse(&split) let result = try extractLastParsedValue(split) // HelpCommand is a valid result, but needs extra information about // the tree from the parser to build its stack of commands. if var helpResult = result as? HelpCommand { try helpResult.buildCommandStack(with: self) return .success(helpResult) } return .success(result) } catch let error as CommandError { return .failure(error) } catch let error as ParserError { let error = arguments.isEmpty ? ParserError.noArguments(error) : error return .failure(CommandError(commandStack: commandStack, parserError: error)) } catch let helpRequest as HelpRequested { return .success(HelpCommand( commandStack: commandStack, visibility: helpRequest.visibility)) } catch { return .failure(CommandError(commandStack: commandStack, parserError: .invalidState)) } } } // MARK: Completion Script Support struct GenerateCompletions: ParsableCommand { @Option() var generateCompletionScript: String } struct AutodetectedGenerateCompletions: ParsableCommand { @Flag() var generateCompletionScript = false } extension CommandParser { func checkForCompletionScriptRequest(_ split: inout SplitArguments) throws { // Pseudo-commands don't support `--generate-completion-script` flag guard rootCommand.configuration._superCommandName == nil else { return } // We don't have the ability to check for `--name [value]`-style args yet, // so we need to try parsing two different commands. // First look for `--generate-completion-script <shell>` var completionsParser = CommandParser(GenerateCompletions.self) if let result = try? completionsParser.parseCurrent(&split) as? GenerateCompletions { throw CommandError(commandStack: commandStack, parserError: .completionScriptRequested(shell: result.generateCompletionScript)) } // Check for for `--generate-completion-script` without a value var autodetectedParser = CommandParser(AutodetectedGenerateCompletions.self) if let result = try? autodetectedParser.parseCurrent(&split) as? AutodetectedGenerateCompletions, result.generateCompletionScript { throw CommandError(commandStack: commandStack, parserError: .completionScriptRequested(shell: nil)) } } func handleCustomCompletion(_ arguments: [String]) throws { // Completion functions use a custom format: // // <command> ---completion [<subcommand> ...] -- <argument-name> [<completion-text>] // // The triple-dash prefix makes '---completion' invalid syntax for regular // arguments, so it's safe to use for this internal purpose. guard arguments.first == "---completion" else { return } var args = arguments.dropFirst() var current = commandTree while let subcommandName = args.popFirst() { // A double dash separates the subcommands from the argument information if subcommandName == "--" { break } guard let nextCommandNode = current.firstChild(withName: subcommandName) else { throw ParserError.invalidState } current = nextCommandNode } // Some kind of argument name is the next required element guard let argToMatch = args.popFirst() else { throw ParserError.invalidState } // Completion text is optional here let completionValues = Array(args) // Generate the argument set and parse the argument to find in the set let argset = ArgumentSet(current.element, visibility: .private, parent: .root) let parsedArgument = try! parseIndividualArg(argToMatch, at: 0).first! // Look up the specified argument and retrieve its custom completion function let completionFunction: ([String]) -> [String] switch parsedArgument.value { case .option(let parsed): guard let matchedArgument = argset.first(matching: parsed), case .custom(let f) = matchedArgument.completion.kind else { throw ParserError.invalidState } completionFunction = f case .value(let str): guard let matchedArgument = argset.firstPositional(named: str), case .custom(let f) = matchedArgument.completion.kind else { throw ParserError.invalidState } completionFunction = f case .terminator: throw ParserError.invalidState } // Parsing and retrieval successful! We don't want to continue with any // other parsing here, so after printing the result of the completion // function, exit with a success code. let output = completionFunction(completionValues).joined(separator: "\n") throw ParserError.completionScriptCustomResponse(output) } } // MARK: Building Command Stacks extension CommandParser { /// Builds an array of commands that matches the given command names. /// /// This stops building the stack if it encounters any command names that /// aren't in the command tree, so it's okay to pass a list of arbitrary /// commands. Will always return at least the root of the command tree. func commandStack(for commandNames: [String]) -> [ParsableCommand.Type] { var node = commandTree var result = [node.element] for name in commandNames { guard let nextNode = node.firstChild(withName: name) else { // Reached a non-command argument. // Ignore anything after this point return result } result.append(nextNode.element) node = nextNode } return result } func commandStack(for subcommand: ParsableCommand.Type) -> [ParsableCommand.Type] { let path = commandTree.path(to: subcommand) return path.isEmpty ? [commandTree.element] : path } } extension SplitArguments { func contains(_ needle: Name) -> Bool { self.elements.contains { switch $0.value { case .option(.name(let name)), .option(.nameWithValue(let name, _)): return name == needle default: return false } } } func contains(anyOf names: [Name]) -> Bool { self.elements.contains { switch $0.value { case .option(.name(let name)), .option(.nameWithValue(let name, _)): return names.contains(name) default: return false } } } }
a3c24d88c08a82a94afbdcc4c3bde7a8
35.473558
133
0.683649
false
false
false
false
stephentyrone/swift
refs/heads/master
test/IDE/complete_multiple_trailingclosure.swift
apache-2.0
1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GLOBALFUNC_SAMELINE | %FileCheck %s -check-prefix=GLOBALFUNC_SAMELINE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GLOBALFUNC_NEWLINE | %FileCheck %s -check-prefix=GLOBALFUNC_NEWLINE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GLOBALFUNC_AFTERLABEL | %FileCheck %s -check-prefix=GLOBALFUNC_AFTERLABEL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METHOD_SAMELINE | %FileCheck %s -check-prefix=METHOD_SAMELINE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METHOD_NEWLINE | %FileCheck %s -check-prefix=METHOD_NEWLINE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_OVERLOADED_SAMELINE | %FileCheck %s -check-prefix=INIT_OVERLOADED_SAMELINE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_OVERLOADED_NEWLINE | %FileCheck %s -check-prefix=INIT_OVERLOADED_NEWLINE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_OPTIONAL_SAMELINE | %FileCheck %s -check-prefix=INIT_OPTIONAL_SAMELINE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_OPTIONAL_NEWLINE | %FileCheck %s -check-prefix=INIT_OPTIONAL_NEWLINE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_REQUIRED_SAMELINE_1 | %FileCheck %s -check-prefix=INIT_REQUIRED_SAMELINE_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_REQUIRED_NEWLINE_1 | %FileCheck %s -check-prefix=INIT_REQUIRED_NEWLINE_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_REQUIRED_SAMELINE_2 | %FileCheck %s -check-prefix=INIT_REQUIRED_SAMELINE_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_REQUIRED_NEWLINE_2 | %FileCheck %s -check-prefix=INIT_REQUIRED_NEWLINE_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_REQUIRED_SAMELINE_3 | %FileCheck %s -check-prefix=INIT_REQUIRED_SAMELINE_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_REQUIRED_NEWLINE_3 | %FileCheck %s -check-prefix=INIT_REQUIRED_NEWLINE_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_FALLBACK_1 | %FileCheck %s -check-prefix=INIT_FALLBACK // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_FALLBACK_2 | %FileCheck %s -check-prefix=INIT_FALLBACK // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBERDECL_SAMELINE | %FileCheck %s -check-prefix=MEMBERDECL_SAMELINE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBERDECL_NEWLINE | %FileCheck %s -check-prefix=MEMBERDECL_NEWLINE func globalFunc1(fn1: () -> Int, fn2: () -> String) {} func testGlobalFunc() { globalFunc1() { 1 } #^GLOBALFUNC_SAMELINE^# #^GLOBALFUNC_NEWLINE^# // GLOBALFUNC_SAMELINE: Begin completions, 1 items // GLOBALFUNC_SAMELINE-DAG: Pattern/ExprSpecific: {#fn2: () -> String {() -> String in|}#}[#() -> String#]; // GLOBALFUNC_SAMELINE: End completions // GLOBALFUNC_NEWLINE: Begin completions, 1 items // GLOBALFUNC_NEWLINE-DAG: Pattern/ExprSpecific: {#fn2: () -> String {() -> String in|}#}[#() -> String#]; // GLOBALFUNC_NEWLINE: End completions globalFunc1() { 1 } fn2: #^GLOBALFUNC_AFTERLABEL^# // FIXME: Closure literal completion. // GLOBALFUNC_AFTERLABEL-NOT: Begin completions } struct SimpleEnum { case foo, bar func enumFunc() {} static func + (lhs: SimpleEnum, rhs: SimpleEnum) -> SimpleEnum {} } struct MyStruct { func method1(fn1: () -> Int, fn2: (() -> String)? = nil) -> SimpleEnum {} func method1(fn1: () -> Int, fn2: Int = nil) -> SimpleEnum {} } func testMethod(value: MyStruct) { value.method1 { } #^METHOD_SAMELINE^# #^METHOD_NEWLINE^# // METHOD_SAMELINE: Begin completions, 4 items // METHOD_SAMELINE-DAG: Pattern/ExprSpecific: {#fn2: (() -> String)? {() -> String in|}#}[#(() -> String)?#]; // METHOD_SAMELINE-DAG: Decl[InstanceMethod]/CurrNominal: .enumFunc()[#Void#]; // METHOD_SAMELINE-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]/IsSystem: [' ']+ {#SimpleEnum#}[#SimpleEnum#]; // METHOD_SAMELINE-DAG: Keyword[self]/CurrNominal: .self[#SimpleEnum#]; // METHOD_SAMELINE: End completions // METHOD_NEWLINE: Begin completions // METHOD_NEWLINE-DAG: Pattern/ExprSpecific: {#fn2: (() -> String)? {() -> String in|}#}[#(() -> String)?#]; // METHOD_NEWLINE-DAG: Keyword[class]/None: class; // METHOD_NEWLINE-DAG: Keyword[if]/None: if; // METHOD_NEWLINE-DAG: Keyword[try]/None: try; // METHOD_NEWLINE-DAG: Decl[LocalVar]/Local: value[#MyStruct#]; name=value // METHOD_NEWLINE: End completions } struct TestStruct { init(fn1: () -> Int, fn2: () -> String, fn3: () -> String) {} init(fn1: () -> Int) {} init(fn1: () -> Int, fn2: () -> String) {} init(fn1: () -> Int, fn3: () -> String) {} func testStructMethod() {} } func testOverloadedInit() { TestStruct { 1 } #^INIT_OVERLOADED_SAMELINE^# #^INIT_OVERLOADED_NEWLINE^# // INIT_OVERLOADED_SAMELINE: Begin completions, 4 items // INIT_OVERLOADED_SAMELINE-DAG: Pattern/ExprSpecific: {#fn2: () -> String {() -> String in|}#}[#() -> String#]; // INIT_OVERLOADED_SAMELINE-DAG: Pattern/ExprSpecific: {#fn3: () -> String {() -> String in|}#}[#() -> String#]; // INIT_OVERLOADED_SAMELINE-DAG: Decl[InstanceMethod]/CurrNominal: .testStructMethod()[#Void#]; // INIT_OVERLOADED_SAMELINE-DAG: Keyword[self]/CurrNominal: .self[#TestStruct#]; // INIT_OVERLOADED_SAMELINE: End completions // INIT_OVERLOADED_NEWLINE: Begin completions // INIT_OVERLOADED_NEWLINE-DAG: Pattern/ExprSpecific: {#fn2: () -> String {() -> String in|}#}[#() -> String#]; // INIT_OVERLOADED_NEWLINE-DAG: Pattern/ExprSpecific: {#fn3: () -> String {() -> String in|}#}[#() -> String#]; // INIT_OVERLOADED_NEWLINE-DAG: Keyword[class]/None: class; // INIT_OVERLOADED_NEWLINE-DAG: Keyword[if]/None: if; // INIT_OVERLOADED_NEWLINE-DAG: Keyword[try]/None: try; // INIT_OVERLOADED_NEWLINE-DAG: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct // INIT_OVERLOADED_NEWLINE: End completions } struct TestStruct2 { init(fn1: () -> Int, fn2: () -> String = {}, fn3: () -> String = {}) {} func testStructMethod() {} } func testOptionalInit() { TestStruct2 { 2 } #^INIT_OPTIONAL_SAMELINE^# #^INIT_OPTIONAL_NEWLINE^# // INIT_OPTIONAL_SAMELINE: Begin completions, 4 items // INIT_OPTIONAL_SAMELINE-DAG: Pattern/ExprSpecific: {#fn2: () -> String {() -> String in|}#}[#() -> String#]; // INIT_OPTIONAL_SAMELINE-DAG: Pattern/ExprSpecific: {#fn3: () -> String {() -> String in|}#}[#() -> String#]; // INIT_OPTIONAL_SAMELINE-DAG: Decl[InstanceMethod]/CurrNominal: .testStructMethod()[#Void#]; // INIT_OPTIONAL_SAMELINE-DAG: Keyword[self]/CurrNominal: .self[#TestStruct2#]; // INIT_OPTIONAL_SAMELINE: End completions // INIT_OPTIONAL_NEWLINE: Begin completions // INIT_OPTIONAL_NEWLINE-DAG: Pattern/ExprSpecific: {#fn2: () -> String {() -> String in|}#}[#() -> String#]; // INIT_OPTIONAL_NEWLINE-DAG: Pattern/ExprSpecific: {#fn3: () -> String {() -> String in|}#}[#() -> String#]; // INIT_OPTIONAL_NEWLINE-DAG: Keyword[class]/None: class; // INIT_OPTIONAL_NEWLINE-DAG: Keyword[if]/None: if; // INIT_OPTIONAL_NEWLINE-DAG: Keyword[try]/None: try; // INIT_OPTIONAL_NEWLINE-DAG: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct // INIT_OPTIONAL_NEWLINE: End completions } struct TestStruct3 { init(fn1: () -> Int, fn2: () -> String, fn3: () -> String) {} func testStructMethod() {} } func testOptionalInit() { // missing 'fn2' and 'fn3'. TestStruct3 { 2 } #^INIT_REQUIRED_SAMELINE_1^# #^INIT_REQUIRED_NEWLINE_1^# // INIT_REQUIRED_SAMELINE_1: Begin completions, 1 items // INIT_REQUIRED_SAMELINE_1-DAG: Pattern/ExprSpecific: {#fn2: () -> String {() -> String in|}#}[#() -> String#]; // INIT_REQUIRED_SAMELINE_1: End completions // INIT_REQUIRED_NEWLINE_1: Begin completions, 1 items // INIT_REQUIRED_NEWLINE_1-DAG: Pattern/ExprSpecific: {#fn2: () -> String {() -> String in|}#}[#() -> String#]; // INIT_REQUIRED_NEWLINE_1: End completions // missing 'fn3'. TestStruct3 { 2 } fn2: { "test" } #^INIT_REQUIRED_SAMELINE_2^# #^INIT_REQUIRED_NEWLINE_2^# // INIT_REQUIRED_SAMELINE_2: Begin completions, 1 items // INIT_REQUIRED_SAMELINE_2-DAG: Pattern/ExprSpecific: {#fn3: () -> String {() -> String in|}#}[#() -> String#]; // INIT_REQUIRED_SAMELINE_2: End completions // INIT_REQUIRED_NEWLINE_2: Begin completions, 1 items // INIT_REQUIRED_NEWLINE_2-DAG: Pattern/ExprSpecific: {#fn3: () -> String {() -> String in|}#}[#() -> String#]; // INIT_REQUIRED_NEWLINE_2: End completions // Call is completed. TestStruct3 { 2 } fn2: { "test" } fn3: { "test" } #^INIT_REQUIRED_SAMELINE_3^# #^INIT_REQUIRED_NEWLINE_3^# // INIT_REQUIRED_SAMELINE_3: Begin completions, 2 items // INIT_REQUIRED_SAMELINE_3-DAG: Decl[InstanceMethod]/CurrNominal: .testStructMethod()[#Void#]; // INIT_REQUIRED_SAMELINE_3-DAG: Keyword[self]/CurrNominal: .self[#TestStruct3#]; // INIT_REQIORED_SAMELINE_3: End completions // INIT_REQUIRED_NEWLINE_3: Begin completions // INIT_REQUIRED_NEWLINE_3-NOT: name=fn2 // INIT_REQUIRED_NEWLINE_3-NOT: name=fn3 // INIT_REQUIRED_NEWLINE_3-DAG: Keyword[class]/None: class; // INIT_REQUIRED_NEWLINE_3-DAG: Keyword[if]/None: if; // INIT_REQUIRED_NEWLINE_3-DAG: Keyword[try]/None: try; // INIT_REQUIRED_NEWLINE_3-DAG: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct // INIT_REQUIRED_NEWLINE_3-NOT: name=fn2 // INIT_REQUIRED_NEWLINE_3-NOT: name=fn3 // INIT_REQUIRED_NEWLINE_3: End completions } struct MyStruct4<T> { init(arg1: Int = 0, arg2: () -> T) {} init(name: String, arg2: () -> String, arg3: () -> T) {} func testStructMethod() {} } func testFallbackPostfix() { let _ = MyStruct4 { 1 } #^INIT_FALLBACK_1^# // INIT_FALLBACK: Begin completions, 2 items // INIT_FALLBACK-DAG: Decl[InstanceMethod]/CurrNominal: .testStructMethod()[#Void#]; // INIT_FALLBACK-DAG: Keyword[self]/CurrNominal: .self[#MyStruct4<Int>#]; // INIT_FALLBACK: End completions let _ = MyStruct4(name: "test") { "" } arg3: { 1 } #^INIT_FALLBACK_2^# } protocol P { func foo() } struct TestNominalMember: P { var value = MyStruct().method1 { 1 } #^MEMBERDECL_SAMELINE^# #^MEMBERDECL_NEWLINE^# // MEMBERDECL_SAMELINE: Begin completions, 4 items // MEMBERDECL_SAMELINE-DAG: Pattern/ExprSpecific: {#fn2: (() -> String)? {() -> String in|}#}[#(() -> String)?#]; name=fn2: (() -> String)? // MEMBERDECL_SAMELINE-DAG: Decl[InstanceMethod]/CurrNominal: .enumFunc()[#Void#]; name=enumFunc() // MEMBERDECL_SAMELINE-DAG: Decl[InfixOperatorFunction]/OtherModule[Swift]/IsSystem: [' ']+ {#SimpleEnum#}[#SimpleEnum#]; name=+ SimpleEnum // MEMBERDECL_SAMELINE-DAG: Keyword[self]/CurrNominal: .self[#SimpleEnum#]; name=self // MEMBERDECL_SAMELINE: End completions // MEMBERDECL_NEWLINE: Begin completions // MEMBERDECL_NEWLINE-DAG: Pattern/ExprSpecific: {#fn2: (() -> String)? {() -> String in|}#}[#(() -> String)?#]; name=fn2: (() -> String)? // MEMBERDECL_NEWLINE-DAG: Keyword[enum]/None: enum; name=enum // MEMBERDECL_NEWLINE-DAG: Keyword[func]/None: func; name=func // MEMBERDECL_NEWLINE-DAG: Keyword[private]/None: private; name=private // MEMBERDECL_NEWLINE-DAG: Keyword/None: lazy; name=lazy // MEMBERDECL_NEWLINE-DAG: Keyword[var]/None: var; name=var // MEMBERDECL_NEWLINE-DAG: Decl[InstanceMethod]/Super: func foo() {|}; name=foo() // MEMBERDECL_NEWLINE: End completions }
e6f088b924580900571d960dd46667cd
52.012712
170
0.658221
false
true
false
false
realm/SwiftLint
refs/heads/main
Source/SwiftLintFramework/Rules/Style/TrailingClosureRule.swift
mit
1
import Foundation import SourceKittenFramework struct TrailingClosureRule: OptInRule, ConfigurationProviderRule { var configuration = TrailingClosureConfiguration() init() {} static let description = RuleDescription( identifier: "trailing_closure", name: "Trailing Closure", description: "Trailing closure syntax should be used whenever possible.", kind: .style, nonTriggeringExamples: [ Example("foo.map { $0 + 1 }\n"), Example("foo.bar()\n"), Example("foo.reduce(0) { $0 + 1 }\n"), Example("if let foo = bar.map({ $0 + 1 }) { }\n"), Example("foo.something(param1: { $0 }, param2: { $0 + 1 })\n"), Example("offsets.sorted { $0.offset < $1.offset }\n"), Example("foo.something({ return 1 }())"), Example("foo.something({ return $0 }(1))"), Example("foo.something(0, { return 1 }())") ], triggeringExamples: [ Example("↓foo.map({ $0 + 1 })\n"), Example("↓foo.reduce(0, combine: { $0 + 1 })\n"), Example("↓offsets.sorted(by: { $0.offset < $1.offset })\n"), Example("↓foo.something(0, { $0 + 1 })\n") ] ) func validate(file: SwiftLintFile) -> [StyleViolation] { let dict = file.structureDictionary return violationOffsets(for: dict, file: file).map { StyleViolation(ruleDescription: Self.description, severity: configuration.severityConfiguration.severity, location: Location(file: file, byteOffset: $0)) } } private func violationOffsets(for dictionary: SourceKittenDictionary, file: SwiftLintFile) -> [ByteCount] { var results = [ByteCount]() if dictionary.expressionKind == .call, shouldBeTrailingClosure(dictionary: dictionary, file: file), let offset = dictionary.offset { results = [offset] } if let kind = dictionary.statementKind, kind != .brace { // trailing closures are not allowed in `if`, `guard`, etc results += dictionary.substructure.flatMap { subDict -> [ByteCount] in guard subDict.statementKind == .brace else { return [] } return violationOffsets(for: subDict, file: file) } } else { results += dictionary.substructure.flatMap { subDict in violationOffsets(for: subDict, file: file) } } return results } private func shouldBeTrailingClosure(dictionary: SourceKittenDictionary, file: SwiftLintFile) -> Bool { func shouldTrigger() -> Bool { return !isAlreadyTrailingClosure(dictionary: dictionary, file: file) && !isAnonymousClosureCall(dictionary: dictionary, file: file) } let arguments = dictionary.enclosedArguments // check if last parameter should be trailing closure if !configuration.onlySingleMutedParameter, arguments.isNotEmpty, case let closureArguments = filterClosureArguments(arguments, file: file), closureArguments.count == 1, closureArguments.last?.offset == arguments.last?.offset { return shouldTrigger() } let argumentsCountIsExpected: Bool = { if SwiftVersion.current >= .fiveDotSix, arguments.count == 1, arguments[0].expressionKind == .argument { return true } return arguments.isEmpty }() // check if there's only one unnamed parameter that is a closure if argumentsCountIsExpected, let offset = dictionary.offset, let totalLength = dictionary.length, let nameOffset = dictionary.nameOffset, let nameLength = dictionary.nameLength, case let start = nameOffset + nameLength, case let length = totalLength + offset - start, case let byteRange = ByteRange(location: start, length: length), let range = file.stringView.byteRangeToNSRange(byteRange), let match = regex("\\s*\\(\\s*\\{").firstMatch(in: file.contents, options: [], range: range)?.range, match.location == range.location { return shouldTrigger() } return false } private func filterClosureArguments(_ arguments: [SourceKittenDictionary], file: SwiftLintFile) -> [SourceKittenDictionary] { return arguments.filter { argument in guard let bodyByteRange = argument.bodyByteRange, let range = file.stringView.byteRangeToNSRange(bodyByteRange), let match = regex("\\s*\\{").firstMatch(in: file.contents, options: [], range: range)?.range, match.location == range.location else { return false } return true } } private func isAlreadyTrailingClosure(dictionary: SourceKittenDictionary, file: SwiftLintFile) -> Bool { guard let byteRange = dictionary.byteRange, let text = file.stringView.substringWithByteRange(byteRange) else { return false } return !text.hasSuffix(")") } private func isAnonymousClosureCall(dictionary: SourceKittenDictionary, file: SwiftLintFile) -> Bool { guard let byteRange = dictionary.byteRange, let range = file.stringView.byteRangeToNSRange(byteRange) else { return false } let pattern = regex("\\)\\s*\\)\\z") return pattern.numberOfMatches(in: file.contents, range: range) > 0 } }
4523c8bc260aa3ddca25e74b24615b98
38.671233
112
0.5827
false
false
false
false
theodinspire/FingerBlade
refs/heads/development
FingerBlade/CutPathGenerator.swift
gpl-3.0
1
// // CutPath.swift // FingerBlade // // Created by Eric T Cormack on 3/3/17. // Copyright © 2017 the Odin Spire. All rights reserved. // import UIKit class CutPathGenerator { let size: CGSize let lefty: Bool /// Initilizes the generator to a target view /// /// - Parameter size: Size of the target view init(ofSize size: CGSize) { self.size = size lefty = UserDefaults.standard.string(forKey: HAND) == "Left" } // Constant points //Corners private static let topFore = CGPoint(x: 0.80, y: 0.20) private static let bottomFore = CGPoint(x: 0.80, y: 0.80) private static let topBack = mirror(point: topFore) private static let bottomBack = mirror(point: bottomFore) //Thrust startings private static let top = CGPoint(x: 0.50, y: 0.20) private static let bottom = CGPoint(x: 0.50, y: 0.80) //Center diamond private static let centerUp = CGPoint(x: 0.50, y: 0.40) private static let centerFore = CGPoint(x: 0.60, y: 0.50) private static let centerDown = CGPoint(x: 0.50, y: 0.60) private static let centerBack = mirror(point: centerFore) //Sides private static let foreUp = CGPoint(x: 0.80, y: 0.40) private static let foreMid = CGPoint(x: 0.80, y: 0.50) private static let backUp = mirror(point: foreUp) private static let backMid = mirror(point: foreMid) //Cavazione turns private static let cavazione = CGPoint(x: 0.70, y: 0.50) private static let cavUp = CGPoint(x: cavazione.x, y: 0.60) private static let cavDown = CGPoint(x: cavazione.x, y: 0.40) /// Builds a Bezier path for a particular cut line /// /// - Parameter cut: Cut line requested /// - Returns: Bezier path of the line func path(`for` cut: CutLine) -> UIBezierPath { let path = UIBezierPath() let start = self.start(for: cut) let end = self.end(for: cut) path.move(to: start) switch cut { case .fendManTut, .fendManMez, .fendRivTut, .fendRivMez, .mezMan, .mezRiv, .sotRivMez, .sotRivFal, .punSot, .punSop: path.addLine(to: end) case .sotManTut: path.addQuadCurve(to: end, controlPoint: handed(CutPathGenerator.bottomBack) * size) case .sotManMez, .sotRivTut: path.addQuadCurve(to: end, controlPoint: CutPathGenerator.bottom * size) case .sotManFal: path.addQuadCurve(to: end, controlPoint: handed(CutPathGenerator.foreUp) * size) case.punCav: let cav = handed(CutPathGenerator.cavazione) path.addCurve(to: cav * size, controlPoint1: mirror(point: cav) * size, controlPoint2: handed(CutPathGenerator.cavDown) * size) path.addCurve(to: end, controlPoint1: handed(CutPathGenerator.cavUp) * size, controlPoint2: mirror(point: cav) * size) //default: //path.addLine(to: end) } return path } /// Gives the starting location of a cut /// /// - Parameter cut: Cut line /// - Returns: Beginning location of the cut func start(`for` cut: CutLine) -> CGPoint { let point: CGPoint switch cut { case .fendManTut, .fendManMez: point = handed(CutPathGenerator.topFore) case .fendRivTut, .fendRivMez: point = handed(CutPathGenerator.topBack) case .mezMan: point = handed(CutPathGenerator.foreUp) case .mezRiv: point = handed(CutPathGenerator.backUp) case .sotManTut, .sotManMez, .sotManFal: point = handed(CutPathGenerator.bottomFore) case .sotRivTut, .sotRivMez, .sotRivFal: point = handed(CutPathGenerator.bottomBack) case .punSot, .punCav: point = CutPathGenerator.bottom case .punSop: point = CutPathGenerator.top //default: //point = CGPoint(x: 0.5, y: 0.5) } return point * size } /// Gives the ending location of a cut /// /// - Parameter cut: Cut line /// - Returns: Endpoint of the cut func end(`for` cut: CutLine) -> CGPoint { let point: CGPoint switch cut { case .fendManTut: point = handed(CutPathGenerator.bottomBack) case .fendManMez, .sotManMez: point = handed(CutPathGenerator.centerBack) case .fendRivTut: point = handed(CutPathGenerator.bottomFore) case .fendRivMez, .sotRivMez: point = handed(CutPathGenerator.centerFore) case .mezMan: point = handed(CutPathGenerator.backMid) case .mezRiv: point = handed(CutPathGenerator.foreMid) case .sotManTut, .sotManFal: point = handed(CutPathGenerator.topBack) case .sotRivTut, .sotRivFal: point = handed(CutPathGenerator.topFore) case .punSot: point = CutPathGenerator.centerUp case .punSop: point = CutPathGenerator.centerDown case .punCav: point = CutPathGenerator.top //default: //point = CGPoint(x: 0.5, y: 0.5) } return point * size } /// Returns the properly handed location of a point given the User's chosen handedness /// /// - Parameter point: Point to be tranlsated, if necessary /// - Returns: Translated point private func handed(_ point: CGPoint) -> CGPoint { return lefty ? mirror(point: point) : point } } extension CGPoint { /// Turns a point defined as a ratio (with values from 0 to 1) to its related point in cartesian coordinates scaled to the size of the target view /// /// - Parameters: /// - point: Ratio defined point /// - scale: Size of targeted view /// - Returns: Point scaled to equivalent location in view static func *(_ point: CGPoint, _ scale: CGSize) -> CGPoint { return CGPoint(x: point.x * scale.width, y: point.y * scale.height) } }
e3843573665ba65d03525901e67d507c
35.341176
150
0.595338
false
false
false
false
antonio081014/LeeCode-CodeBase
refs/heads/main
Swift/perfect-rectangle.swift
mit
2
/** * Problem Link: https://leetcode.com/problems/perfect-rectangle/ * * Linear Algorithm gives TLE. This Algorithm written in other language could pass. * * To get the perfect square, there are only 3 kinds of vertices. * * 1st, final 4 cornor vertices of the square, which connects only one rectangle. * * 2nd, vertices connect two rectangles. * * 3rd, vertices connect four rectangles. */ class Solution { struct Point: Hashable { let x: Int let y: Int init(_ xx: Int, _ yy: Int) { self.x = xx self.y = yy } var hashValue: Int { return self.x ^ self.y } static func == (lhs: Point, rhs: Point) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } } struct Rectangle { private let x1: Int private let y1: Int private let x2: Int private let y2: Int var p1: Point { return Point(x1, y1) } var p2: Point { return Point(x1, y2) } var p3: Point { return Point(x2, y1) } var p4: Point { return Point(x2, y2) } var area: Int { return (self.y2 - self.y1) * (self.x2 - self.x1) } var minx: Int { return self.x1 } var miny: Int { return self.y1 } var maxx: Int { return self.x2 } var maxy: Int { return self.y2 } init(x1: Int, y1: Int, x2: Int, y2: Int) { self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 } } func isRectangleCover(_ rectangles: [[Int]]) -> Bool { let rectList = rectangles.map {Rectangle(x1: $0[0], y1: $0[1], x2: $0[2], y2: $0[3])} let result: (Int, Int, Int, Int, Int, Set<Point>) = rectList.reduce((Int.max, Int.max, Int.min, Int.min, 0, Set<Point>())) { res, rect in let (minx, miny, maxx, maxy, s, sset) = res var set = sset if set.insert(rect.p1).0 == false { set.remove(rect.p1) } if set.insert(rect.p2).0 == false { set.remove(rect.p2) } if set.insert(rect.p3).0 == false { set.remove(rect.p3) } if set.insert(rect.p4).0 == false { set.remove(rect.p4) } return (min(minx, rect.minx), min(miny, rect.miny), max(maxx, rect.maxx), max(maxy, rect.maxy), s + rect.area, set) } let set = result.5 let mRect = Rectangle(x1: result.0, y1: result.1, x2: result.2, y2: result.3) if set.count != 4 || !set.contains(mRect.p1) || !set.contains(mRect.p2) || !set.contains(mRect.p3) || !set.contains(mRect.p4) { return false } return mRect.area == result.4 } func isRectangleCover2(_ rectangles: [[Int]]) -> Bool { let rectList = rectangles.map {Rectangle(x1: $0[0], y1: $0[1], x2: $0[2], y2: $0[3])} var minx = Int.max var miny = Int.max var maxx = Int.min var maxy = Int.min var area = 0 var set = Set<Point>() for rect in rectList { if set.insert(rect.p1).0 == false { set.remove(rect.p1) } if set.insert(rect.p2).0 == false { set.remove(rect.p2) } if set.insert(rect.p3).0 == false { set.remove(rect.p3) } if set.insert(rect.p4).0 == false { set.remove(rect.p4) } minx = min(minx, rect.minx) miny = min(miny, rect.miny) maxx = max(maxx, rect.maxx) maxy = max(maxy, rect.maxy) area += rect.area } let mRect = Rectangle(x1: minx, y1: miny, x2: maxx, y2: maxy) if set.count != 4 || !set.contains(mRect.p1) || !set.contains(mRect.p2) || !set.contains(mRect.p3) || !set.contains(mRect.p4) { return false } return mRect.area == area } }
dcbb94c66d8ade9c7cd79967f61de88d
29.342857
135
0.471751
false
false
false
false
AaronMT/firefox-ios
refs/heads/master
Client/Frontend/Settings/AdvancedAccountSettingViewController.swift
mpl-2.0
6
/* 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 SnapKit import FxA import Account fileprivate class CustomFxAContentServerEnableSetting: BoolSetting { init(prefs: Prefs, settingDidChange: ((Bool?) -> Void)? = nil) { super.init( prefs: prefs, prefKey: PrefsKeys.KeyUseCustomFxAContentServer, defaultValue: false, attributedTitleText: NSAttributedString(string: Strings.SettingsAdvancedAccountUseCustomFxAContentServerURITitle), settingDidChange: settingDidChange ) } } fileprivate class CustomSyncTokenServerEnableSetting: BoolSetting { init(prefs: Prefs, settingDidChange: ((Bool?) -> Void)? = nil) { super.init( prefs: prefs, prefKey: PrefsKeys.KeyUseCustomSyncTokenServerOverride, defaultValue: false, attributedTitleText: NSAttributedString(string: Strings.SettingsAdvancedAccountUseCustomSyncTokenServerTitle), settingDidChange: settingDidChange ) } } fileprivate class CustomURLSetting: WebPageSetting { override init(prefs: Prefs, prefKey: String, defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, isChecked: @escaping () -> Bool = { return false }, settingDidChange: ((String?) -> Void)? = nil) { super.init(prefs: prefs, prefKey: prefKey, defaultValue: defaultValue, placeholder: placeholder, accessibilityIdentifier: accessibilityIdentifier, settingDidChange: settingDidChange) textField.clearButtonMode = .always } } class AdvancedAccountSettingViewController: SettingsTableViewController { fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier" fileprivate var customFxAContentURI: String? fileprivate var customSyncTokenServerURI: String? override func viewDidLoad() { super.viewDidLoad() title = Strings.SettingsAdvancedAccountTitle self.customFxAContentURI = self.profile.prefs.stringForKey(PrefsKeys.KeyCustomFxAContentServer) self.customSyncTokenServerURI = self.profile.prefs.stringForKey(PrefsKeys.KeyCustomSyncTokenServerOverride) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) RustFirefoxAccounts.reconfig(prefs: profile.prefs) } override func generateSettings() -> [SettingSection] { let prefs = profile.prefs let useStage = BoolSetting(prefs: prefs, prefKey: PrefsKeys.UseStageServer, defaultValue: false, attributedTitleText: NSAttributedString(string: NSLocalizedString("Use stage servers", comment: "Debug option"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) { isOn in self.settings = self.generateSettings() self.tableView.reloadData() } let customFxA = CustomURLSetting(prefs: prefs, prefKey: PrefsKeys.KeyCustomFxAContentServer, placeholder: Strings.SettingsAdvancedAccountCustomFxAContentServerURI, accessibilityIdentifier: "CustomFxAContentServer") let customSyncTokenServerURISetting = CustomURLSetting(prefs: prefs, prefKey: PrefsKeys.KeyCustomSyncTokenServerOverride, placeholder: Strings.SettingsAdvancedAccountCustomSyncTokenServerURI, accessibilityIdentifier: "CustomSyncTokenServerURISetting") let autoconfigSettings = [ CustomFxAContentServerEnableSetting(prefs: prefs) { isOn in self.settings = self.generateSettings() self.tableView.reloadData() }, customFxA ] let tokenServerSettings = [ CustomSyncTokenServerEnableSetting(prefs: prefs), customSyncTokenServerURISetting ] var settings: [SettingSection] = [SettingSection(title:nil, children: [useStage])] if !(prefs.boolForKey(PrefsKeys.UseStageServer) ?? false) { settings.append(SettingSection(title: nil, children: autoconfigSettings)) settings.append(SettingSection(title: nil, children: tokenServerSettings)) } return settings } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! ThemedTableSectionHeaderFooterView let sectionSetting = settings[section] headerView.titleLabel.text = sectionSetting.title?.string switch section { case 1, 3: headerView.titleAlignment = .top headerView.titleLabel.numberOfLines = 0 default: return super.tableView(tableView, viewForHeaderInSection: section) } return headerView } }
d1751086e64616c57ce721849bba1aab
44.560345
305
0.670388
false
false
false
false
codingforentrepreneurs/30-Days-of-Swift
refs/heads/master
Simple_Final/Simple/LocationCollectionViewCell.swift
apache-2.0
1
// // LocationCollectionViewCell.swift // Simple // // Created by Justin Mitchel on 12/18/14. // Copyright (c) 2014 Coding for Entrepreneurs. All rights reserved. // import UIKit class LocationCollectionViewCell: UICollectionViewCell { var textView:UITextView! required init(coder aDecoder:NSCoder) { super.init(coder: aDecoder) } override init(frame:CGRect) { super.init(frame:frame) let tvFrame = CGRectMake(10, 0, frame.size.width - 20, frame.size.height) textView = UITextView(frame: tvFrame) textView.font = UIFont.systemFontOfSize(20.0) textView.backgroundColor = UIColor(white: 1.0, alpha: 0.3) textView.textAlignment = .Left textView.scrollEnabled = false textView.userInteractionEnabled = true textView.editable = false textView.dataDetectorTypes = UIDataDetectorTypes.All contentView.addSubview(textView) } }
21d79a619260b6560ef40edcab99db4e
27.085714
81
0.657172
false
false
false
false
nsnull0/YWTopInputField
refs/heads/master
YWTopInputField/Classes/YWTopInputFieldController.swift
mit
1
// // YWTopInputFieldController.swift // YWTopInputField // // Created by Yoseph Wijaya on 2017/06/24. // Copyright © 2017 Yoseph Wijaya. All rights reserved. // import UIKit public class YWTopInputFieldController: UIViewController { @IBOutlet weak var messageLabelYW: UILabel! @IBOutlet weak var titleLabelYW: UILabel! @IBOutlet weak var inputTextContainerYW: UITextView! @IBOutlet weak var containerBlur: UIVisualEffectView! @IBOutlet weak var topContainerBlurConstraint: NSLayoutConstraint! @IBOutlet weak var accessoryOfYWInputField: UIView! @IBOutlet weak var inputAcessoryYWInputField: UIVisualEffectView! @IBOutlet weak var inputAccessoryYWInputFieldPart: UIVisualEffectView! @IBOutlet weak var bottomConstraintInputYWField: NSLayoutConstraint! @IBOutlet weak var heightConstraintContainerInputYWField: NSLayoutConstraint! weak var delegate :YWInputProtocol? private weak var root:UIViewController? private var addressTag:Int = 0 public var customize:YWTopInputFieldLogic = YWTopInputFieldLogic() override public func viewDidLoad() { super.viewDidLoad() //version 2.0 //self.inputTextContainerYW.inputAccessoryView = accessoryOfYWInputField self.view.frame = CGRect(x: 0, y: 0, width: getScreenWidth(), height: getScreenHeight()) self.inputAccessoryYWInputFieldPart.layer.opacity = 0 } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.topContainerBlurConstraint.constant = -self.getContainerHeight() self.view.layoutIfNeeded() } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } required public init(_contentController parent:UIViewController, _andDelegate delegation:YWInputProtocol?) { let bundle = Bundle(for: YWTopInputFieldController.self) super.init(nibName: "YWMainView", bundle: bundle) self.root = parent self.delegate = delegation self.didMove(toParentViewController: self.root!) self.createPrivateObjectWithout() } //MARK: Animation and Interface public func showInput(_withTitle titleStr:String,_andMessage messageStr:String, _withTag tag:Int, completion:@escaping (_ finished:Bool) -> Void){ self.showInput(completion: completion) self.titleLabelYW.text = YWTopInputFieldLogic.checkValidate(_onContent: titleStr, _defaultContent: YWTopInputFieldUtility.titleDefault) self.messageLabelYW.text = YWTopInputFieldLogic.checkValidate(_onContent: messageStr, _defaultContent: YWTopInputFieldUtility.messageDefault) self.addressTag = tag self.delegate?.didShowYWInputField() } public func showInput(_withTitle titleStr:String,_andMessage messageStr:String,_withContentString content:String, _withTag tag:Int , completion:@escaping (_ finished:Bool) -> Void){ self.showInput(completion: completion) self.titleLabelYW.text = YWTopInputFieldLogic.checkValidate(_onContent: titleStr, _defaultContent: YWTopInputFieldUtility.titleDefault) self.messageLabelYW.text = YWTopInputFieldLogic.checkValidate(_onContent: messageStr, _defaultContent: YWTopInputFieldUtility.messageDefault) self.inputTextContainerYW.text = content self.addressTag = tag self.delegate?.didShowYWInputField() } public func showInput(_withTitle titleStr:String,_andMessage messageStr:String,_withContentAttributedString content:NSAttributedString, _withTag tag:Int, completion:@escaping (_ finished:Bool) -> Void){ self.showInput(completion: completion) self.titleLabelYW.text = YWTopInputFieldLogic.checkValidate(_onContent: titleStr, _defaultContent: YWTopInputFieldUtility.titleDefault) self.messageLabelYW.text = YWTopInputFieldLogic.checkValidate(_onContent: messageStr, _defaultContent: YWTopInputFieldUtility.messageDefault) self.inputTextContainerYW.attributedText = content self.addressTag = tag self.delegate?.didShowYWInputField() } //MARK: Private Animation and Interface implementation func showInput(completion:@escaping (_ finished:Bool) -> Void){ guard self.root != nil else { completion(false) return } self.createObject() self.view.layoutIfNeeded() UIView.animate(withDuration: 0.3, animations: { self.topContainerBlurConstraint.constant = 0 self.view.layoutIfNeeded() }) { (finished) in self.inputTextContainerYW.becomeFirstResponder() completion(true) } } func hideInput (completion:@escaping (AnyObject, _ finished:Bool) -> Void){ UIView.animate(withDuration: 0.3, animations: { self.topContainerBlurConstraint.constant = -self.customize.propertyYW.heightContainerConstraint-50 self.view.layoutIfNeeded() }) { (finished) in self.inputTextContainerYW.resignFirstResponder() self.view.removeFromSuperview() self.removeFromParentViewController() completion(self.inputTextContainerYW.text as AnyObject, true) } } func createObject() { self.root!.view.addSubview(self.view) self.view.frame = CGRect(x: 0, y: 0, width: getScreenWidth(), height: getScreenHeight()) self.view.setupLayoutConstraint_0_0_0_0_toParent() self.inputTextContainerYW.autocorrectionType = self.customize.propertyYW.correctionType self.inputTextContainerYW.keyboardAppearance = self.customize.propertyYW.keyboardAppearance self.inputTextContainerYW.spellCheckingType = self.customize.propertyYW.spellCheckType self.inputTextContainerYW.keyboardType = self.customize.propertyYW.keyboardType // let visEffect:UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: self.containerEffectType)) // self.containerBlur.effect = visEffect.effect! // self.inputAcessoryYWInputField.effect = visEffect.effect! // self.inputAccessoryYWInputFieldPart.effect = visEffect.effect! self.titleLabelYW.textColor = self.customize.propertyYW.titleColorText self.messageLabelYW.textColor = self.customize.propertyYW.messageColorText self.titleLabelYW.font = self.customize.propertyYW.titleFontText self.messageLabelYW.font = self.customize.propertyYW.messageFontText self.heightConstraintContainerInputYWField.constant = self.customize.propertyYW.heightContainerConstraint } func createPrivateObjectWithout(){ self.root!.view.addSubview(self.view) self.view.frame = CGRect(x: 0, y: 0, width: getScreenWidth(), height: getScreenHeight()) self.view.setupLayoutConstraint_0_0_0_0_toParent() self.inputTextContainerYW.autocorrectionType = self.customize.propertyYW.correctionType self.inputTextContainerYW.keyboardAppearance = self.customize.propertyYW.keyboardAppearance self.inputTextContainerYW.spellCheckingType = self.customize.propertyYW.spellCheckType self.inputTextContainerYW.keyboardType = self.customize.propertyYW.keyboardType // let visEffect:UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: self.containerEffectType)) // self.containerBlur.effect = visEffect.effect! // self.inputAcessoryYWInputField.effect = visEffect.effect! // self.inputAccessoryYWInputFieldPart.effect = visEffect.effect! self.titleLabelYW.textColor = self.customize.propertyYW.titleColorText self.messageLabelYW.textColor = self.customize.propertyYW.messageColorText self.titleLabelYW.font = self.customize.propertyYW.titleFontText self.messageLabelYW.font = self.customize.propertyYW.messageFontText self.heightConstraintContainerInputYWField.constant = self.customize.propertyYW.heightContainerConstraint self.view.removeFromSuperview() self.removeFromParentViewController() } //MARK: Action Handler @IBAction func tapDismiss(_ sender: UITapGestureRecognizer) { self.hideInput(completion: { (text:AnyObject, completion) in self.delegate?.didCancel() }) self.delegate?.didCancel() } @IBAction func doneAction(_ sender: UIButton) { self.hideInput { (text:AnyObject, completion) in let toText = text as! String self.delegate?.doneAction(resultStr: toText, _withTag: self.addressTag) } } @IBAction func cancelAction(_ sender: UIButton) { self.hideInput(completion: { (text:AnyObject, completion) in self.delegate?.didCancel() }) } @IBAction func editAttributes(_ sender: UIButton) { guard self.bottomConstraintInputYWField.constant == -40 else { UIView.animate(withDuration: 0.3, animations: { self.bottomConstraintInputYWField.constant = -40 self.inputAccessoryYWInputFieldPart.layer.opacity = 0 self.accessoryOfYWInputField.layoutIfNeeded() }) return } UIView.animate(withDuration: 0.3, animations: { self.bottomConstraintInputYWField.constant = 0 self.inputAccessoryYWInputFieldPart.layer.opacity = 1 self.accessoryOfYWInputField.layoutIfNeeded() }) } //MARK: Setup Default public override var prefersStatusBarHidden: Bool { return true } }
a2438ebbff7dde812619cc8d3a5879e8
38.057471
206
0.678634
false
false
false
false
qutheory/vapor
refs/heads/main
Sources/Vapor/Routing/Route.swift
mit
2
public final class Route: CustomStringConvertible { public var method: HTTPMethod public var path: [PathComponent] public var responder: Responder public var requestType: Any.Type public var responseType: Any.Type public var userInfo: [AnyHashable: Any] public var description: String { let path = self.path.map { "\($0)" }.joined(separator: "/") return "\(self.method.string) /\(path)" } public init( method: HTTPMethod, path: [PathComponent], responder: Responder, requestType: Any.Type, responseType: Any.Type ) { self.method = method self.path = path self.responder = responder self.requestType = requestType self.responseType = responseType self.userInfo = [:] } @discardableResult public func description(_ string: String) -> Route { self.userInfo["description"] = string return self } }
df30dd75844ddcb55ce44b4cbca1eb86
27.257143
67
0.608696
false
false
false
false
hucool/XMImagePicker
refs/heads/master
Pod/Classes/AlbumCell.swift
mit
1
// // ThumbCell.swift // XMImagePicker // // Created by tiger on 2017/2/8. // Copyright © 2017年 xinma. All rights reserved. // import UIKit import Foundation class AlbumCell: UITableViewCell { var albumInfo: Album! { didSet { iTitleLabel.text = albumInfo.title iCountLabel.text = "(\(albumInfo.count))" if let thumb = albumInfo.thumb { iThumbImageView.image = thumb } } } // album title fileprivate lazy var iTitleLabel: UILabel = { self.iTitleLabel = UILabel() self.iTitleLabel.textColor = .black self.iTitleLabel.font = UIFont.systemFont(ofSize: 16) self.iTitleLabel.translatesAutoresizingMaskIntoConstraints = false return self.iTitleLabel }() // album photo conut fileprivate lazy var iCountLabel: UILabel = { self.iCountLabel = UILabel() self.iCountLabel.textColor = .gray self.iCountLabel.font = UIFont.systemFont(ofSize: 16) self.iCountLabel.translatesAutoresizingMaskIntoConstraints = false return self.iCountLabel }() // album thumb fileprivate lazy var iThumbImageView: UIImageView = { self.iThumbImageView = UIImageView() self.iThumbImageView.translatesAutoresizingMaskIntoConstraints = false return self.iThumbImageView }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) accessoryType = .disclosureIndicator contentView.addSubview(iTitleLabel) contentView.addSubview(iCountLabel) contentView.addSubview(iThumbImageView) constraintSetup() } private func constraintSetup() { // set album thumb imageView constraint contentView.addConstraint(NSLayoutConstraint.init(item: iThumbImageView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint.init(item: iThumbImageView, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint.init(item: iThumbImageView, attribute: .width, relatedBy: .equal, toItem: iThumbImageView, attribute: .height, multiplier: 1, constant: 0)) // set album name label constraint contentView.addConstraint(NSLayoutConstraint.init(item: iTitleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint.init(item: iTitleLabel, attribute: .left, relatedBy: .equal, toItem: iThumbImageView, attribute: .right, multiplier: 1, constant: 10)) // set album number label constraint contentView.addConstraint(NSLayoutConstraint.init(item: iCountLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint.init(item: iCountLabel, attribute: .left, relatedBy: .equal, toItem: iTitleLabel, attribute: .right, multiplier: 1, constant: 15)) contentView.layoutIfNeeded() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
2011d595832f5a17584aa2402b38004e
47.180328
82
0.402348
false
false
false
false
seeRead/roundware-ios-framework-v2
refs/heads/master
Pod/Classes/RWFrameworkProtocol.swift
mit
1
// // RWFrameworkProtocol.swift // RWFramework // // Created by Joe Zobkiw on 1/27/15. // Copyright (c) 2015 Roundware. All rights reserved. // import Foundation import CoreLocation // TODO: Consider making this multiple protocols instead of using @objc in order to get optional capabilities // see http://ashfurrow.com/blog/protocols-and-swift/ // NOTE: These methods are called on the main queue unless otherwise noted // MARK: RWFrameworkProtocol @objc public protocol RWFrameworkProtocol: class { // API success/failure delegate methods /// Sent when a token and username are returned from the server @objc optional func rwPostUsersSuccess(data: NSData?) /// Sent when a token and username fails to be returned from the server @objc optional func rwPostUsersFailure(error: NSError?) /// Sent when a new user session for the project has been created @objc optional func rwPostSessionsSuccess(data: NSData?) /// Sent when the server fails to create a new user session for the project @objc optional func rwPostSessionsFailure(error: NSError?) /// Sent when project information has been received from the server @objc optional func rwGetProjectsIdSuccess(data: NSData?) /// Sent when the server fails to send project information @objc optional func rwGetProjectsIdFailure(error: NSError?) /// Sent when project tags have been received from the server @objc optional func rwGetProjectsIdTagsSuccess(data: NSData?) /// Sent when the server fails to send project tags @objc optional func rwGetProjectsIdTagsFailure(error: NSError?) /// Sent when project uigroups have been received from the server @objc optional func rwGetProjectsIdUIGroupsSuccess(data: NSData?) /// Sent when project uigroups have been received from the server @objc optional func rwGetProjectsIdUIGroupsFailure(error: NSError?) /// Sent when a stream has been acquired and can be played. Clients should enable their Play buttons. @objc optional func rwPostStreamsSuccess(data: NSData?) /// Sent when a stream could not be acquired and therefore can not be played. Clients should disable their Play buttons. @objc optional func rwPostStreamsFailure(error: NSError?) /// Sent after a stream is modified successfully @objc optional func rwPatchStreamsIdSuccess(data: NSData?) /// Sent when a stream could not be modified successfully @objc optional func rwPatchStreamsIdFailure(error: NSError?) /// Sent to the server if the GPS has not been updated in gps_idle_interval_in_seconds @objc optional func rwPostStreamsIdHeartbeatSuccess(data: NSData?) /// Sent in the case that sending the heartbeat failed @objc optional func rwPostStreamsIdHeartbeatFailure(error: NSError?) /// Sent after the server successfully advances to the next sound in the stream as per request @objc optional func rwPostStreamsIdSkipSuccess(data: NSData?) /// Sent in the case that advancing to the next sound in the stream, as per request, fails @objc optional func rwPostStreamsIdSkipFailure(error: NSError?) @objc optional func rwPostStreamsIdPlayAssetSuccess(data: NSData?) @objc optional func rwPostStreamsIdPlayAssetFailure(error: NSError?) @objc optional func rwPostStreamsIdReplayAssetSuccess(data: NSData?) @objc optional func rwPostStreamsIdReplayAssetFailure(error: NSError?) @objc optional func rwPostStreamsIdPauseSuccess(data: NSData?) @objc optional func rwPostStreamsIdPauseFailure(error: NSError?) @objc optional func rwPostStreamsIdResumeSuccess(data: NSData?) @objc optional func rwPostStreamsIdResumeFailure(error: NSError?) /// Sent after the server successfully gets the current asset ID in the stream @objc optional func rwGetStreamsIdCurrentSuccess(data: NSData?) /// Sent in the case that getting the current assed ID in the stream fails @objc optional func rwGetStreamsIdCurrentFailure(error: NSError?) /// Sent after the server successfully returns a new envelope id @objc optional func rwPostEnvelopesSuccess(data: NSData?) /// Sent in the case that the server can not return a new envelope id @objc optional func rwPostEnvelopesFailure(error: NSError?) /// Sent after the server successfully accepts an envelope item (media upload) @objc optional func rwPatchEnvelopesIdSuccess(data: NSData?) /// Sent in the case that the server can not accept an envelope item (media upload) @objc optional func rwPatchEnvelopesIdFailure(error: NSError?) /// Sent after the server successfully gets asset info @objc optional func rwGetAssetsSuccess(data: NSData?) /// Sent in the case that the server can not get asset info @objc optional func rwGetAssetsFailure(error: NSError?) /// Sent after the server successfully gets asset id info @objc optional func rwGetAssetsIdSuccess(data: NSData?) /// Sent in the case that the server can not get asset id info @objc optional func rwGetAssetsIdFailure(error: NSError?) /// Sent after the server successfully posts a vote @objc optional func rwPostAssetsIdVotesSuccess(data: NSData?) /// Sent in the case that the server can not post a vote @objc optional func rwPostAssetsIdVotesFailure(error: NSError?) /// Sent after the server successfully gets vote info for an asset @objc optional func rwGetAssetsIdVotesSuccess(data: NSData?) /// Sent in the case that the server can not get vote info for an asset @objc optional func rwGetAssetsIdVotesFailure(error: NSError?) /// Sent after the server successfully posts an event @objc optional func rwPostEventsSuccess(data: NSData?) /// Sent in the case that the server can not post an event @objc optional func rwPostEventsFailure(error: NSError?) // MARK: metadata /// Sent when metadata (and all other observed values) are found, sent synchronously on main thread @objc optional func rwObserveValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSKeyValueChangeKey : AnyObject]?, context: UnsafeMutableRawPointer?) // MARK: Image Picker /// Sent when the imagePickerController is dismissed after picking media @objc optional func rwImagePickerControllerDidFinishPickingMedia(info: [String : AnyObject], path: String) /// Sent when the imagePickerController is dismissed after cancelling @objc optional func rwImagePickerControllerDidCancel() // MARK: Record /// Sent when the framework determines that recording is possible (via config) @objc optional func rwReadyToRecord() /// Sent to indicate the % complete when recording @objc optional func rwRecordingProgress(percentage: Double, maxDuration: TimeInterval, peakPower: Float, averagePower: Float) /// Sent to indicate the % complete when playing back a recording @objc optional func rwPlayingBackProgress(percentage: Double, duration: TimeInterval, peakPower: Float, averagePower: Float) /// Sent when the audio recorder finishes recording @objc optional func rwAudioRecorderDidFinishRecording() /// Sent when the audio player finishes playing @objc optional func rwAudioPlayerDidFinishPlaying() // MARK: UI/Status /// A user-readable message that can be passed on as status information. This will always be called on the main thread @objc optional func rwUpdateStatus(message: String) /// The number of items in the queue waiting to be uploaded @objc optional func rwUpdateApplicationIconBadgeNumber(count: Int) /// Called when the framework needs the current view controller in order to display the tag editor. /// If this method is not implemented then it is assumed that the delegate is a view controller. @objc optional func rwGetCurrentViewController() -> UIViewController // MARK: Location /// Called when location updates @objc optional func rwLocationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) /// Called when location authorization changes @objc optional func rwLocationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) } /// The framework calls these methods to call thru to the delegate protocol in order to keep the calling code clean of respondsToSelector checks extension RWFramework { // MARK: public delegate management /// Add a delegate to the list of delegates public func addDelegate(object: AnyObject) { delegates.add(object) println(object: "addDelegate: \(delegates)") } /// Remove a delegate from the list of delegates (if it is a delegate) public func removeDelegate(object: AnyObject) { delegates.remove(object) println(object: "removeDelegate: \(delegates)") } /// Remove all delegates from the list of delegates public func removeAllDelegates() { delegates.removeAllObjects() println(object: "removeAllDelegates: \(delegates)") } /// Return true if the object is currently a delegate, false otherwise public func isDelegate(object: AnyObject) -> Bool { return delegates.contains(object) } // MARK: dam /// dam = dispatch_async on the main queue func dam(f: @escaping () -> Void) { DispatchQueue.main.async(execute: { () -> Void in f() }) } // MARK: protocaller /// Utility function to call method with AnyObject param on valid delegates func protocaller(param: AnyObject? = nil, completion:(_ rwfp: RWFrameworkProtocol, _ param: AnyObject?) -> Void) { let enumerator = delegates.objectEnumerator() while let d: AnyObject = enumerator.nextObject() as AnyObject? { if let dd = d as? RWFrameworkProtocol { completion(dd, param) } } } // MARK: callers func rwPostUsersSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPostUsersSuccess?(data: data) } } } func rwPostUsersFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPostUsersFailure != nil) { self.dam { rwfp.rwPostUsersFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPostUsersFailure"), message: error!.localizedDescription) } } } func rwPostSessionsSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPostSessionsSuccess?(data: data) } } } func rwPostSessionsFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPostSessionsFailure != nil) { self.dam { rwfp.rwPostSessionsFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPostSessionsFailure"), message: error!.localizedDescription) } } } func rwGetProjectsIdSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwGetProjectsIdSuccess?(data: data) } } } func rwGetProjectsIdFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwGetProjectsIdFailure != nil) { self.dam { rwfp.rwGetProjectsIdFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwGetProjectsIdFailure"), message: error!.localizedDescription) } } } func rwGetProjectsIdTagsSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwGetProjectsIdTagsSuccess?(data: data) } } } func rwGetProjectsIdTagsFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwGetProjectsIdTagsFailure != nil) { self.dam { rwfp.rwGetProjectsIdTagsFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwGetProjectsIdTagsFailure"), message: error!.localizedDescription) } } } func rwGetProjectsIdUIGroupsSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwGetProjectsIdUIGroupsSuccess?(data: data) } } } func rwGetProjectsIdUIGroupsFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwGetProjectsIdTagsFailure != nil) { self.dam { rwfp.rwGetProjectsIdUIGroupsFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwGetProjectsIdUIGroupsFailure"), message: error!.localizedDescription) } } } func rwPostStreamsSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPostStreamsSuccess?(data: data) } } } func rwPostStreamsFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPostStreamsFailure != nil) { self.dam { rwfp.rwPostStreamsFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPostStreamsFailure"), message: error!.localizedDescription) } } } func rwPatchStreamsIdSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPatchStreamsIdSuccess?(data: data) } } } func rwPatchStreamsIdFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPatchStreamsIdFailure != nil) { self.dam { rwfp.rwPatchStreamsIdFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPatchStreamsIdFailure"), message: error!.localizedDescription) } } } func rwPostStreamsIdHeartbeatSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPostStreamsIdHeartbeatSuccess?(data: data) } } } func rwPostStreamsIdHeartbeatFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPostStreamsIdHeartbeatFailure != nil) { self.dam { rwfp.rwPostStreamsIdHeartbeatFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPostStreamsIdHeartbeatFailure"), message: error!.localizedDescription) } } } func rwPostStreamsIdSkipSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPostStreamsIdSkipSuccess?(data: data) } } } func rwPostStreamsIdSkipFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPostStreamsIdSkipFailure != nil) { self.dam { rwfp.rwPostStreamsIdSkipFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPostStreamsIdSkipFailure"), message: error!.localizedDescription) } } } func rwPostStreamsIdPlayAssetSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPostStreamsIdPlayAssetSuccess?(data: data) } } } func rwPostStreamsIdPlayAssetFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPostStreamsIdPlayAssetFailure != nil) { self.dam { rwfp.rwPostStreamsIdPlayAssetFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPostStreamsIdPlayAssetFailure"), message: error!.localizedDescription) } } } func rwPostStreamsIdReplayAssetSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPostStreamsIdReplayAssetSuccess?(data: data) } } } func rwPostStreamsIdReplayAssetFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPostStreamsIdReplayAssetFailure != nil) { self.dam { rwfp.rwPostStreamsIdReplayAssetFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPostStreamsIdReplayAssetFailure"), message: error!.localizedDescription) } } } func rwPostStreamsIdPauseSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPostStreamsIdPauseSuccess?(data: data) } } } func rwPostStreamsIdPauseFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPostStreamsIdPauseFailure != nil) { self.dam { rwfp.rwPostStreamsIdPauseFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPostStreamsIdPauseFailure"), message: error!.localizedDescription) } } } func rwPostStreamsIdResumeSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPostStreamsIdResumeSuccess?(data: data) } } } func rwPostStreamsIdResumeFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPostStreamsIdResumeFailure != nil) { self.dam { rwfp.rwPostStreamsIdResumeFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPostStreamsIdResumeFailure"), message: error!.localizedDescription) } } } func rwGetStreamsIdCurrentSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwGetStreamsIdCurrentSuccess?(data: data) } } } func rwGetStreamsIdCurrentFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwGetStreamsIdCurrentFailure != nil) { self.dam { rwfp.rwGetStreamsIdCurrentFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwGetStreamsIdCurrentFailure"), message: error!.localizedDescription) } } } func rwPostEnvelopesSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPostEnvelopesSuccess?(data: data) } } } func rwPostEnvelopesFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPostEnvelopesFailure != nil) { self.dam { rwfp.rwPostEnvelopesFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPostEnvelopesFailure"), message: error!.localizedDescription) } } } func rwPatchEnvelopesIdSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPatchEnvelopesIdSuccess?(data: data) } } } func rwPatchEnvelopesIdFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPatchEnvelopesIdFailure != nil) { self.dam { rwfp.rwPatchEnvelopesIdFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPatchEnvelopesIdFailure"), message: error!.localizedDescription) } } } func rwGetAssetsSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwGetAssetsSuccess?(data: data) } } } func rwGetAssetsFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwGetAssetsFailure != nil) { self.dam { rwfp.rwGetAssetsFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwGetAssetsFailure"), message: error!.localizedDescription) } } } func rwGetAssetsIdSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwGetAssetsIdSuccess?(data: data) } } } func rwGetAssetsIdFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwGetAssetsIdFailure != nil) { self.dam { rwfp.rwGetAssetsIdFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwGetAssetsIdFailure"), message: error!.localizedDescription) } } } func rwPostAssetsIdVotesSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPostAssetsIdVotesSuccess?(data: data) } } } func rwPostAssetsIdVotesFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPostAssetsIdVotesFailure != nil) { self.dam { rwfp.rwPostAssetsIdVotesFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPostAssetsIdVotesFailure"), message: error!.localizedDescription) } } } func rwGetAssetsIdVotesSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwGetAssetsIdVotesSuccess?(data: data) } } } func rwGetAssetsIdVotesFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwGetAssetsIdVotesFailure != nil) { self.dam { rwfp.rwGetAssetsIdVotesFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwGetAssetsIdVotesFailure"), message: error!.localizedDescription) } } } func rwPostEventsSuccess(data: NSData?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPostEventsSuccess?(data: data) } } } func rwPostEventsFailure(error: NSError?) { protocaller { (rwfp, _) -> Void in if (rwfp.rwPostEventsFailure != nil) { self.dam { rwfp.rwPostEventsFailure?(error: error) } } else { self.alertOK(title: self.LS(key: "RWFramework - rwPostEventsFailure"), message: error!.localizedDescription) } } } // MARK: metadata func rwObserveValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSKeyValueChangeKey : AnyObject]?, context: UnsafeMutableRawPointer?) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwObserveValueForKeyPath?(keyPath: keyPath, ofObject: object, change: change, context: context) } } } // MARK: Image Picker func rwImagePickerControllerDidFinishPickingMedia(info: [String : AnyObject], path: String) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwImagePickerControllerDidFinishPickingMedia?(info: info, path: path) } } } func rwImagePickerControllerDidCancel() { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwImagePickerControllerDidCancel?() } } } // MARK: Record func rwReadyToRecord() { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwReadyToRecord?() } } } func rwRecordingProgress(percentage: Double, maxDuration: TimeInterval, peakPower: Float, averagePower: Float) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwRecordingProgress?(percentage: percentage, maxDuration: maxDuration, peakPower: peakPower, averagePower: averagePower) } } } func rwPlayingBackProgress(percentage: Double, duration: TimeInterval, peakPower: Float, averagePower: Float) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwPlayingBackProgress?(percentage: percentage, duration: duration, peakPower: peakPower, averagePower: averagePower) } } } func rwAudioRecorderDidFinishRecording() { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwAudioRecorderDidFinishRecording?() } } } func rwAudioPlayerDidFinishPlaying() { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwAudioPlayerDidFinishPlaying?() } } } // MARK: UI/Status func rwUpdateStatus(message: String) { var showedAlert = false protocaller { (rwfp, _) -> Void in if (rwfp.rwUpdateStatus != nil) { self.dam { rwfp.rwUpdateStatus?(message: message) } } else if (showedAlert == false) { showedAlert = true // Only show the alert once per call self.dam { let alert = UIAlertController(title: self.LS(key: "RWFramework"), message: message, preferredStyle: UIAlertControllerStyle.alert) let OKAction = UIAlertAction(title: self.LS(key: "OK"), style: .default) { (action) in } alert.addAction(OKAction) if let currentViewController = rwfp.rwGetCurrentViewController?() { currentViewController.present(alert, animated: true, completion: { () -> Void in }) } else { let assumedViewController = rwfp as! UIViewController assumedViewController.present(alert, animated: true, completion: { () -> Void in }) } } } } } func rwUpdateApplicationIconBadgeNumber(count: Int) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwUpdateApplicationIconBadgeNumber?(count: count) } } } // MARK: Location func rwLocationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwLocationManager?(manager: manager, didUpdateLocations: locations) } } } func rwLocationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { protocaller { (rwfp, _) -> Void in self.dam { rwfp.rwLocationManager?(manager: manager, didChangeAuthorizationStatus: status) } } } }
4d6a407675effcbfb0210c8f6f338c6c
39.091603
174
0.641698
false
false
false
false
pseudomuto/CircuitBreaker
refs/heads/master
Example/Tests/ClosedStateTests.swift
mit
1
// // ClosedStateTests.swift // CircuitBreaker // // Created by David Muto on 2016-02-05. // Copyright © 2016 CocoaPods. All rights reserved. // import Quick import Nimble @testable import CircuitBreaker class ClosedStateTests: QuickSpec { override func spec() { describe("ClosedState") { var subject: ClosedState! let breakerSwitch = MockSwitch() let invoker = MockInvoker() beforeEach { subject = ClosedState(breakerSwitch, invoker: invoker, errorThreshold: 2, invocationTimeout: 0.1) breakerSwitch.clearCalls() invoker.clearCalls() } context("initialization") { it("sets up all the things") { expect(subject.errorThreshold).to(equal(2)) expect(subject.invocationTimeout).to(equal(0.1)) expect(subject.failures).to(equal(0)) } } context("type") { it("is closed") { expect(subject.type()).to(equal(StateType.Closed)) } } context("activate") { it("resets failures to 0") { subject.onError() expect(subject.failures).to(equal(1)) subject.activate() expect(subject.failures).to(equal(0)) } } context("invoke") { it("invokes the block via the invoker") { let result = try! subject.invoke { return "ok" } expect(result).to(equal("ok")) expect(invoker).to(haveReceived("invoke")) } } context("onSuccess") { it("resets failures to 0") { subject.onError() expect(subject.failures).to(equal(1)) subject.activate() expect(subject.failures).to(equal(0)) } } context("onError") { it("increments the failure count") { let current = subject.failures subject.onError() expect(subject.failures).to(equal(current + 1)) } it("trips the circuit when errorThreshold reached") { subject.onError() subject.onError() expect(breakerSwitch).to(haveReceived("trip")) } it("only trips the switch when the threshold is reached") { subject.onError() expect(breakerSwitch).toNot(haveReceived("trip")) } } } } }
a3a2e574018f5d49d12647ab9ef8e3f2
24.946809
105
0.538745
false
false
false
false
iOS-Swift-Developers/Swift
refs/heads/master
基础语法/可选值/main.swift
mit
1
// // main.swift // 可选值 // // Created by 韩俊强 on 2017/6/1. // Copyright © 2017年 HaRi. All rights reserved. // import Foundation /* 可选值: optionals 有两种状态: 1.有值 2.没有值, 没有值就是nil */ //有值 var optValue1: Int? = 9 //没有值 var optValue2: Int? var optValue3: Int? = nil /* 可选值可以用if语句来进行判断 */ var optValue4: Int? if optValue4 != nil { print(optValue4) }else { print(optValue1) } /* 提取可选类型的值(强制解析) 会将optValue中的整型值强制拿出来赋值给result, 换言之就是告诉编译器optValue一定有值, 因为可选类型有两种状态 有值和没有值, 所以告诉编译器到底有没有值 需要注意的是如果强制解析optValue, 但是optValue中没有值时会引发一个运行时错误 */ var optValue5: Int? = 10 var result1: Int = optValue5! print(result1) //报错: //var optValue6: Int? //var result2: Int = optValue6! //print(result2) /* 可选绑定: 为了安全的解析可选类型的值, 一般情况下使用可选绑定 如果optValue没有值就不会做任何操作, 如果opValue有值会返回并将optValue的值赋值给result执行大括号中的内容 */ var optValue7: Int? = 11 if let result3 = optValue7 { print(result3) }
b1b5ba5b991b12d0a97e010f72bf7517
12.363636
88
0.712018
false
false
false
false
DTVD/APIKitExt
refs/heads/master
Carthage/Checkouts/APIKit/Sources/APIKit/Request.swift
mit
4
import Foundation import Result /// `Request` protocol represents a request for Web API. /// Following 5 items must be implemented. /// - `typealias Response` /// - `var baseURL: URL` /// - `var method: HTTPMethod` /// - `var path: String` /// - `func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response` public protocol Request { /// The response type associated with the request type. associatedtype Response /// The base URL. var baseURL: URL { get } /// The HTTP request method. var method: HTTPMethod { get } /// The path URL component. var path: String { get } /// The convenience property for `queryParameters` and `bodyParameters`. If the implementation of /// `queryParameters` and `bodyParameters` are not provided, the values for them will be computed /// from this property depending on `method`. var parameters: Any? { get } /// The actual parameters for the URL query. The values of this property will be escaped using `URLEncodedSerialization`. /// If this property is not implemented and `method.prefersQueryParameter` is `true`, the value of this property /// will be computed from `parameters`. var queryParameters: [String: Any]? { get } /// The actual parameters for the HTTP body. If this property is not implemented and `method.prefersQueryParameter` is `false`, /// the value of this property will be computed from `parameters` using `JSONBodyParameters`. var bodyParameters: BodyParameters? { get } /// The HTTP header fields. In addition to fields defined in this property, `Accept` and `Content-Type` /// fields will be added by `dataParser` and `bodyParameters`. If you define `Accept` and `Content-Type` /// in this property, the values in this property are preferred. var headerFields: [String: String] { get } /// The parser object that states `Content-Type` to accept and parses response body. var dataParser: DataParser { get } /// Intercepts `URLRequest` which is created by `Request.buildURLRequest()`. If an error is /// thrown in this method, the result of `Session.send()` turns `.failure(.requestError(error))`. /// - Throws: `ErrorType` func intercept(urlRequest: URLRequest) throws -> URLRequest /// Intercepts response `Any` and `HTTPURLResponse`. If an error is thrown in this method, /// the result of `Session.send()` turns `.failure(.responseError(error))`. /// The default implementation of this method is provided to throw `RequestError.unacceptableStatusCode` /// if the HTTP status code is not in `200..<300`. /// - Throws: `ErrorType` func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any /// Build `Response` instance from raw response object. This method is called after /// `intercept(object:urlResponse:)` if it does not throw any error. /// - Throws: `ErrorType` func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response } public extension Request { public var parameters: Any? { return nil } public var queryParameters: [String: Any]? { guard let parameters = parameters as? [String: Any], method.prefersQueryParameters else { return nil } return parameters } public var bodyParameters: BodyParameters? { guard let parameters = parameters, !method.prefersQueryParameters else { return nil } return JSONBodyParameters(JSONObject: parameters) } public var headerFields: [String: String] { return [:] } public var dataParser: DataParser { return JSONDataParser(readingOptions: []) } public func intercept(urlRequest: URLRequest) throws -> URLRequest { return urlRequest } public func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any { guard (200..<300).contains(urlResponse.statusCode) else { throw ResponseError.unacceptableStatusCode(urlResponse.statusCode) } return object } /// Builds `URLRequest` from properties of `self`. /// - Throws: `RequestError`, `ErrorType` public func buildURLRequest() throws -> URLRequest { let url = path.isEmpty ? baseURL : baseURL.appendingPathComponent(path) guard var components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { throw RequestError.invalidBaseURL(baseURL) } var urlRequest = URLRequest(url: url) if let queryParameters = queryParameters, !queryParameters.isEmpty { components.percentEncodedQuery = URLEncodedSerialization.string(from: queryParameters) } if let bodyParameters = bodyParameters { urlRequest.setValue(bodyParameters.contentType, forHTTPHeaderField: "Content-Type") switch try bodyParameters.buildEntity() { case .data(let data): urlRequest.httpBody = data case .inputStream(let inputStream): urlRequest.httpBodyStream = inputStream } } urlRequest.url = components.url urlRequest.httpMethod = method.rawValue urlRequest.setValue(dataParser.contentType, forHTTPHeaderField: "Accept") headerFields.forEach { key, value in urlRequest.setValue(value, forHTTPHeaderField: key) } return (try intercept(urlRequest: urlRequest) as URLRequest) } /// Builds `Response` from response `Data`. /// - Throws: `ResponseError`, `ErrorType` public func parse(data: Data, urlResponse: HTTPURLResponse) throws -> Response { let parsedObject = try dataParser.parse(data: data) let passedObject = try intercept(object: parsedObject, urlResponse: urlResponse) return try response(from: passedObject, urlResponse: urlResponse) } }
3116198f4656f07896a7c87ccb3651b1
38.891892
131
0.676152
false
false
false
false
AboutObjectsTraining/swift-comp-reston-2017-02
refs/heads/master
demos/Coolness/Coolness/CoolViewCell.swift
mit
1
import UIKit //let defaultAttributes = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)] private let xPadding: CGFloat = 10 private let yPadding: CGFloat = 5 private let textOrigin = CGPoint(x: xPadding, y: yPadding) class CoolViewCell: UIView { class var defaultAttributes: [String: Any] { return [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18), NSForegroundColorAttributeName: UIColor.white] } var text: String? { didSet { sizeToFit() } } var highlighted = false { didSet { alpha = highlighted ? 0.5 : 1.0 } } func configureLayer() { layer.borderWidth = 2 layer.borderColor = UIColor.white.cgColor layer.cornerRadius = 8 layer.masksToBounds = true } func configureGestureRecognizers() { let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(bounce(recognizer:))) addGestureRecognizer(tapRecognizer) let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(pan(recognizer:))) addGestureRecognizer(panRecognizer) } override init(frame: CGRect) { super.init(frame: frame) configureLayer() configureGestureRecognizers() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func pan(recognizer: UIPanGestureRecognizer) { // print("In \(#function)") let translation = recognizer.translation(in: nil) center.x += translation.x center.y += translation.y recognizer.setTranslation(CGPoint.zero, in: nil) highlighted = recognizer.state == .began || recognizer.state == .changed } } // MARK: - Animation extension CoolViewCell { func bounce(recognizer: UITapGestureRecognizer) { animateBounce(duration: 1.0, size: CGSize(width: 120, height: 240)) } func configureBounce(size: CGSize) { UIView.setAnimationRepeatCount(3.5) UIView.setAnimationRepeatAutoreverses(true) let translation = CGAffineTransform(translationX: size.width, y: size.height) transform = translation.rotated(by: CGFloat.pi / 2) } func animateCompletion(duration: TimeInterval, size: CGSize) { UIView.animate(withDuration: duration) { [weak self] in self?.transform = CGAffineTransform.identity } } func animateBounce(duration: TimeInterval, size: CGSize) { UIView.animate(withDuration: duration, animations: { [weak self] in self?.configureBounce(size: size) }, completion: { [weak self] _ in self?.animateCompletion(duration: duration, size: size) }) } } // MARK: - Drawing extension CoolViewCell { override func sizeThatFits(_ size: CGSize) -> CGSize { guard let text = text else { return size } var newSize = (text as NSString).size(attributes: type(of:self).defaultAttributes) newSize.width += 2 * xPadding newSize.height += 2 * yPadding return newSize } override func draw(_ rect: CGRect) { guard let text = text else { return } (text as NSString).draw(at: textOrigin, withAttributes: type(of:self).defaultAttributes) } } // MARK: - Responding to Touches extension CoolViewCell { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first, let view = touch.view as? CoolViewCell else { return } view.superview?.bringSubview(toFront: view) view.highlighted = true } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { // guard let touch = touches.first, let view = touch.view else { return } // // let currLocation = touch.location(in: view.superview) // let prevLocation = touch.previousLocation(in: view.superview) // // view.center.x += currLocation.x - prevLocation.x // view.center.y += currLocation.y - prevLocation.y } func finish(touch: UITouch?) { guard let view = touch?.view as? CoolViewCell else { return } view.highlighted = false } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { finish(touch: touches.first) } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { finish(touch: touches.first) } }
74a21d2df79f1d47904e1ec270cb063a
31.22695
104
0.635343
false
false
false
false
daaavid/TIY-Assignments
refs/heads/master
19--Forecaster/Forecaster/Forecaster/WeatherTableViewController.swift
cc0-1.0
1
// // WeatherTableViewController.swift // Forecaster // // Created by david on 10/29/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit let kLocationKey = "location" protocol ZipPopViewControllerDelegate { func zipWasChosen(zip: String, cc: String) } protocol DarkSkyAPIControllerProtocol { func darkSkySearchWasCompleted(results: NSDictionary, location: Location) // func darkSkySearchWasCompleted(results: NSDictionary) } protocol GoogleZipAPIControllerProtocol { func googleSearchWasCompleted(results: NSArray) } class WeatherTableViewController: UITableViewController, ZipPopViewControllerDelegate, UIPopoverPresentationControllerDelegate, DarkSkyAPIControllerProtocol, GoogleZipAPIControllerProtocol { var locationArr = [Location]() var googleAPI: GoogleZipAPIController! // var darkskyAPI: DarkSkyAPIController! // var weatherDetailVC: WeatherDetailViewController! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.leftBarButtonItem = self.editButtonItem() editButtonItem().tintColor = UIColor(red:0.00, green:0.75, blue:1.00, alpha:1.0) editButtonItem() view.backgroundColor = UIColor(red: 0.0, green: 0.65, blue: 0.86, alpha: 1.0) if locationArr.count == 0 { zipWasChosen(String(32801), cc: "zip") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return locationArr.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("WeatherCell", forIndexPath: indexPath) as! WeatherCell cell.backgroundColor = UIColor(white: 0.0, alpha: 0.0) let location = locationArr[indexPath.row] if location.city == "" { locationArr.removeAtIndex(indexPath.row) tableView.reloadData() UIApplication.sharedApplication().networkActivityIndicatorVisible = false } else if location.city != "" { cell.cityLabel.text = location.city + ", " + location.state cell.quickWeatherLabel.text = location.weather?.summary if location.weather?.temp != nil { cell.tempLabel.text = String(location.weather!.temp) + "°" assignWeatherImg(cell, icon: location.weather!.icon, location: location) } } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let chosenLocation = locationArr[indexPath.row] let weatherDetailVC = storyboard?.instantiateViewControllerWithIdentifier("WeatherDetail") as! WeatherDetailViewController weatherDetailVC.location = chosenLocation navigationController?.pushViewController(weatherDetailVC, animated: true) } //MARK: - View override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "popover" { let popVC = segue.destinationViewController as! ZipPopViewController popVC.popoverPresentationController?.delegate = self popVC.delegate = self popVC.locationArr = self.locationArr // popVC.view.backgroundColor = UIColor.whiteColor() popVC.preferredContentSize = CGSizeMake(280, 100) } } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } //MARK: - Images and Animation func assignWeatherImg(cell: WeatherCell, icon: String, location: Location) { cell.img.image = UIImage(named: location.weather!.icon) animateWeatherImg(cell, location: location) } func animateWeatherImg(cell: WeatherCell, location: Location) { if location.imgHasBeenAnimated == false { UIView.animateWithDuration(0.5, delay: 0.0, options: [], animations: { var img = cell.img.frame img.origin.x += img.size.width + 100 cell.quickWeatherLabel.frame = img cell.tempLabel.frame = img cell.img.frame = img }, completion: nil) location.imgHasBeenAnimated = true } } //MARK: - Private func zipWasChosen(zip: String, cc: String) { googleAPI = GoogleZipAPIController(delegate: self) print(zip, cc) googleAPI.search(zip, cc: cc) UIApplication.sharedApplication().networkActivityIndicatorVisible = true } // MARK: - Search func googleSearchWasCompleted(results: NSArray) { dispatch_async(dispatch_get_main_queue(), { self.dismissViewControllerAnimated(true, completion: nil) let userLocation = Location.locationWithJSON(results) self.locationArr.append(userLocation) let darkSkyAPI = DarkSkyAPIController(delegate: self) darkSkyAPI.search(userLocation) self.tableView.reloadData() }) } func darkSkySearchWasCompleted(results: NSDictionary, location: Location) { dispatch_async(dispatch_get_main_queue(), { if let weather = Weather.weatherWithJSON(results) { for city in self.locationArr { if city.city == location.city { city.weather = weather } } } self.tableView.reloadData() UIApplication.sharedApplication().networkActivityIndicatorVisible = false }) } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source locationArr.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) tableView.reloadData() } 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 } } func loadCityData() -> Bool { var rc = true if let data = NSUserDefaults.standardUserDefaults().objectForKey(kLocationKey) as? NSData { if let savedLocations = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Location] { locationArr = savedLocations rc = false tableView.reloadData() let darkSkyAPI = DarkSkyAPIController(delegate: self) for location in locationArr { darkSkyAPI.search(location) } } } return rc } func saveCityData() { let locationData = NSKeyedArchiver.archivedDataWithRootObject(locationArr) NSUserDefaults.standardUserDefaults().setObject(locationData, forKey: kLocationKey) } }
f4b486d7095b393c09fdf95608b1dce5
32.309623
188
0.619269
false
false
false
false
avito-tech/Marshroute
refs/heads/master
MarshrouteTests/Sources/Routers/ModalPresentationRouterTests/ModalPresentationRouterTests_BaseRouter.swift
mit
1
import XCTest @testable import Marshroute final class ModalPresentationRouterTests_BaseRouter: XCTestCase { var detailAnimatingTransitionsHandlerSpy: AnimatingTransitionsHandlerSpy! var router: ModalPresentationRouter! override func setUp() { super.setUp() let transitionIdGenerator = TransitionIdGeneratorImpl() let peekAndPopTransitionsCoordinator = PeekAndPopUtilityImpl() let transitionsCoordinator = TransitionsCoordinatorImpl( stackClientProvider: TransitionContextsStackClientProviderImpl(), peekAndPopTransitionsCoordinator: peekAndPopTransitionsCoordinator ) detailAnimatingTransitionsHandlerSpy = AnimatingTransitionsHandlerSpy( transitionsCoordinator: transitionsCoordinator ) router = BaseRouter( routerSeed: RouterSeed( transitionsHandlerBox: .init( animatingTransitionsHandler: detailAnimatingTransitionsHandlerSpy ), transitionId: transitionIdGenerator.generateNewTransitionId(), presentingTransitionsHandler: nil, transitionsHandlersProvider: transitionsCoordinator, transitionIdGenerator: transitionIdGenerator, controllersProvider: RouterControllersProviderImpl() ) ) } // MARK: - UIViewController func testThatRouterCallsItsTransitionsHandlerOn_PresentModalViewControllerDerivedFrom_WithCorrectPresentationContext() { // Given let targetViewController = UIViewController() var nextModuleRouterSeed: RouterSeed! // When router.presentModalViewControllerDerivedFrom { (routerSeed) -> UIViewController in nextModuleRouterSeed = routerSeed return targetViewController } // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssert(presentationContext?.targetViewController === targetViewController) if case .some(.animating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters) if case .some(.modal(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.targetViewController! == targetViewController) } else { XCTFail() } } func testThatRouterCallsItsTransitionsHandlerOn_PresentModalViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator() { // Given let targetViewController = UIViewController() var nextModuleRouterSeed: RouterSeed! let modalTransitionsAnimator = ModalTransitionsAnimator() // When router.presentModalViewControllerDerivedFrom( { (routerSeed) -> UIViewController in nextModuleRouterSeed = routerSeed return targetViewController }, animator: modalTransitionsAnimator ) // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssert(presentationContext?.targetViewController === targetViewController) if case .some(.animating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters) if case .some(.modal(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.animator === modalTransitionsAnimator) XCTAssert(launchingContext.targetViewController! === targetViewController) } else { XCTFail() } } // MARK: - UISplitViewController func testThatRouterCallsItsTransitionsHandlerOn_PresentModalMasterDetailViewControllerDerivedFrom_WithCorrectPresentationContext() { // Given let targetMasterViewController = UIViewController() let targetDetailViewController = UIViewController() var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed! var nextDetailModuleRouterSeed: RouterSeed! // When router.presentModalMasterDetailViewControllerDerivedFrom( deriveMasterViewController: { (routerSeed) -> UIViewController in nextMasterDetailModuleRouterSeed = routerSeed return targetMasterViewController }, deriveDetailViewController: { (routerSeed) -> UIViewController in nextDetailModuleRouterSeed = routerSeed return targetDetailViewController } ) // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId) XCTAssertEqual(presentationContext?.transitionId, nextDetailModuleRouterSeed.transitionId) if case .some(.containing) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters) if case .some(.modalMasterDetail) = presentationContext?.presentationAnimationLaunchingContextBox {} else { XCTFail() } } func testThatRouterCallsItsTransitionsHandlerOn_PresentModalMasterDetailViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator() { // Given let targetMasterViewController = UIViewController() let targetDetailViewController = UIViewController() let modalMasterDetailTransitionsAnimator = ModalMasterDetailTransitionsAnimator() var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed! var nextDetailModuleRouterSeed: RouterSeed! // When router.presentModalMasterDetailViewControllerDerivedFrom( deriveMasterViewController: { (routerSeed) -> UIViewController in nextMasterDetailModuleRouterSeed = routerSeed return targetMasterViewController }, deriveDetailViewController: { (routerSeed) -> UIViewController in nextDetailModuleRouterSeed = routerSeed return targetDetailViewController }, animator: modalMasterDetailTransitionsAnimator ) // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId) XCTAssertEqual(presentationContext?.transitionId, nextDetailModuleRouterSeed.transitionId) if case .some(.containing) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters) if case .some(.modalMasterDetail(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.animator === modalMasterDetailTransitionsAnimator) } else { XCTFail() } } func testThatRouterCallsItsTransitionsHandlerOn_PresentModalMasterDetailViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator_CustomMasterNavigationController_CustomDetailNavigationController_CustomSplitViewController() { // Given let targetMasterViewController = UIViewController() let targetDetailViewController = UIViewController() let splitViewController = UISplitViewController() let modalMasterDetailTransitionsAnimator = ModalMasterDetailTransitionsAnimator() var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed! var nextDetailModuleRouterSeed: RouterSeed! // When router.presentModalMasterDetailViewControllerDerivedFrom( deriveMasterViewController: { (routerSeed) -> UIViewController in nextMasterDetailModuleRouterSeed = routerSeed return targetMasterViewController }, deriveDetailViewController: { (routerSeed) -> UIViewController in nextDetailModuleRouterSeed = routerSeed return targetDetailViewController }, animator: modalMasterDetailTransitionsAnimator, masterNavigationController: UINavigationController(), detailNavigationController: UINavigationController(), splitViewController: splitViewController ) // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId) XCTAssertEqual(presentationContext?.transitionId, nextDetailModuleRouterSeed.transitionId) if case .some(.containing) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters) if case .some(.modalMasterDetail(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.animator === modalMasterDetailTransitionsAnimator) XCTAssert(launchingContext.targetViewController! === splitViewController) } else { XCTFail() } } // MARK: - UIViewController in UINavigationController func testThatRouterCallsItsTransitionsHandlerOn_PresentModalNavigationControllerWithRootViewControllerDerivedFrom_WithCorrectPresentationContext() { // Given let targetViewController = UIViewController() var nextModuleRouterSeed: RouterSeed! // When router.presentModalNavigationControllerWithRootViewControllerDerivedFrom { (routerSeed) -> UIViewController in nextModuleRouterSeed = routerSeed return targetViewController } // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssert(presentationContext?.targetViewController === targetViewController) if case .some(.animating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters) if case .some(.modalNavigation(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.targetViewController! == targetViewController) } else { XCTFail() } } func testThatRouterCallsItsTransitionsHandlerOn_PresentModalNavigationControllerWithRootViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator() { // Given let targetViewController = UIViewController() var nextModuleRouterSeed: RouterSeed! let modalNavigationTransitionsAnimator = ModalNavigationTransitionsAnimator() // When router.presentModalNavigationControllerWithRootViewControllerDerivedFrom( { (routerSeed) -> UIViewController in nextModuleRouterSeed = routerSeed return targetViewController }, animator: modalNavigationTransitionsAnimator ) // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssert(presentationContext?.targetViewController === targetViewController) if case .some(.animating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters) if case .some(.modalNavigation(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.animator === modalNavigationTransitionsAnimator) XCTAssert(launchingContext.targetViewController! === targetViewController) } else { XCTFail() } } func testThatRouterCallsItsTransitionsHandlerOn_PresentModalNavigationControllerWithRootViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator_CustomNavigationController() { // Given let targetViewController = UIViewController() let navigationController = UINavigationController() var nextModuleRouterSeed: RouterSeed! let modalNavigationTransitionsAnimator = ModalNavigationTransitionsAnimator() // When router.presentModalNavigationControllerWithRootViewControllerDerivedFrom( { (routerSeed) -> UIViewController in nextModuleRouterSeed = routerSeed return targetViewController }, animator: modalNavigationTransitionsAnimator, navigationController: navigationController ) // Then XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled) let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId) XCTAssert(presentationContext?.targetViewController === targetViewController) if case .some(.animating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() } XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters) if case .some(.modalNavigation(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox { XCTAssert(launchingContext.animator === modalNavigationTransitionsAnimator) XCTAssert(launchingContext.targetViewController! === targetViewController) XCTAssert(launchingContext.targetNavigationController! === navigationController) } else { XCTFail() } } }
57bcc679413e7c7d22ce074550b2c46b
53.173759
245
0.73411
false
false
false
false
GlobusLTD/components-ios
refs/heads/master
Demo/Sources/ViewControllers/TextView/TextViewController.swift
mit
1
// // Globus // import Globus class TextViewController: GLBViewController { // MARK - Outlet property @IBOutlet fileprivate weak var textView: GLBTextView! // MARK - UIViewController override func viewDidLoad() { super.viewDidLoad() self.textView.glb_borderColor = UIColor.darkGray self.textView.glb_borderWidth = 1 self.textView.glb_cornerRadius = 4 self.textView.minimumHeight = 48 self.textView.maximumHeight = 96 let placeholderStyle = GLBTextStyle() placeholderStyle.font = UIFont.boldSystemFont(ofSize: 16) placeholderStyle.color = UIColor.lightGray self.textView.placeholderStyle = placeholderStyle self.textView.placeholder = "Placeholder" self.textView.actionValueChanged = GLBAction(target: self, action: #selector(changedText(_:))) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.textView.becomeFirstResponder() } // MARK - Action @IBAction internal func pressedMenu(_ sender: Any) { self.glb_slideViewController?.showLeftViewController(animated: true, complete: nil) } @IBAction internal func changedText(_ sender: Any) { print("ChangedText: \(self.textView.text)") } // MARK: - GLBNibExtension public override static func nibName() -> String { return "TextViewController-Swift" } }
58c485c22f61dc54ce63d014b08fcfe2
26.527273
102
0.641347
false
false
false
false
RxSwiftCommunity/RxSwift-Ext
refs/heads/main
Tests/RxSwift/OnceTests.swift
mit
2
// // OnceTests.swift // RxSwiftExt // // Created by Florent Pillet on 12/04/16. // Copyright © 2016 RxSwift Community. All rights reserved. // import XCTest import RxSwift import RxSwiftExt import RxTest class OnceTests: XCTestCase { func testOnce() { let onceObservable = Observable.once("Hello") let scheduler = TestScheduler(initialClock: 0) let observer1 = scheduler.createObserver(String.self) _ = onceObservable.subscribe(observer1) let observer2 = scheduler.createObserver(String.self) _ = onceObservable.subscribe(observer2) scheduler.start() let correct1 = Recorded.events([ .next(0, "Hello"), .completed(0) ]) let correct2: [Recorded<Event<String>>] = [ .completed(0) ] XCTAssertEqual(observer1.events, correct1) XCTAssertEqual(observer2.events, correct2) } func testMultipleOnce() { let onceObservable1 = Observable.once("Hello") let onceObservable2 = Observable.once("world") let scheduler = TestScheduler(initialClock: 0) let observer1 = scheduler.createObserver(String.self) _ = onceObservable1.subscribe(observer1) let observer2 = scheduler.createObserver(String.self) _ = onceObservable1.subscribe(observer2) let observer3 = scheduler.createObserver(String.self) _ = onceObservable2.subscribe(observer3) let observer4 = scheduler.createObserver(String.self) _ = onceObservable2.subscribe(observer4) scheduler.start() let correct1 = Recorded.events([ .next(0, "Hello"), .completed(0) ]) let correct2: [Recorded<Event<String>>] = [ .completed(0) ] let correct3 = Recorded.events([ .next(0, "world"), .completed(0) ]) let correct4: [Recorded<Event<String>>] = [ .completed(0) ] XCTAssertEqual(observer1.events, correct1) XCTAssertEqual(observer2.events, correct2) XCTAssertEqual(observer3.events, correct3) XCTAssertEqual(observer4.events, correct4) } }
da87526d2c956d3827cec04c4c44a011
25.650602
61
0.617541
false
true
false
false
git-hushuai/MOMO
refs/heads/master
MMHSMeterialProject/HSTabBarController.swift
mit
1
// // HSTabBarController.swift // MMMaterialProject // // Created by hushuaike on 16/3/24. // Copyright © 2016年 hushuaike. All rights reserved. // import UIKit class HSTabBarController: UITabBarController { var tabBarBtnTitleArray : NSMutableArray = NSMutableArray(); var tabSelectedIndex:NSInteger = 0{ didSet{ print("select did select :\(tabSelectedIndex)"); // super.selectedIndex = tabSelectedIndex; let btn1 = self.tabBar.viewWithTag(100+self.selectedIndex) as? UIButton; print("btn1 info :\(btn1)"); btn1?.selected = false; let btn2 = self.tabBar.viewWithTag(100+tabSelectedIndex) as? UIButton; print("btn2 info :\(btn1)"); btn2?.selected = true; self.selectedIndex = tabSelectedIndex; } }; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.tabBar.backgroundColor = RGBA(0xf3, g: 0xf3, b: 0xf3, a: 1.0); } func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat)->UIColor { return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) } func TAB_BAR_HEIGHT()->CGFloat{ return 49.0; } internal func setTabImages(tabImages:NSArray,highlightedImages:NSArray){ let width = Int(Float(self.view.bounds.size.width))/(tabImages.count); print("width \(width)"); for var i = 0 ;i<tabImages.count;++i{ let norImage = tabImages.objectAtIndex(i); let highlightedImg = highlightedImages.objectAtIndex(i); let btnTitle = self.tabBarBtnTitleArray.objectAtIndex(i); let tabBtn = HSTabBarBtn(); tabBtn.frame = CGRectMake(CGFloat(i*width), 0, CGFloat(width), TAB_BAR_HEIGHT()); tabBtn.tag = 100+i; tabBtn.setImage(norImage as? UIImage, forState:.Normal); tabBtn.setImage(highlightedImg as? UIImage, forState: .Highlighted); tabBtn.setImage(highlightedImg as? UIImage, forState: .Selected); tabBtn.setTitle(btnTitle as? String,forState: .Normal); tabBtn.setTitleColor(RGBA(0x7c, g: 0x7c, b: 0x7c, a: 1.0), forState:.Normal); tabBtn.setTitleColor(RGBA(0x3c, g: 0xb3, b: 0xec, a: 1.0), forState: .Highlighted); tabBtn.setTitleColor(RGBA(0x3c, g: 0xb3, b: 0xec, a: 1.0), forState: .Selected); tabBtn.backgroundColor = RGBA(0xf8, g:0xf8, b: 0xf8, a: 1.0); tabBtn.addTarget(self, action: "onTabBarBtnClickAction:", forControlEvents: .TouchUpInside); self.tabBar.addSubview(tabBtn); if i==0{ tabBtn.selected = true; self.tabSelectedIndex = 0; } } } func onTabBarBtnClickAction(sender:UIButton){ print("tabBar title :\(sender.titleLabel?.text)") let index = sender.tag-100; if self.tabSelectedIndex != index{ self.tabSelectedIndex = index; }else{ } } // convenience init(){ // self.init(); // } // // convenience init(controllers : NSArray){ // self.init(); // self.viewControllers = controllers as? [UIViewController]; // let controller = controllers.objectAtIndex(0) as? UIViewController; // self.title = controller?.title; // } // // required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } // override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
54adcf5b1d4ec30c7a72ba15f61857ba
31.596899
106
0.591677
false
false
false
false
Gitliming/Demoes
refs/heads/master
Demoes/Demoes/CustomAnimationNav/CustomAnimaViewNavigation.swift
apache-2.0
1
// // CustomAnimaViewNavigation.swift // Dispersive switch // // Created by xpming on 16/6/8. // Copyright © 2016年 xpming. All rights reserved. // import UIKit class CustomAnimaViewNavigation: UINavigationController , UINavigationControllerDelegate { var isPush:Bool = false //动画的起始位置 var imageRect:CGRect? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func pushViewController(_ viewController: UIViewController,Rect:CGRect, animated: Bool) { self.delegate = self imageRect = Rect isPush = true super.pushViewController(viewController, animated: true) } override func popViewController(animated: Bool) -> UIViewController? { isPush = false return super.popViewController(animated: true) } func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { let animatedTransition = NavigateAnimation() animatedTransition.isPush = isPush animatedTransition.imageRect = imageRect if !isPush { self.delegate = nil } return animatedTransition } }
abca0b76d42b766f880c3adc4cc995af
30.22
246
0.675208
false
false
false
false
TheTekton/Malibu
refs/heads/master
Sources/Response/Wave.swift
mit
1
import Foundation import When open class Wave: Equatable { open let data: Data open let request: URLRequest open let response: HTTPURLResponse public init(data: Data, request: URLRequest, response: HTTPURLResponse) { self.data = data self.request = request self.response = response } } // MARK: - Equatable public func ==(lhs: Wave, rhs: Wave) -> Bool { return lhs.data == rhs.data && lhs.request == rhs.request && lhs.response == rhs.response }
1e530de56ec66810d3789080a1420669
20
75
0.679089
false
false
false
false
mikina/Swift-play
refs/heads/master
Archive/CustomSwipeBack/CustomSwipeBack/FadeAnimator.swift
gpl-3.0
1
// // FadeAnimator.swift // CustomSwipeBack // // Created by Mike Mikina on 5/3/16. // Copyright © 2016 FDT. All rights reserved. // import UIKit class FadeAnimator: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.35 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { guard let toView = transitionContext.viewForKey(UITransitionContextToViewKey) else { return } guard let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey) else { return } let containerView = transitionContext.containerView() toView.alpha = 0 containerView?.addSubview(toView) UIView.animateWithDuration(0.35, animations: { toView.alpha = 1 }) { (finished) in fromView.removeFromSuperview() transitionContext.completeTransition(finished) } } }
b238d5102709ec70441745cc86e21706
24.175
103
0.709037
false
false
false
false
CodeJoyTeam/SwiftSimpleFramwork
refs/heads/master
SwiftDemo/Network/NetworkTool.swift
mit
3
// // NetworkTool.swift // SwiftDemo // // Created by zhoutong on 2017/1/4. // Base on Aerolitec Template // Copyright © 2017年 zhoutong. All rights reserved. // import UIKit import SwiftyJSON import Alamofire // MARK: - // MARK: NetworkTool // MARK: - private let obj = NetworkTool() class NetworkTool { class var sharedInstance : NetworkTool { return obj } } extension NetworkTool { //MARK: - GET 请求 // let tools : NetworkRequest.shareInstance! func getRequest(urlString: String, params : [String : Any]? = nil, success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) { //使用Alamofire进行网络请求时,调用该方法的参数都是通过getRequest(urlString, params, success :, failture :)传入的,而success传入的其实是一个接受 [String : AnyObject]类型 返回void类型的函数 DLog(message: urlString) DLog(message: params) Alamofire.request(urlString, method: .get, parameters: params) .responseJSON { (response) in/*这里使用了闭包*/ //当请求后response是我们自定义的,这个变量用于接受服务器响应的信息 //使用switch判断请求是否成功,也就是response的result switch response.result { case .success(let value): //当响应成功是,使用临时变量value接受服务器返回的信息并判断是否为[String: AnyObject]类型 如果是那么将其传给其定义方法中的success if let value = response.result.value as? [String: AnyObject] { success(value) } let json = JSON(value) DLog(message: json) case .failure(let error): failture(error) DLog(message: "error:\(error)") } } } //MARK: - POST 请求 func postRequest(urlString : String, params : [String : Any], success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()) { Alamofire.request(urlString, method: HTTPMethod.post, parameters: params).responseJSON { (response) in switch response.result{ case .success: if let value = response.result.value as? [String: AnyObject] { success(value) let json = JSON(value) DLog(message: json) } case .failure(let error): failture(error) DLog(message: "error:\(error)") } } } //MARK: - 照片上传 /// /// - Parameters: /// - urlString: 服务器地址 /// - params: ["flag":"","userId":""] - flag,userId 为必传参数 /// flag - 666 信息上传多张 -999 服务单上传 -000 头像上传 /// - data: image转换成Data /// - name: fileName /// - success: /// - failture: func upLoadImageRequest(urlString : String, params:[String:String], data: [Data], name: [String],success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()){ let headers = ["content-type":"multipart/form-data"] Alamofire.upload( multipartFormData: { multipartFormData in //666多张图片上传 let flag = params["flag"] let userId = params["userId"] multipartFormData.append((flag?.data(using: String.Encoding.utf8)!)!, withName: "flag") multipartFormData.append( (userId?.data(using: String.Encoding.utf8)!)!, withName: "userId") for i in 0..<data.count { multipartFormData.append(data[i], withName: "appPhoto", fileName: name[i], mimeType: "image/png") } }, to: urlString, headers: headers, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in if let value = response.result.value as? [String: AnyObject]{ success(value) let json = JSON(value) DLog(message: json) } } case .failure(let encodingError): DLog(message: encodingError) failture(encodingError) } } ) } }
8a316c4538e5eb29920a44ef1e98e915
35.308943
206
0.512091
false
false
false
false
frootloops/swift
refs/heads/master
test/SILGen/opaque_values_silgen_lib.swift
apache-2.0
1
// RUN: %target-swift-frontend -enable-sil-ownership -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen -module-name Swift %s | %FileCheck %s // UNSUPPORTED: resilient_stdlib precedencegroup AssignmentPrecedence { assignment: true } enum Optional<Wrapped> { case none case some(Wrapped) } protocol EmptyP {} struct String { var ptr: Builtin.NativeObject } // Tests Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value) // --- // CHECK-LABEL: sil hidden @_T0s21s010______PAndS_casesyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[MTYPE:%.*]] = metatype $@thin PAndSEnum.Type // CHECK: [[EAPPLY:%.*]] = apply {{.*}}([[MTYPE]]) : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in EmptyP, @owned String) -> @out PAndSEnum // CHECK: destroy_value [[EAPPLY]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T0s21s010______PAndS_casesyyF' func s010______PAndS_cases() { _ = PAndSEnum.A } // Test emitBuiltinReinterpretCast. // --- // CHECK-LABEL: sil hidden @_T0s21s020__________bitCastq_x_q_m2totr0_lF : $@convention(thin) <T, U> (@in T, @thick U.Type) -> @out U { // CHECK: [[BORROW:%.*]] = begin_borrow %0 : $T // CHECK: [[COPY:%.*]] = copy_value [[BORROW]] : $T // CHECK: [[CAST:%.*]] = unchecked_bitwise_cast [[COPY]] : $T to $U // CHECK: [[RET:%.*]] = copy_value [[CAST]] : $U // CHECK: destroy_value [[COPY]] : $T // CHECK: return [[RET]] : $U // CHECK-LABEL: } // end sil function '_T0s21s020__________bitCastq_x_q_m2totr0_lF' func s020__________bitCast<T, U>(_ x: T, to type: U.Type) -> U { return Builtin.reinterpretCast(x) } // Test emitBuiltinCastReference // --- // CHECK-LABEL: sil hidden @_T0s21s030__________refCastq_x_q_m2totr0_lF : $@convention(thin) <T, U> (@in T, @thick U.Type) -> @out U { // CHECK: bb0(%0 : @owned $T, %1 : @trivial $@thick U.Type): // CHECK: [[BORROW:%.*]] = begin_borrow %0 : $T // CHECK: [[COPY:%.*]] = copy_value [[BORROW]] : $T // CHECK: [[SRC:%.*]] = alloc_stack $T // CHECK: store [[COPY]] to [init] [[SRC]] : $*T // CHECK: [[DEST:%.*]] = alloc_stack $U // CHECK: unchecked_ref_cast_addr T in [[SRC]] : $*T to U in [[DEST]] : $*U // CHECK: [[LOAD:%.*]] = load [take] [[DEST]] : $*U // CHECK: dealloc_stack [[DEST]] : $*U // CHECK: dealloc_stack [[SRC]] : $*T // CHECK: destroy_value %0 : $T // CHECK: return [[LOAD]] : $U // CHECK-LABEL: } // end sil function '_T0s21s030__________refCastq_x_q_m2totr0_lF' func s030__________refCast<T, U>(_ x: T, to: U.Type) -> U { return Builtin.castReference(x) } // Init of Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value) // --- // CHECK-LABEL: sil shared [transparent] @_T0s9PAndSEnumO1AABs6EmptyP_p_SStcABmF : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum { // CHECK: bb0([[ARG0:%.*]] : @owned $EmptyP, [[ARG1:%.*]] : @owned $String, [[ARG2:%.*]] : @trivial $@thin PAndSEnum.Type): // CHECK: [[RTUPLE:%.*]] = tuple ([[ARG0]] : $EmptyP, [[ARG1]] : $String) // CHECK: [[RETVAL:%.*]] = enum $PAndSEnum, #PAndSEnum.A!enumelt.1, [[RTUPLE]] : $(EmptyP, String) // CHECK: return [[RETVAL]] : $PAndSEnum // CHECK-LABEL: } // end sil function '_T0s9PAndSEnumO1AABs6EmptyP_p_SStcABmF' // CHECK-LABEL: sil shared [transparent] [thunk] @_T0s9PAndSEnumO1AABs6EmptyP_p_SStcABmFTc : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in EmptyP, @owned String) -> @out PAndSEnum { // CHECK: bb0([[ARG:%.*]] : @trivial $@thin PAndSEnum.Type): // CHECK: [[RETVAL:%.*]] = partial_apply [callee_guaranteed] {{.*}}([[ARG]]) : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum // CHECK: return [[RETVAL]] : $@callee_guaranteed (@in EmptyP, @owned String) -> @out PAndSEnum // CHECK-LABEL: } // end sil function '_T0s9PAndSEnumO1AABs6EmptyP_p_SStcABmFTc' enum PAndSEnum { case A(EmptyP, String) }
c181476c9aa1d931ad3307a0a52c5d34
51.552632
211
0.621182
false
false
false
false
cbh2000/flickrtest
refs/heads/develop
FlickrTest/ImageViewController.swift
mit
1
// // ImageViewController.swift // FlickrTest // // Created by Christopher Bryan Henderson on 9/20/16. // Copyright © 2016 Christopher Bryan Henderson. All rights reserved. // import UIKit /** * Here, I decided to create the view controller programmatically, without the use of Storyboard. * * Sadly, there is no pinch to zoom, but you can rotate the phone into landscape. */ class ImageViewController: UIViewController { let imageView = UIImageView() let closeButton = UIButton() let spinner = UIActivityIndicatorView() convenience init(imageURL: URL) { self.init(nibName: nil, bundle: nil) setImage(with: imageURL) } func setImage(with url: URL) { imageView.sd_setImage(with: url) { (image: UIImage?, _, _, _) in self.spinner.stopAnimating() self.spinner.isHidden = true } } override var prefersStatusBarHidden: Bool { return true } override func viewDidLoad() { super.viewDidLoad() // TODO: This doesn't work on the iOS 10 simulator, but it looks ok nonetheless. view.backgroundColor = UIColor.black.withAlphaComponent(0.5) // Makes it fade in instead of sliding in. modalTransitionStyle = .crossDissolve modalPresentationStyle = .overCurrentContext spinner.activityIndicatorViewStyle = .white spinner.startAnimating() spinner.translatesAutoresizingMaskIntoConstraints = false view.addSubview(spinner) spinner.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true spinner.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true // Configure the image view. imageView.backgroundColor = .clear imageView.contentMode = .scaleAspectFit // Required for programmatically created views or else auto-generated constrants will conflict with ours. imageView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(imageView) // Alternatively, you can create the NSLayoutConstraints directly, or just set the frames in view(Did|Will)LayoutSubviews. imageView.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor).isActive = true imageView.heightAnchor.constraint(lessThanOrEqualTo: view.heightAnchor).isActive = true imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true // Configure the button. closeButton.translatesAutoresizingMaskIntoConstraints = false closeButton.setImage(UIImage(named: "close"), for: []) closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside) view.addSubview(closeButton) // Layout close button closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -15).isActive = true closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 15).isActive = true closeButton.widthAnchor.constraint(equalToConstant: 44).isActive = true closeButton.heightAnchor.constraint(equalToConstant: 44).isActive = true } func closeTapped() { dismiss(animated: true, completion: nil) } }
2509b6b273d752bbaf006785d40243d6
39.674699
130
0.689277
false
false
false
false
iOSDevLog/iOSDevLog
refs/heads/master
116. Dropit/Dropit/DropitBehavior.swift
mit
1
// // DropitBehavior.swift // Dropit // // Created by jiaxianhua on 15/10/4. // Copyright © 2015年 com.jiaxh. All rights reserved. // import UIKit class DropitBehavior: UIDynamicBehavior { let gravity = UIGravityBehavior() lazy var collider: UICollisionBehavior = { let lazilyCreatedCOllider = UICollisionBehavior() lazilyCreatedCOllider.translatesReferenceBoundsIntoBoundary = true return lazilyCreatedCOllider }() lazy var dropBehavior: UIDynamicItemBehavior = { let lazilyCreatedDropBehavior = UIDynamicItemBehavior() lazilyCreatedDropBehavior.allowsRotation = false lazilyCreatedDropBehavior.elasticity = 0.75 return lazilyCreatedDropBehavior }() override init() { super.init() addChildBehavior(gravity) addChildBehavior(collider) addChildBehavior(dropBehavior) } func addBarrier(path: UIBezierPath, named name: String) { collider.removeBoundaryWithIdentifier(name) collider.addBoundaryWithIdentifier(name, forPath: path) } func addDrop(drop: UIView) { dynamicAnimator?.referenceView?.addSubview(drop) gravity.addItem(drop) collider.addItem(drop) dropBehavior.addItem(drop) } func removeDrop(drop: UIView) { gravity.removeItem(drop) collider.removeItem(drop) dropBehavior.removeItem(drop) drop.removeFromSuperview() } }
8fb04906c69171b16545bf31ba191245
27
74
0.673854
false
false
false
false
iosyoujian/SwiftTask
refs/heads/swift/2.0
Playgrounds/02-Async.playground/Contents.swift
mit
4
//: Playground - noun: a place where people can play import Cocoa import XCPlayground // // NOTE: custom framework needs to be built first (and restart Xcode if needed) // // Importing Custom Frameworks Into a Playground // https://developer.apple.com/library/prerelease/ios/recipes/Playground_Help/Chapters/ImportingaFrameworkIntoaPlayground.html // import SwiftTask typealias Progress = Float typealias Value = String typealias Error = NSError typealias MyTask = Task<Progress, Value, Error> let myError = NSError(domain: "MyErrorDomain", code: 0, userInfo: nil) // for async test XCPSetExecutionShouldContinueIndefinitely() // fulfills after 100ms func asyncTask(value: String) -> MyTask { return MyTask { progress, fulfill, reject, configure in dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 100_000_000), dispatch_get_main_queue()) { fulfill(value) } } } //-------------------------------------------------- // Example 1: Async //-------------------------------------------------- let task1a = asyncTask("Hello") let task1b = task1a .success { value -> String in return "\(value) World" } // NOTE: these values should be all nil because task is async task1a.value task1a.errorInfo task1b.value task1b.errorInfo //-------------------------------------------------- // Example 2: Async chaining //-------------------------------------------------- let task2a = asyncTask("Hello") let task2b = task2a .success { value -> MyTask in return asyncTask("\(value) Cruel") // next async } .success { value -> String in return "\(value) World" }
6ceeb0caee0e110eb7b117cb7f67ef79
25.419355
126
0.613928
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/PlaygroundTransform/declarations.swift
apache-2.0
15
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %S/Inputs/SilentPCMacroRuntime.swift %t/main.swift // RUN: %target-run %t/main | %FileCheck %s // REQUIRES: executable_test var a = 2 var b = 3 a + b // CHECK: [{{.*}}] $builtin_log[a='2'] // CHECK-NEXT: [{{.*}}] $builtin_log[b='3'] // CHECK-NEXT: [{{.*}}] $builtin_log[='5']
97a90b64ebecb905b0dcba2d47c4b934
46.571429
197
0.666667
false
true
false
false
syoung-smallwisdom/BridgeAppSDK
refs/heads/master
BridgeAppSDK/SBAProfileInfoForm.swift
bsd-3-clause
1
// // SBARegistrationForm.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchKit public enum SBAProfileInfoOption : String { case email = "email" case password = "password" case externalID = "externalID" case name = "name" case birthdate = "birthdate" case gender = "gender" } enum SBAProfileInfoOptionsError: Error { case missingRequiredOptions case missingEmail case missingExternalID case missingName case notConsented case unrecognizedSurveyItemType } struct SBAExternalIDOptions { static let defaultAutocapitalizationType: UITextAutocapitalizationType = .allCharacters static let defaultKeyboardType: UIKeyboardType = .asciiCapable let autocapitalizationType: UITextAutocapitalizationType let keyboardType: UIKeyboardType init() { self.autocapitalizationType = SBAExternalIDOptions.defaultAutocapitalizationType self.keyboardType = SBAExternalIDOptions.defaultKeyboardType } init(autocapitalizationType: UITextAutocapitalizationType, keyboardType: UIKeyboardType) { self.autocapitalizationType = autocapitalizationType self.keyboardType = keyboardType } init(options: [AnyHashable: Any]?) { self.autocapitalizationType = { if let autocap = options?["autocapitalizationType"] as? String { return UITextAutocapitalizationType(key: autocap) } else { return SBAExternalIDOptions.defaultAutocapitalizationType } }() self.keyboardType = { if let keyboard = options?["keyboardType"] as? String { return UIKeyboardType(key: keyboard) } else { return SBAExternalIDOptions.defaultKeyboardType } }() } } public struct SBAProfileInfoOptions { public let includes: [SBAProfileInfoOption] public let customOptions: [Any] let externalIDOptions: SBAExternalIDOptions public init(includes: [SBAProfileInfoOption]) { self.includes = includes self.externalIDOptions = SBAExternalIDOptions() self.customOptions = [] } init(externalIDOptions: SBAExternalIDOptions) { self.includes = [.externalID] self.externalIDOptions = externalIDOptions self.customOptions = [] } public init?(inputItem: SBASurveyItem?) { guard let surveyForm = inputItem as? SBAFormStepSurveyItem, let items = surveyForm.items else { return nil } // Map the includes, and if it is an external ID then also map the keyboard options var externalIDOptions = SBAExternalIDOptions(autocapitalizationType: .none, keyboardType: .default) var customOptions: [Any] = [] self.includes = items.mapAndFilter({ (obj) -> SBAProfileInfoOption? in if let str = obj as? String { return SBAProfileInfoOption(rawValue: str) } else if let dictionary = obj as? [String : AnyObject], let identifier = dictionary["identifier"] as? String, let option = SBAProfileInfoOption(rawValue: identifier) { if option == .externalID { externalIDOptions = SBAExternalIDOptions(options: dictionary) } return option } else { customOptions.append(obj) } return nil }) self.externalIDOptions = externalIDOptions self.customOptions = customOptions } func makeFormItems(surveyItemType: SBASurveyItemType) -> [ORKFormItem] { var formItems: [ORKFormItem] = [] for option in self.includes { switch option { case .email: let formItem = makeEmailFormItem(option) formItems.append(formItem) case .password: let (formItem, answerFormat) = makePasswordFormItem(option) formItems.append(formItem) // confirmation if (surveyItemType == .account(.registration)) { let confirmFormItem = makeConfirmationFormItem(formItem, answerFormat: answerFormat) formItems.append(confirmFormItem) } case .externalID: let formItem = makeExternalIDFormItem(option) formItems.append(formItem) case .name: let formItem = makeNameFormItem(option) formItems.append(formItem) case .birthdate: let formItem = makeBirthdateFormItem(option) formItems.append(formItem) case .gender: let formItem = makeGenderFormItem(option) formItems.append(formItem) } } return formItems } func makeEmailFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { let answerFormat = ORKAnswerFormat.emailAnswerFormat() let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("EMAIL_FORM_ITEM_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("EMAIL_FORM_ITEM_PLACEHOLDER") return formItem } func makePasswordFormItem(_ option: SBAProfileInfoOption) -> (ORKFormItem, ORKTextAnswerFormat) { let answerFormat = ORKAnswerFormat.textAnswerFormat() answerFormat.multipleLines = false answerFormat.isSecureTextEntry = true answerFormat.autocapitalizationType = .none answerFormat.autocorrectionType = .no answerFormat.spellCheckingType = .no let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("PASSWORD_FORM_ITEM_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("PASSWORD_FORM_ITEM_PLACEHOLDER") return (formItem, answerFormat) } func makeConfirmationFormItem(_ formItem: ORKFormItem, answerFormat: ORKTextAnswerFormat) -> ORKFormItem { // If this is a registration, go ahead and set the default password verification let minLength = SBARegistrationStep.defaultPasswordMinLength let maxLength = SBARegistrationStep.defaultPasswordMaxLength answerFormat.validationRegex = "[[:ascii:]]{\(minLength),\(maxLength)}" answerFormat.invalidMessage = Localization.localizedStringWithFormatKey("SBA_REGISTRATION_INVALID_PASSWORD_LENGTH_%@_TO_%@", NSNumber(value: minLength), NSNumber(value: maxLength)) // Add a confirmation field let confirmIdentifier = SBARegistrationStep.confirmationIdentifier let confirmText = Localization.localizedString("CONFIRM_PASSWORD_FORM_ITEM_TITLE") let confirmError = Localization.localizedString("CONFIRM_PASSWORD_ERROR_MESSAGE") let confirmFormItem = formItem.confirmationAnswer(withIdentifier: confirmIdentifier, text: confirmText, errorMessage: confirmError) confirmFormItem.placeholder = Localization.localizedString("CONFIRM_PASSWORD_FORM_ITEM_PLACEHOLDER") return confirmFormItem } func makeExternalIDFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { let answerFormat = ORKAnswerFormat.textAnswerFormat() answerFormat.multipleLines = false answerFormat.autocapitalizationType = self.externalIDOptions.autocapitalizationType answerFormat.autocorrectionType = .no answerFormat.spellCheckingType = .no answerFormat.keyboardType = self.externalIDOptions.keyboardType let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("SBA_REGISTRATION_EXTERNALID_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("SBA_REGISTRATION_EXTERNALID_PLACEHOLDER") return formItem } func makeNameFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { let answerFormat = ORKAnswerFormat.textAnswerFormat() answerFormat.multipleLines = false answerFormat.autocapitalizationType = .words answerFormat.autocorrectionType = .no answerFormat.spellCheckingType = .no answerFormat.keyboardType = .default let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("SBA_REGISTRATION_FULLNAME_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("SBA_REGISTRATION_FULLNAME_PLACEHOLDER") return formItem } func makeBirthdateFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { // Calculate default date (20 years old). let defaultDate = (Calendar.current as NSCalendar).date(byAdding: .year, value: -20, to: Date(), options: NSCalendar.Options(rawValue: 0)) let answerFormat = ORKAnswerFormat.dateAnswerFormat(withDefaultDate: defaultDate, minimumDate: nil, maximumDate: Date(), calendar: Calendar.current) let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("DOB_FORM_ITEM_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("DOB_FORM_ITEM_PLACEHOLDER") return formItem } func makeGenderFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { let textChoices: [ORKTextChoice] = [ ORKTextChoice(text: Localization.localizedString("GENDER_FEMALE"), value: HKBiologicalSex.female.rawValue as NSNumber), ORKTextChoice(text: Localization.localizedString("GENDER_MALE"), value: HKBiologicalSex.male.rawValue as NSNumber), ORKTextChoice(text: Localization.localizedString("GENDER_OTHER"), value: HKBiologicalSex.other.rawValue as NSNumber), ] let answerFormat = ORKValuePickerAnswerFormat(textChoices: textChoices) let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("GENDER_FORM_ITEM_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("GENDER_FORM_ITEM_PLACEHOLDER") return formItem } } public protocol SBAFormProtocol : class { var identifier: String { get } var title: String? { get set } var text: String? { get set } var formItems: [ORKFormItem]? { get set } init(identifier: String) } extension SBAFormProtocol { public func formItemForIdentifier(_ identifier: String) -> ORKFormItem? { return self.formItems?.find({ $0.identifier == identifier }) } } extension ORKFormStep: SBAFormProtocol { } public protocol SBAProfileInfoForm : SBAFormProtocol { var surveyItemType: SBASurveyItemType { get } func defaultOptions(_ inputItem: SBASurveyItem?) -> [SBAProfileInfoOption] } extension SBAProfileInfoForm { public var options: [SBAProfileInfoOption]? { return self.formItems?.mapAndFilter({ SBAProfileInfoOption(rawValue: $0.identifier) }) } public func formItemForProfileInfoOption(_ profileInfoOption: SBAProfileInfoOption) -> ORKFormItem? { return self.formItems?.find({ $0.identifier == profileInfoOption.rawValue }) } func commonInit(_ inputItem: SBASurveyItem?) { self.title = inputItem?.stepTitle self.text = inputItem?.stepText if let formStep = self as? ORKFormStep { formStep.footnote = inputItem?.stepFootnote } let options = SBAProfileInfoOptions(inputItem: inputItem) ?? SBAProfileInfoOptions(includes: defaultOptions(inputItem)) self.formItems = options.makeFormItems(surveyItemType: self.surveyItemType) } }
1ea61a9ffd2516c172356b59b5b44c20
42.562874
188
0.645704
false
false
false
false
edmoks/RecordBin
refs/heads/master
RecordBin/Class/Service/StoreService.swift
mit
1
// // DataService.swift // RecordBin // // Created by Eduardo Rangel on 05/10/2017. // Copyright © 2017 Eduardo Rangel. All rights reserved. // import Foundation import SwiftyJSON import Firebase class StoreService { ////////////////////////////////////////////////// // MARK: - Singleton static let instance = StoreService() private var storesReference: CollectionReference! ////////////////////////////////////////////////// // MARK: - Methods func getStores(completion: ([Store], Bool) -> Void) { var stores = [Store]() do { if let file = Bundle.main.url(forResource: "StoresIE", withExtension: "json") { let data = try Data(contentsOf: file) let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) let json = JSON(jsonObject) for (_, jsonStore):(String, JSON) in json { let store = Store.init(about: jsonStore["about"].stringValue, address: jsonStore["address"].stringValue, city: jsonStore["city"].stringValue, country: jsonStore["country"].stringValue, email: jsonStore["email"].stringValue, latitude: jsonStore["latitude"].stringValue, longitude: jsonStore["longitude"].stringValue, mobilePhone: jsonStore["mobilePhone"].stringValue, name: jsonStore["name"].stringValue, neighborhood: jsonStore["neighborhood"].stringValue, state: jsonStore["state"].stringValue, telephone: jsonStore["telephone"].stringValue, url: jsonStore["url"].stringValue, zipCode: jsonStore["zipCode"].stringValue) stores.append(store) } completion(stores, true) } else { print("no file") completion(stores, false) } } catch { print(error.localizedDescription) completion(stores, false) } } func saveStore(store: Store?, completion: (Bool) -> Void) { // do { if let safeStore = store { let storeToSave: [String : Any] = [KDatabaseStore.Model.About : safeStore.about, KDatabaseStore.Model.Address : safeStore.address, // KDatabaseStore.Model.BusinessHours : safeStore.businessHours, KDatabaseStore.Model.City : safeStore.city, KDatabaseStore.Model.Country : safeStore.country, KDatabaseStore.Model.Email : safeStore.email, KDatabaseStore.Model.Latitude : safeStore.latitude, KDatabaseStore.Model.Longitude : safeStore.longitude, KDatabaseStore.Model.MobilePhone : safeStore.mobilePhone, KDatabaseStore.Model.Name : safeStore.name, KDatabaseStore.Model.Neighborhood : safeStore.neighborhood, KDatabaseStore.Model.State : safeStore.state, KDatabaseStore.Model.Telephone : safeStore.telephone, KDatabaseStore.Model.URL : safeStore.url, KDatabaseStore.Model.ZipCode : safeStore.zipCode] // TODO - docRef = Firestore.firestore().collection("collection").document("document") OR storesReference = Firestore.firestore().collection("stores") storesReference.addDocument(data: storeToSave, completion: { (error) in if let error = error { print(">>>>> FIREBASE ERROR: \(error.localizedDescription) <<<<<") // completion(false) } else { print(">>>>> FIREBASE SUCCESS <<<<<") // completion(true) } }) } else { print("Store is nil.") completion(false) } // } catch { // print(error.localizedDescription) // completion(false) // } } }
196e561e53f4e96b7927d3ac9ffc541b
46.7
114
0.421955
false
false
false
false
douweh/RedditWallpaper
refs/heads/master
RedditWallpaper/ViewController.swift
mit
1
// // ViewController.swift // RedditWallpaper // // Created by Douwe Homans on 12/3/15. // Copyright © 2015 Douwe Homans. All rights reserved. // import UIKit import CoreData import Alamofire import AlamofireImage class ImageTableViewCell : UITableViewCell { @IBOutlet weak var myLabel: UILabel! @IBOutlet weak var wallpaperImageView: UIImageView! var wallpaper: Wallpaper? { didSet { let newValue = wallpaper self.wallpaperImageView?.image = nil wallpaper?.loadImage({ (image) -> Void in // Only update image if this cell's wallpaper didn't change in the meantime. if (self.wallpaper == newValue) { self.wallpaperImageView?.contentMode = .ScaleAspectFill self.wallpaperImageView?.image = image } }) } } } class ViewController: UIViewController, UITableViewDataSource { let ImageCellIdentifier = "ImageCellIdentifier" var dataStore = [Wallpaper]() var refreshControl:UIRefreshControl! @IBOutlet weak var tableView: UITableView! func addWallpaper(name: String){ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext // Check if we already have this url let urlPredicate = NSPredicate(format: "remoteUrl == %@", argumentArray: [name]) let fetchRequest = NSFetchRequest(entityName: "Wallpaper") fetchRequest.predicate = urlPredicate //3 do { let preExistingWallpapers = try managedContext.executeFetchRequest(fetchRequest) if (preExistingWallpapers.count > 0){ return } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } //2 let entity = NSEntityDescription.entityForName("Wallpaper", inManagedObjectContext:managedContext) let wallpaper = Wallpaper(entity: entity!, insertIntoManagedObjectContext: managedContext) //3 wallpaper.setValue(name, forKey: "remoteUrl") //4 do { try managedContext.save() //5 dataStore.append(wallpaper) } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(ImageCellIdentifier) as! ImageTableViewCell let wallpaper = dataStore[indexPath.item] cell.wallpaper = wallpaper return cell; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataStore.count } // MARK: - ViewController Lifecycle - override func viewDidLoad() { super.viewDidLoad() self.refreshControl = UIRefreshControl() self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) self.tableView.addSubview(refreshControl) fetchDataFromReddit() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) reloadDataStore() } func refresh(sender:AnyObject) { fetchDataFromReddit { self.refreshControl?.endRefreshing() } reloadDataStore() } func reloadDataStore() { //1 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext //2 let fetchRequest = NSFetchRequest(entityName: "Wallpaper") //3 do { let results = try managedContext.executeFetchRequest(fetchRequest) dataStore = results as! [Wallpaper] tableView.reloadData() } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } func fetchDataFromReddit() { // Call fetchDataFromReddit with empty callback fetchDataFromReddit {} } func fetchDataFromReddit(callback: ()->Void) { // Create GET fetch request. Alamofire.request(.GET, "https://www.reddit.com/r/wallpapers.json", parameters: ["foo": "bar"]) .responseJSON { response in // Get all 'data.children' objects (if there is JSON data) if let JSON = response.result.value, data = JSON.valueForKey("data") as? NSDictionary, children = data.valueForKey("children") as? [NSDictionary] { // In every 'child' there should be a 'data.preview.images' array let imageArrays = children.map({ (child: NSDictionary) -> [NSDictionary] in if let data = child["data"] as? NSDictionary, preview = data["preview"] as? NSDictionary, images = preview["images"] as? [NSDictionary] { return images } else { return [] } }) // Flatten imageArrays let images = imageArrays.reduce([],combine: {$0 + $1}) // Extract 'source' objects let sources = images.map{ $0["source"] } // Filter out sources smaller then 1024 let filteredSources = sources.filter{ $0?["width"] as? Int > 1024 } // Extract urls let urls = filteredSources.map{ $0?["url"] as? String} // Store wallpaperURL in dataStore urls.forEach{ if let url = $0 { self.addWallpaper(url) } } // Call the callback callback() } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showImage" { if let wallpaperVC = segue.destinationViewController as? WallpaperViewController, let originatingCell = sender as? ImageTableViewCell { wallpaperVC.wallpaper = sender?.wallpaper } } } @IBAction func unwindToViewController (sender: UIStoryboardSegue) { } }
3f2fb5f718a7b993aa322f80bb168637
31.232558
111
0.560029
false
false
false
false
apple/swift-tools-support-core
refs/heads/main
Sources/TSCBasic/Path.swift
apache-2.0
1
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ #if os(Windows) import Foundation import WinSDK #endif #if os(Windows) private typealias PathImpl = WindowsPath #else private typealias PathImpl = UNIXPath #endif import protocol Foundation.CustomNSError import var Foundation.NSLocalizedDescriptionKey /// Represents an absolute file system path, independently of what (or whether /// anything at all) exists at that path in the file system at any given time. /// An absolute path always starts with a `/` character, and holds a normalized /// string representation. This normalization is strictly syntactic, and does /// not access the file system in any way. /// /// The absolute path string is normalized by: /// - Collapsing `..` path components /// - Removing `.` path components /// - Removing any trailing path separator /// - Removing any redundant path separators /// /// This string manipulation may change the meaning of a path if any of the /// path components are symbolic links on disk. However, the file system is /// never accessed in any way when initializing an AbsolutePath. /// /// Note that `~` (home directory resolution) is *not* done as part of path /// normalization, because it is normally the responsibility of the shell and /// not the program being invoked (e.g. when invoking `cd ~`, it is the shell /// that evaluates the tilde; the `cd` command receives an absolute path). public struct AbsolutePath: Hashable, Sendable { /// Check if the given name is a valid individual path component. /// /// This only checks with regard to the semantics enforced by `AbsolutePath` /// and `RelativePath`; particular file systems may have their own /// additional requirements. static func isValidComponent(_ name: String) -> Bool { return PathImpl.isValidComponent(name) } /// Private implementation details, shared with the RelativePath struct. private let _impl: PathImpl /// Private initializer when the backing storage is known. private init(_ impl: PathImpl) { _impl = impl } /// Initializes an AbsolutePath from a string that may be either absolute /// or relative; if relative, `basePath` is used as the anchor; if absolute, /// it is used as is, and in this case `basePath` is ignored. public init(validating str: String, relativeTo basePath: AbsolutePath) throws { if PathImpl(string: str).isAbsolute { try self.init(validating: str) } else { #if os(Windows) assert(!basePath.pathString.isEmpty) guard !str.isEmpty else { self.init(basePath._impl) return } let base: UnsafePointer<Int8> = basePath.pathString.fileSystemRepresentation defer { base.deallocate() } let path: UnsafePointer<Int8> = str.fileSystemRepresentation defer { path.deallocate() } var pwszResult: PWSTR! _ = String(cString: base).withCString(encodedAs: UTF16.self) { pwszBase in String(cString: path).withCString(encodedAs: UTF16.self) { pwszPath in PathAllocCombine(pwszBase, pwszPath, ULONG(PATHCCH_ALLOW_LONG_PATHS.rawValue), &pwszResult) } } defer { LocalFree(pwszResult) } self.init(String(decodingCString: pwszResult, as: UTF16.self)) #else self.init(basePath, RelativePath(str)) #endif } } /// Initializes the AbsolutePath by concatenating a relative path to an /// existing absolute path, and renormalizing if necessary. public init(_ absPath: AbsolutePath, _ relPath: RelativePath) { self.init(absPath._impl.appending(relativePath: relPath._impl)) } /// Convenience initializer that appends a string to a relative path. public init(_ absPath: AbsolutePath, _ relStr: String) { self.init(absPath, RelativePath(relStr)) } /// Initializes the AbsolutePath from `absStr`, which must be an absolute /// path (i.e. it must begin with a path separator; this initializer does /// not interpret leading `~` characters as home directory specifiers). /// The input string will be normalized if needed, as described in the /// documentation for AbsolutePath. public init(validating path: String) throws { try self.init(PathImpl(validatingAbsolutePath: path)) } /// Directory component. An absolute path always has a non-empty directory /// component (the directory component of the root path is the root itself). public var dirname: String { return _impl.dirname } /// Last path component (including the suffix, if any). it is never empty. public var basename: String { return _impl.basename } /// Returns the basename without the extension. public var basenameWithoutExt: String { if let ext = self.extension { return String(basename.dropLast(ext.count + 1)) } return basename } /// Suffix (including leading `.` character) if any. Note that a basename /// that starts with a `.` character is not considered a suffix, nor is a /// trailing `.` character. public var suffix: String? { return _impl.suffix } /// Extension of the give path's basename. This follow same rules as /// suffix except that it doesn't include leading `.` character. public var `extension`: String? { return _impl.extension } /// Absolute path of parent directory. This always returns a path, because /// every directory has a parent (the parent directory of the root directory /// is considered to be the root directory itself). public var parentDirectory: AbsolutePath { return AbsolutePath(_impl.parentDirectory) } /// True if the path is the root directory. public var isRoot: Bool { return _impl.isRoot } /// Returns the absolute path with the relative path applied. public func appending(_ subpath: RelativePath) -> AbsolutePath { return AbsolutePath(self, subpath) } /// Returns the absolute path with an additional literal component appended. /// /// This method accepts pseudo-path like '.' or '..', but should not contain "/". public func appending(component: String) -> AbsolutePath { return AbsolutePath(_impl.appending(component: component)) } /// Returns the absolute path with additional literal components appended. /// /// This method should only be used in cases where the input is guaranteed /// to be a valid path component (i.e., it cannot be empty, contain a path /// separator, or be a pseudo-path like '.' or '..'). public func appending(components names: [String]) -> AbsolutePath { // FIXME: This doesn't seem a particularly efficient way to do this. return names.reduce(self, { path, name in path.appending(component: name) }) } public func appending(components names: String...) -> AbsolutePath { appending(components: names) } /// NOTE: We will most likely want to add other `appending()` methods, such /// as `appending(suffix:)`, and also perhaps `replacing()` methods, /// such as `replacing(suffix:)` or `replacing(basename:)` for some /// of the more common path operations. /// NOTE: We may want to consider adding operators such as `+` for appending /// a path component. /// NOTE: We will want to add a method to return the lowest common ancestor /// path. /// Root directory (whose string representation is just a path separator). public static let root = AbsolutePath(PathImpl.root) /// Normalized string representation (the normalization rules are described /// in the documentation of the initializer). This string is never empty. public var pathString: String { return _impl.string } /// Returns an array of strings that make up the path components of the /// absolute path. This is the same sequence of strings as the basenames /// of each successive path component, starting from the root. Therefore /// the first path component of an absolute path is always `/`. public var components: [String] { return _impl.components } } /// Represents a relative file system path. A relative path never starts with /// a `/` character, and holds a normalized string representation. As with /// AbsolutePath, the normalization is strictly syntactic, and does not access /// the file system in any way. /// /// The relative path string is normalized by: /// - Collapsing `..` path components that aren't at the beginning /// - Removing extraneous `.` path components /// - Removing any trailing path separator /// - Removing any redundant path separators /// - Replacing a completely empty path with a `.` /// /// This string manipulation may change the meaning of a path if any of the /// path components are symbolic links on disk. However, the file system is /// never accessed in any way when initializing a RelativePath. public struct RelativePath: Hashable, Sendable { /// Private implementation details, shared with the AbsolutePath struct. fileprivate let _impl: PathImpl /// Private initializer when the backing storage is known. private init(_ impl: PathImpl) { _impl = impl } /// Private initializer for constructing a relative path without performing /// normalization or canonicalization. This will construct a path without /// an anchor and thus may be invalid. fileprivate init(unsafeUncheckedPath string: String) { self.init(PathImpl(string: string)) } /// Initializes the RelativePath from `str`, which must be a relative path /// (which means that it must not begin with a path separator or a tilde). /// An empty input path is allowed, but will be normalized to a single `.` /// character. The input string will be normalized if needed, as described /// in the documentation for RelativePath. public init(_ string: String) { // Normalize the relative string and store it as our Path. self.init(PathImpl(normalizingRelativePath: string)) } /// Convenience initializer that verifies that the path is relative. public init(validating path: String) throws { try self.init(PathImpl(validatingRelativePath: path)) } /// Directory component. For a relative path without any path separators, /// this is the `.` string instead of the empty string. public var dirname: String { return _impl.dirname } /// Last path component (including the suffix, if any). It is never empty. public var basename: String { return _impl.basename } /// Returns the basename without the extension. public var basenameWithoutExt: String { if let ext = self.extension { return String(basename.dropLast(ext.count + 1)) } return basename } /// Suffix (including leading `.` character) if any. Note that a basename /// that starts with a `.` character is not considered a suffix, nor is a /// trailing `.` character. public var suffix: String? { return _impl.suffix } /// Extension of the give path's basename. This follow same rules as /// suffix except that it doesn't include leading `.` character. public var `extension`: String? { return _impl.extension } /// Normalized string representation (the normalization rules are described /// in the documentation of the initializer). This string is never empty. public var pathString: String { return _impl.string } /// Returns an array of strings that make up the path components of the /// relative path. This is the same sequence of strings as the basenames /// of each successive path component. Therefore the returned array of /// path components is never empty; even an empty path has a single path /// component: the `.` string. public var components: [String] { return _impl.components } /// Returns the relative path with the given relative path applied. public func appending(_ subpath: RelativePath) -> RelativePath { return RelativePath(_impl.appending(relativePath: subpath._impl)) } /// Returns the relative path with an additional literal component appended. /// /// This method accepts pseudo-path like '.' or '..', but should not contain "/". public func appending(component: String) -> RelativePath { return RelativePath(_impl.appending(component: component)) } /// Returns the relative path with additional literal components appended. /// /// This method should only be used in cases where the input is guaranteed /// to be a valid path component (i.e., it cannot be empty, contain a path /// separator, or be a pseudo-path like '.' or '..'). public func appending(components names: [String]) -> RelativePath { // FIXME: This doesn't seem a particularly efficient way to do this. return names.reduce(self, { path, name in path.appending(component: name) }) } public func appending(components names: String...) -> RelativePath { appending(components: names) } } extension AbsolutePath: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(pathString) } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() try self.init(validating: container.decode(String.self)) } } extension RelativePath: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(pathString) } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() try self.init(validating: container.decode(String.self)) } } // Make absolute paths Comparable. extension AbsolutePath: Comparable { public static func < (lhs: AbsolutePath, rhs: AbsolutePath) -> Bool { return lhs.pathString < rhs.pathString } } /// Make absolute paths CustomStringConvertible and CustomDebugStringConvertible. extension AbsolutePath: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return pathString } public var debugDescription: String { // FIXME: We should really be escaping backslashes and quotes here. return "<AbsolutePath:\"\(pathString)\">" } } /// Make relative paths CustomStringConvertible and CustomDebugStringConvertible. extension RelativePath: CustomStringConvertible { public var description: String { return _impl.string } public var debugDescription: String { // FIXME: We should really be escaping backslashes and quotes here. return "<RelativePath:\"\(_impl.string)\">" } } /// Private implementation shared between AbsolutePath and RelativePath. protocol Path: Hashable { /// Root directory. static var root: Self { get } /// Checks if a string is a valid component. static func isValidComponent(_ name: String) -> Bool /// Normalized string of the (absolute or relative) path. Never empty. var string: String { get } /// Returns whether the path is the root path. var isRoot: Bool { get } /// Returns whether the path is an absolute path. var isAbsolute: Bool { get } /// Returns the directory part of the stored path (relying on the fact that it has been normalized). Returns a /// string consisting of just `.` if there is no directory part (which is the case if and only if there is no path /// separator). var dirname: String { get } /// Returns the last past component. var basename: String { get } /// Returns the components of the path between each path separator. var components: [String] { get } /// Path of parent directory. This always returns a path, because every directory has a parent (the parent /// directory of the root directory is considered to be the root directory itself). var parentDirectory: Self { get } /// Creates a path from its normalized string representation. init(string: String) /// Creates a path from an absolute string representation and normalizes it. init(normalizingAbsolutePath: String) /// Creates a path from an relative string representation and normalizes it. init(normalizingRelativePath: String) /// Creates a path from a string representation, validates that it is a valid absolute path and normalizes it. init(validatingAbsolutePath: String) throws /// Creates a path from a string representation, validates that it is a valid relative path and normalizes it. init(validatingRelativePath: String) throws /// Returns suffix with leading `.` if withDot is true otherwise without it. func suffix(withDot: Bool) -> String? /// Returns a new Path by appending the path component. func appending(component: String) -> Self /// Returns a path by concatenating a relative path and renormalizing if necessary. func appending(relativePath: Self) -> Self } extension Path { var suffix: String? { return suffix(withDot: true) } var `extension`: String? { return suffix(withDot: false) } } #if os(Windows) private struct WindowsPath: Path, Sendable { let string: String // NOTE: this is *NOT* a root path. It is a drive-relative path that needs // to be specified due to assumptions in the APIs. Use the platform // specific path separator as we should be normalizing the path normally. // This is required to make the `InMemoryFileSystem` correctly iterate // paths. static let root = Self(string: "\\") static func isValidComponent(_ name: String) -> Bool { return name != "" && name != "." && name != ".." && !name.contains("/") } static func isAbsolutePath(_ path: String) -> Bool { return !path.withCString(encodedAs: UTF16.self, PathIsRelativeW) } var dirname: String { let fsr: UnsafePointer<Int8> = self.string.fileSystemRepresentation defer { fsr.deallocate() } let path: String = String(cString: fsr) return path.withCString(encodedAs: UTF16.self) { let data = UnsafeMutablePointer(mutating: $0) PathCchRemoveFileSpec(data, path.count) return String(decodingCString: data, as: UTF16.self) } } var isAbsolute: Bool { return Self.isAbsolutePath(self.string) } public var isRoot: Bool { return self.string.withCString(encodedAs: UTF16.self, PathCchIsRoot) } var basename: String { let path: String = self.string return path.withCString(encodedAs: UTF16.self) { PathStripPathW(UnsafeMutablePointer(mutating: $0)) return String(decodingCString: $0, as: UTF16.self) } } // FIXME: We should investigate if it would be more efficient to instead // return a path component iterator that does all its work lazily, moving // from one path separator to the next on-demand. // var components: [String] { let normalized: UnsafePointer<Int8> = string.fileSystemRepresentation defer { normalized.deallocate() } return String(cString: normalized).components(separatedBy: "\\").filter { !$0.isEmpty } } var parentDirectory: Self { return self == .root ? self : Self(string: dirname) } init(string: String) { self.string = string } init(normalizingAbsolutePath path: String) { let normalized: UnsafePointer<Int8> = path.fileSystemRepresentation defer { normalized.deallocate() } self.init(string: String(cString: normalized) .withCString(encodedAs: UTF16.self) { pwszPath in var canonical: PWSTR! _ = PathAllocCanonicalize(pwszPath, ULONG(PATHCCH_ALLOW_LONG_PATHS.rawValue), &canonical) return String(decodingCString: canonical, as: UTF16.self) }) } init(normalizingRelativePath path: String) { if path.isEmpty || path == "." { self.init(string: ".") } else { var buffer: [WCHAR] = Array<WCHAR>(repeating: 0, count: Int(MAX_PATH + 1)) _ = path.replacingOccurrences(of: "/", with: "\\").withCString(encodedAs: UTF16.self) { PathCanonicalizeW(&buffer, $0) } self.init(string: String(decodingCString: buffer, as: UTF16.self)) } } init(validatingAbsolutePath path: String) throws { let fsr: UnsafePointer<Int8> = path.fileSystemRepresentation defer { fsr.deallocate() } let realpath = String(cString: fsr) if !Self.isAbsolutePath(realpath) { throw PathValidationError.invalidAbsolutePath(path) } self.init(normalizingAbsolutePath: path) } init(validatingRelativePath path: String) throws { let fsr: UnsafePointer<Int8> = path.fileSystemRepresentation defer { fsr.deallocate() } let realpath: String = String(cString: fsr) // Treat a relative path as an invalid relative path... if Self.isAbsolutePath(realpath) || realpath.first == "~" || realpath.first == "\\" { throw PathValidationError.invalidRelativePath(path) } self.init(normalizingRelativePath: path) } func suffix(withDot: Bool) -> String? { return self.string.withCString(encodedAs: UTF16.self) { if let pointer = PathFindExtensionW($0) { let substring = String(decodingCString: pointer, as: UTF16.self) guard substring.length > 0 else { return nil } return withDot ? substring : String(substring.dropFirst(1)) } return nil } } func appending(component name: String) -> Self { var result: PWSTR? _ = string.withCString(encodedAs: UTF16.self) { root in name.withCString(encodedAs: UTF16.self) { path in PathAllocCombine(root, path, ULONG(PATHCCH_ALLOW_LONG_PATHS.rawValue), &result) } } defer { LocalFree(result) } return PathImpl(string: String(decodingCString: result!, as: UTF16.self)) } func appending(relativePath: Self) -> Self { var result: PWSTR? _ = string.withCString(encodedAs: UTF16.self) { root in relativePath.string.withCString(encodedAs: UTF16.self) { path in PathAllocCombine(root, path, ULONG(PATHCCH_ALLOW_LONG_PATHS.rawValue), &result) } } defer { LocalFree(result) } return PathImpl(string: String(decodingCString: result!, as: UTF16.self)) } } #else private struct UNIXPath: Path, Sendable { let string: String static let root = Self(string: "/") static func isValidComponent(_ name: String) -> Bool { return name != "" && name != "." && name != ".." && !name.contains("/") } var dirname: String { // FIXME: This method seems too complicated; it should be simplified, // if possible, and certainly optimized (using UTF8View). // Find the last path separator. guard let idx = string.lastIndex(of: "/") else { // No path separators, so the directory name is `.`. return "." } // Check if it's the only one in the string. if idx == string.startIndex { // Just one path separator, so the directory name is `/`. return "/" } // Otherwise, it's the string up to (but not including) the last path // separator. return String(string.prefix(upTo: idx)) } var isAbsolute: Bool { return string.hasPrefix("/") } var isRoot: Bool { return self == Self.root } var basename: String { // FIXME: This method seems too complicated; it should be simplified, // if possible, and certainly optimized (using UTF8View). // Check for a special case of the root directory. if string.spm_only == "/" { // Root directory, so the basename is a single path separator (the // root directory is special in this regard). return "/" } // Find the last path separator. guard let idx = string.lastIndex(of: "/") else { // No path separators, so the basename is the whole string. return string } // Otherwise, it's the string from (but not including) the last path // separator. return String(string.suffix(from: string.index(after: idx))) } // FIXME: We should investigate if it would be more efficient to instead // return a path component iterator that does all its work lazily, moving // from one path separator to the next on-demand. // var components: [String] { // FIXME: This isn't particularly efficient; needs optimization, and // in fact, it might well be best to return a custom iterator so we // don't have to allocate everything up-front. It would be backed by // the path string and just return a slice at a time. let components = string.components(separatedBy: "/").filter({ !$0.isEmpty }) if string.hasPrefix("/") { return ["/"] + components } else { return components } } var parentDirectory: Self { return self == .root ? self : Self(string: dirname) } init(string: String) { self.string = string } init(normalizingAbsolutePath path: String) { precondition(path.first == "/", "Failure normalizing \(path), absolute paths should start with '/'") // At this point we expect to have a path separator as first character. assert(path.first == "/") // Fast path. if !mayNeedNormalization(absolute: path) { self.init(string: path) } // Split the character array into parts, folding components as we go. // As we do so, we count the number of characters we'll end up with in // the normalized string representation. var parts: [String] = [] var capacity = 0 for part in path.split(separator: "/") { switch part.count { case 0: // Ignore empty path components. continue case 1 where part.first == ".": // Ignore `.` path components. continue case 2 where part.first == "." && part.last == ".": // If there's a previous part, drop it; otherwise, do nothing. if let prev = parts.last { parts.removeLast() capacity -= prev.count } default: // Any other component gets appended. parts.append(String(part)) capacity += part.count } } capacity += max(parts.count, 1) // Create an output buffer using the capacity we've calculated. // FIXME: Determine the most efficient way to reassemble a string. var result = "" result.reserveCapacity(capacity) // Put the normalized parts back together again. var iter = parts.makeIterator() result.append("/") if let first = iter.next() { result.append(contentsOf: first) while let next = iter.next() { result.append("/") result.append(contentsOf: next) } } // Sanity-check the result (including the capacity we reserved). assert(!result.isEmpty, "unexpected empty string") assert(result.count == capacity, "count: " + "\(result.count), cap: \(capacity)") // Use the result as our stored string. self.init(string: result) } init(normalizingRelativePath path: String) { precondition(path.first != "/") // FIXME: Here we should also keep track of whether anything actually has // to be changed in the string, and if not, just return the existing one. // Split the character array into parts, folding components as we go. // As we do so, we count the number of characters we'll end up with in // the normalized string representation. var parts: [String] = [] var capacity = 0 for part in path.split(separator: "/") { switch part.count { case 0: // Ignore empty path components. continue case 1 where part.first == ".": // Ignore `.` path components. continue case 2 where part.first == "." && part.last == ".": // If at beginning, fall through to treat the `..` literally. guard let prev = parts.last else { fallthrough } // If previous component is anything other than `..`, drop it. if !(prev.count == 2 && prev.first == "." && prev.last == ".") { parts.removeLast() capacity -= prev.count continue } // Otherwise, fall through to treat the `..` literally. fallthrough default: // Any other component gets appended. parts.append(String(part)) capacity += part.count } } capacity += max(parts.count - 1, 0) // Create an output buffer using the capacity we've calculated. // FIXME: Determine the most efficient way to reassemble a string. var result = "" result.reserveCapacity(capacity) // Put the normalized parts back together again. var iter = parts.makeIterator() if let first = iter.next() { result.append(contentsOf: first) while let next = iter.next() { result.append("/") result.append(contentsOf: next) } } // Sanity-check the result (including the capacity we reserved). assert(result.count == capacity, "count: " + "\(result.count), cap: \(capacity)") // If the result is empty, return `.`, otherwise we return it as a string. self.init(string: result.isEmpty ? "." : result) } init(validatingAbsolutePath path: String) throws { switch path.first { case "/": self.init(normalizingAbsolutePath: path) case "~": throw PathValidationError.startsWithTilde(path) default: throw PathValidationError.invalidAbsolutePath(path) } } init(validatingRelativePath path: String) throws { switch path.first { case "/", "~": throw PathValidationError.invalidRelativePath(path) default: self.init(normalizingRelativePath: path) } } func suffix(withDot: Bool) -> String? { // FIXME: This method seems too complicated; it should be simplified, // if possible, and certainly optimized (using UTF8View). // Find the last path separator, if any. let sIdx = string.lastIndex(of: "/") // Find the start of the basename. let bIdx = (sIdx != nil) ? string.index(after: sIdx!) : string.startIndex // Find the last `.` (if any), starting from the second character of // the basename (a leading `.` does not make the whole path component // a suffix). let fIdx = string.index(bIdx, offsetBy: 1, limitedBy: string.endIndex) ?? string.startIndex if let idx = string[fIdx...].lastIndex(of: ".") { // Unless it's just a `.` at the end, we have found a suffix. if string.distance(from: idx, to: string.endIndex) > 1 { let fromIndex = withDot ? idx : string.index(idx, offsetBy: 1) return String(string.suffix(from: fromIndex)) } else { return nil } } // If we get this far, there is no suffix. return nil } func appending(component name: String) -> Self { assert(!name.contains("/"), "\(name) is invalid path component") // Handle pseudo paths. switch name { case "", ".": return self case "..": return self.parentDirectory default: break } if self == Self.root { return PathImpl(string: "/" + name) } else { return PathImpl(string: string + "/" + name) } } func appending(relativePath: Self) -> Self { // Both paths are already normalized. The only case in which we have // to renormalize their concatenation is if the relative path starts // with a `..` path component. var newPathString = string if self != .root { newPathString.append("/") } let relativePathString = relativePath.string newPathString.append(relativePathString) // If the relative string starts with `.` or `..`, we need to normalize // the resulting string. // FIXME: We can actually optimize that case, since we know that the // normalization of a relative path can leave `..` path components at // the beginning of the path only. if relativePathString.hasPrefix(".") { if newPathString.hasPrefix("/") { return PathImpl(normalizingAbsolutePath: newPathString) } else { return PathImpl(normalizingRelativePath: newPathString) } } else { return PathImpl(string: newPathString) } } } #endif /// Describes the way in which a path is invalid. public enum PathValidationError: Error { case startsWithTilde(String) case invalidAbsolutePath(String) case invalidRelativePath(String) } extension PathValidationError: CustomStringConvertible { public var description: String { switch self { case .startsWithTilde(let path): return "invalid absolute path '\(path)'; absolute path must begin with '/'" case .invalidAbsolutePath(let path): return "invalid absolute path '\(path)'" case .invalidRelativePath(let path): return "invalid relative path '\(path)'; relative path should not begin with '\(AbsolutePath.root.pathString)' or '~'" } } } extension AbsolutePath { /// Returns a relative path that, when concatenated to `base`, yields the /// callee path itself. If `base` is not an ancestor of the callee, the /// returned path will begin with one or more `..` path components. /// /// Because both paths are absolute, they always have a common ancestor /// (the root path, if nothing else). Therefore, any path can be made /// relative to any other path by using a sufficient number of `..` path /// components. /// /// This method is strictly syntactic and does not access the file system /// in any way. Therefore, it does not take symbolic links into account. public func relative(to base: AbsolutePath) -> RelativePath { let result: RelativePath // Split the two paths into their components. // FIXME: The is needs to be optimized to avoid unncessary copying. let pathComps = self.components let baseComps = base.components // It's common for the base to be an ancestor, so try that first. if pathComps.starts(with: baseComps) { // Special case, which is a plain path without `..` components. It // might be an empty path (when self and the base are equal). let relComps = pathComps.dropFirst(baseComps.count) #if os(Windows) result = RelativePath(unsafeUncheckedPath: relComps.joined(separator: "\\")) #else result = RelativePath(relComps.joined(separator: "/")) #endif } else { // General case, in which we might well need `..` components to go // "up" before we can go "down" the directory tree. var newPathComps = ArraySlice(pathComps) var newBaseComps = ArraySlice(baseComps) while newPathComps.prefix(1) == newBaseComps.prefix(1) { // First component matches, so drop it. newPathComps = newPathComps.dropFirst() newBaseComps = newBaseComps.dropFirst() } // Now construct a path consisting of as many `..`s as are in the // `newBaseComps` followed by what remains in `newPathComps`. var relComps = Array(repeating: "..", count: newBaseComps.count) relComps.append(contentsOf: newPathComps) #if os(Windows) result = RelativePath(unsafeUncheckedPath: relComps.joined(separator: "\\")) #else result = RelativePath(relComps.joined(separator: "/")) #endif } assert(AbsolutePath(base, result) == self) return result } /// Returns true if the path contains the given path. /// /// This method is strictly syntactic and does not access the file system /// in any way. @available(*, deprecated, renamed: "isDescendantOfOrEqual(to:)") public func contains(_ other: AbsolutePath) -> Bool { return isDescendantOfOrEqual(to: other) } /// Returns true if the path is an ancestor of the given path. /// /// This method is strictly syntactic and does not access the file system /// in any way. public func isAncestor(of descendant: AbsolutePath) -> Bool { return descendant.components.dropLast().starts(with: self.components) } /// Returns true if the path is an ancestor of or equal to the given path. /// /// This method is strictly syntactic and does not access the file system /// in any way. public func isAncestorOfOrEqual(to descendant: AbsolutePath) -> Bool { return descendant.components.starts(with: self.components) } /// Returns true if the path is a descendant of the given path. /// /// This method is strictly syntactic and does not access the file system /// in any way. public func isDescendant(of ancestor: AbsolutePath) -> Bool { return self.components.dropLast().starts(with: ancestor.components) } /// Returns true if the path is a descendant of or equal to the given path. /// /// This method is strictly syntactic and does not access the file system /// in any way. public func isDescendantOfOrEqual(to ancestor: AbsolutePath) -> Bool { return self.components.starts(with: ancestor.components) } } extension PathValidationError: CustomNSError { public var errorUserInfo: [String : Any] { return [NSLocalizedDescriptionKey: self.description] } } // FIXME: We should consider whether to merge the two `normalize()` functions. // The argument for doing so is that some of the code is repeated; the argument // against doing so is that some of the details are different, and since any // given path is either absolute or relative, it's wasteful to keep checking // for whether it's relative or absolute. Possibly we can do both by clever // use of generics that abstract away the differences. /// Fast check for if a string might need normalization. /// /// This assumes that paths containing dotfiles are rare: private func mayNeedNormalization(absolute string: String) -> Bool { var last = UInt8(ascii: "0") for c in string.utf8 { switch c { case UInt8(ascii: "/") where last == UInt8(ascii: "/"): return true case UInt8(ascii: ".") where last == UInt8(ascii: "/"): return true default: break } last = c } if last == UInt8(ascii: "/") { return true } return false } // MARK: - `AbsolutePath` backwards compatibility, delete after deprecation period. extension AbsolutePath { @available(*, deprecated, message: "use throwing variant instead") public init(_ absStr: String) { try! self.init(validating: absStr) } @available(*, deprecated, message: "use throwing variant instead") public init(_ str: String, relativeTo basePath: AbsolutePath) { try! self.init(validating: str, relativeTo: basePath) } }
9ea293e4797e75a83a8cfdc941a379e6
37.375465
130
0.63189
false
false
false
false
gkaimakas/ReactiveBluetooth
refs/heads/master
ReactiveBluetooth/Classes/CBCharacteristic/CBCharacteristic+Reactive.swift
mit
1
// // CBCharacteristic+Reactive.swift // ReactiveBluetooth // // Created by George Kaimakas on 04/03/2018. // import CoreBluetooth import Foundation import ReactiveCocoa import ReactiveSwift import Result extension Reactive where Base: CBCharacteristic { /// The value of the characteristic. public var value: Property<Data?> { get { guard let value = objc_getAssociatedObject(base, &CBCharacteristic.Associations.value) as? Property<Data?> else { let value = Property<Data?>(initial: base.value, then: producer(forKeyPath: #keyPath(CBCharacteristic.value)) .map { $0 as? Data } ) objc_setAssociatedObject(base, &CBCharacteristic.Associations.value, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return value } return value } } /// A list of the descriptors that have been discovered in this characteristic. public var descriptors: Property<Set<CBDescriptor>> { guard let descriptors = objc_getAssociatedObject(base, &CBCharacteristic.Associations.descriptors) as? Property<Set<CBDescriptor>> else { let descriptors = Property(initial: Set(), then: producer(forKeyPath: #keyPath(CBCharacteristic.descriptors)) .filterMap { $0 as? [CBDescriptor] } .map { Set($0) }) objc_setAssociatedObject(base, &CBCharacteristic.Associations.descriptors, descriptors, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return descriptors } return descriptors } /// The properties of the characteristic. public var properties: Property<CBCharacteristicProperties> { get { guard let properties = objc_getAssociatedObject(base, CBCharacteristic.Associations.properties) as? Property<CBCharacteristicProperties> else { let properties = Property<CBCharacteristicProperties>(value: base.properties) objc_setAssociatedObject(base, &CBCharacteristic.Associations.properties, properties, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return properties } return properties } } /// The properties of the characteristic. public var isNotifying: Property<Bool> { get { guard let isNotifying = objc_getAssociatedObject(base, CBCharacteristic.Associations.isNotifying) as? Property<Bool> else { let isNotifying = Property<Bool>(initial: base.isNotifying, then: producer(forKeyPath: #keyPath(CBCharacteristic.isNotifying)) .filterMap { $0 as? Bool } ) objc_setAssociatedObject(base, &CBCharacteristic.Associations.isNotifying, isNotifying, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return isNotifying } return isNotifying } } /// Retrieves the value of a specified characteristic. public func readValue() -> SignalProducer<CBCharacteristic, NSError> { return base .service .peripheral .reactive .readValue(for: base) } /// Writes the value of a characteristic. public func writeValue(_ data: Data, type: CBCharacteristicWriteType) -> SignalProducer<CBCharacteristic, NSError> { return base .service .peripheral .reactive .writeValue(data, for: base, type: type) } /// Sets notifications or indications for the value of a specified characteristic. public func setNotifyValue(_ enabled: Bool) -> SignalProducer<CBCharacteristic, NSError> { return base .service .peripheral .reactive .setNotifyValue(enabled, for: base) } } extension Reactive where Base: CBCharacteristic { public var didUpdateNotificationState: Signal<(isNotifying: Bool, error: Error?), NoError> { return base .service .peripheral .reactive .didUpdateNotificationState .filter { $0.characteristic == self.base } .map { (isNotifying: $0.characteristic.isNotifying, error: $0.error) } } public var didWriteValue: Signal<(characteristic: CBCharacteristic, error: Error?), NoError> { return base .service .peripheral .reactive .didUpdateValueForCharacteristic .filter { $0.characteristic == self.base } } public var didUpdateValue: Signal<(value: Data?, error: Error?), NoError> { return base .service .peripheral .reactive .didUpdateValueForCharacteristic .filter { $0.characteristic == self.base } .map { (value: $0.characteristic.value, error: $0.error) } } }
910a3564d3c426ca0acecf86c7309d84
32.846154
155
0.547378
false
false
false
false
ccrama/Slide-iOS
refs/heads/master
Slide for Reddit/Onboarding2/OnboardingPageViewController+Pages.swift
apache-2.0
1
// // OnboardingPageViewController+Pages.swift // Slide for Reddit // // Created by Jonathan Cole on 9/15/20. // Copyright © 2020 Haptic Apps. All rights reserved. // import Anchorage import AVKit import reddift import Then import UIKit /** ViewController for a single page in the OnboardingPageViewController. Describes a splash screen with animated background. */ class OnboardingSplashPageViewController: UIViewController { let text: String let subText: String let image: UIImage var textView = UILabel() var subTextView = UILabel() var imageView = UIImageView() var baseView = UIView() var shouldMove = true var gradientSet = false let bubbles = UIScreen.main.bounds.height / 30 var lanes = [Int](repeating: 0, count: Int(UIScreen.main.bounds.height / 30)) init(text: String, subText: String, image: UIImage) { self.text = text self.subText = subText self.image = image super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() self.setupViews() self.setupConstriants() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.setupMovingViews() self.view.clipsToBounds = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIView.animate(withDuration: 1) { self.baseView.alpha = 0 } completion: { (_) in self.stopMoving() } } func stopMoving() { shouldMove = false } func setupMovingViews() { gradientSet = false baseView.removeFromSuperview() baseView = UIView() view.addSubview(baseView) baseView.centerAnchors == self.view.centerAnchors baseView.widthAnchor == CGFloat(bubbles) * 30 baseView.heightAnchor == CGFloat(bubbles) * 30 for i in 0..<Int(bubbles) { if i % 2 == 0 { self.lanes[i] = 2 continue } let movingView = PreviewSubredditView(frame: CGRect.zero) baseView.addSubview(movingView) movingView.setFrame(getInitialFrame(for: movingView, in: i)) movingView.alpha = 0 movingView.tag = i self.lanes[i] += 1 DispatchQueue.main.asyncAfter(deadline: .now() + Double(Int.random(in: 0...6))) { movingView.alpha = 1 self.moveView(view: movingView, chosenLane: i) } } let radians = -30 / 180.0 * CGFloat.pi baseView.transform = CGAffineTransform(rotationAngle: radians) baseView.alpha = 0.4 view.bringSubviewToFront(imageView) view.bringSubviewToFront(textView) view.bringSubviewToFront(subTextView) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if !gradientSet { gradientSet = true let gradientMaskLayer = CAGradientLayer() gradientMaskLayer.frame = self.view.bounds gradientMaskLayer.shadowRadius = 50 gradientMaskLayer.shadowPath = CGPath(roundedRect: self.view.bounds.insetBy(dx: 0, dy: 0), cornerWidth: 0, cornerHeight: 0, transform: nil) gradientMaskLayer.shadowOpacity = 1 gradientMaskLayer.shadowOffset = CGSize.zero gradientMaskLayer.shadowColor = ColorUtil.theme.foregroundColor.cgColor view.layer.mask = gradientMaskLayer } } func getInitialFrame(for view: PreviewSubredditView, in lane: Int) -> CGRect { print("Lane is \(CGRect(x: CGFloat(bubbles * 30), y: CGFloat(lane) * 30, width: 200, height: 30))") return CGRect(x: CGFloat(bubbles * 30), y: CGFloat(lane) * 30, width: 200, height: 30) } func getFinalFrame(for view: PreviewSubredditView, in lane: Int) -> CGRect { return CGRect(x: -1 * 200, y: CGFloat(lane) * 30, width: view.frame.size.width, height: 30) } func moveView(view: PreviewSubredditView, chosenLane: Int) { let time = Int.random(in: 5...10) UIView.animate(withDuration: Double(time), delay: 0, options: .curveLinear, animations: { () -> Void in view.frame = self.getFinalFrame(for: view, in: chosenLane) }, completion: { [weak self] (Bool) -> Void in guard let self = self else { return } if self.shouldMove { view.randomizeColors() self.lanes[chosenLane] -= 1 var emptyIndexes = [Int]() for i in 0..<self.lanes.count { if self.lanes[i] < 1 { emptyIndexes.append(i) } } let newLane = emptyIndexes.randomItem ?? 0 self.lanes[newLane] += 1 view.setFrame(self.getInitialFrame(for: view, in: newLane)) self.moveView(view: view, chosenLane: newLane) } else { view.removeFromSuperview() } }) } func setupViews() { let newTitle = NSMutableAttributedString(string: text.split("\n").first ?? "", attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor, NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20)]) newTitle.append(NSAttributedString(string: "\n")) newTitle.append(NSMutableAttributedString(string: text.split("\n").last ?? "", attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor, NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 30)])) self.textView = UILabel().then { $0.font = UIFont.boldSystemFont(ofSize: 30) $0.textColor = ColorUtil.theme.fontColor $0.textAlignment = .center $0.numberOfLines = 0 $0.attributedText = newTitle } self.subTextView = UILabel().then { $0.font = UIFont.systemFont(ofSize: 15) $0.textColor = ColorUtil.theme.fontColor $0.textAlignment = .center $0.text = subText } self.imageView = UIImageView(image: image).then { $0.contentMode = .scaleAspectFill $0.layer.cornerRadius = 25 $0.clipsToBounds = true } self.view.addSubviews(imageView, textView, subTextView) } func setupConstriants() { textView.horizontalAnchors == self.view.horizontalAnchors + 32 textView.bottomAnchor == self.imageView.topAnchor - 40 imageView.centerAnchors == self.view.centerAnchors imageView.widthAnchor == 100 imageView.heightAnchor == 100 subTextView.horizontalAnchors == self.view.horizontalAnchors + 32 subTextView.bottomAnchor == self.view.safeBottomAnchor - 8 } @available(*, unavailable) required init?(coder: NSCoder) { self.text = "" self.subText = "" self.image = UIImage() super.init(coder: coder) } } class PreviewSubredditView: UIView { var bubble = UIView() var label = UIView() var toSetFrame = CGRect.zero var frameSet = false override func layoutSubviews() { super.layoutSubviews() if !frameSet { frameSet = true self.frame = toSetFrame } } override init(frame: CGRect) { super.init(frame: frame) setupViews() setupConstraints() randomizeColors() self.translatesAutoresizingMaskIntoConstraints = false } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func randomizeColors() { let seed = Int.random(in: 0...100) if seed < 30 { self.bubble.backgroundColor = ColorUtil.theme.fontColor self.label.backgroundColor = ColorUtil.theme.fontColor self.label.alpha = 0.6 } else if seed < 50 { self.bubble.backgroundColor = GMColor.green500Color() self.label.backgroundColor = GMColor.green500Color() self.label.alpha = 0.6 } else if seed < 60 { self.bubble.backgroundColor = GMColor.red500Color() self.label.backgroundColor = GMColor.red500Color() self.label.alpha = 0.6 } else if seed < 70 { self.bubble.backgroundColor = GMColor.orange500Color() self.label.backgroundColor = GMColor.orange500Color() self.label.alpha = 0.6 } else if seed < 80 { self.bubble.backgroundColor = GMColor.yellow500Color() self.label.backgroundColor = GMColor.yellow500Color() self.label.alpha = 0.6 } else if seed < 90 { self.bubble.backgroundColor = GMColor.purple500Color() self.label.backgroundColor = GMColor.purple500Color() self.label.alpha = 0.6 } else { self.bubble.backgroundColor = GMColor.blue500Color() self.label.backgroundColor = GMColor.blue500Color() self.label.alpha = 0.6 } } func setFrame(_ frame: CGRect) { self.frame = frame self.toSetFrame = frame } func setupViews() { bubble = UIView().then { $0.clipsToBounds = true } } func setupConstraints() { self.addSubviews(bubble, label) let size = Int.random(in: 5...10) let scale = CGFloat(5) / CGFloat(size) bubble.widthAnchor == 30 * scale bubble.heightAnchor == 30 * scale bubble.layer.cornerRadius = 15 * scale label.widthAnchor == CGFloat(Int.random(in: 40...150)) * scale label.heightAnchor == 25 * scale label.layer.cornerRadius = 5 * scale label.clipsToBounds = true label.leftAnchor == bubble.rightAnchor + 8 * scale label.centerYAnchor == bubble.centerYAnchor } } /** ViewController for a single page in the OnboardingPageViewController. Describes a single feature with text and an image. */ class OnboardingFeaturePageViewController: UIViewController { let text: String let subText: String let image: UIImage var textView = UILabel() var subTextView = UILabel() var imageView = UIImageView() init(text: String, subText: String, image: UIImage) { self.text = text self.subText = subText self.image = image super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() self.setupViews() self.setupConstriants() } func setupViews() { self.textView = UILabel().then { $0.font = UIFont.boldSystemFont(ofSize: 20) $0.textColor = ColorUtil.theme.fontColor $0.textAlignment = .center $0.text = text } self.subTextView = UILabel().then { $0.font = UIFont.systemFont(ofSize: 15) $0.textColor = ColorUtil.theme.fontColor $0.textAlignment = .center $0.text = subText } self.imageView = UIImageView(image: image).then { $0.contentMode = .scaleAspectFill $0.layer.cornerRadius = 25 $0.clipsToBounds = true } self.view.addSubviews(imageView, textView, subTextView) } func setupConstriants() { textView.horizontalAnchors == self.view.horizontalAnchors + 16 textView.topAnchor == self.view.safeTopAnchor + 8 imageView.centerAnchors == self.view.centerAnchors imageView.widthAnchor == 100 imageView.heightAnchor == 100 subTextView.horizontalAnchors == self.view.horizontalAnchors + 16 subTextView.bottomAnchor == self.view.safeBottomAnchor - 8 } @available(*, unavailable) required init?(coder: NSCoder) { self.text = "" self.subText = "" self.image = UIImage() super.init(coder: coder) } } /** ViewController for a single page in the OnboardingPageViewController. Describes the app's latest changelog. */ class OnboardingChangelogPageViewController: UIViewController { let link: Link init(link: Link) { self.link = link super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { self.link = Link(id: "") super.init(coder: coder) } } /** ViewController for a single page in the OnboardingPageViewController. Describes the app's latest changelog as Strings. */ class OnboardingHardcodedChangelogPageViewController: UIViewController { let paragraphs: [String: String] let order: [String] let subButton = UILabel() let body = UIScrollView() let content = UILabel() var sizeSet = false init(order: [String], paragraphs: [String: String]) { self.paragraphs = paragraphs self.order = order super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { self.paragraphs = [:] self.order = [] super.init(coder: coder) } override func viewDidLoad() { super.viewDidLoad() setupViews() setupConstraints() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if !sizeSet { sizeSet = true self.content.preferredMaxLayoutWidth = self.body.frame.size.width - 16 self.content.sizeToFit() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } func setupViews() { let attributedChangelog = NSMutableAttributedString() for paragraph in order { attributedChangelog.append(NSAttributedString(string: paragraph, attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor, NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20)])) attributedChangelog.append(NSAttributedString(string: "\n")) attributedChangelog.append(NSAttributedString(string: "\n")) attributedChangelog.append(NSAttributedString(string: paragraphs[paragraph]!, attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])) attributedChangelog.append(NSAttributedString(string: "\n")) attributedChangelog.append(NSAttributedString(string: "\n")) } content.numberOfLines = 0 content.attributedText = attributedChangelog body.addSubview(content) self.view.addSubviews(body, subButton) subButton.backgroundColor = GMColor.orange500Color() subButton.textColor = .white subButton.layer.cornerRadius = 20 subButton.clipsToBounds = true subButton.textAlignment = .center subButton.font = UIFont.boldSystemFont(ofSize: 20) subButton.text = "Awesome!" } func setupConstraints() { body.horizontalAnchors == self.view.horizontalAnchors + 32 body.bottomAnchor == self.subButton.topAnchor - 4 body.topAnchor == self.view.topAnchor + 4 content.edgeAnchors == body.edgeAnchors self.subButton.bottomAnchor == self.view.bottomAnchor - 8 self.subButton.horizontalAnchors == self.view.horizontalAnchors + 8 self.subButton.alpha = 0 //Hide for now self.subButton.heightAnchor == 0 } } /** ViewController for a single page in the OnboardingPageViewController. Shows a video with a given resource name. */ class OnboardingVideoPageViewController: UIViewController { let text: String let subText: String let video: String var textView = UILabel() var subTextView = UILabel() var videoPlayer = AVPlayer() let videoContainer = UIView() let aspectRatio: Float var layer: AVPlayerLayer? var frameSet = false init(text: String, subText: String, video: String, aspectRatio: Float) { self.text = text self.subText = subText self.video = video self.aspectRatio = aspectRatio super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { self.text = "" self.subText = "" self.video = "" self.aspectRatio = 1 super.init(coder: coder) } override func viewDidLoad() { super.viewDidLoad() setupViews() setupConstraints() startVideos() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } func setupViews() { self.textView = UILabel().then { $0.font = UIFont.boldSystemFont(ofSize: 20) $0.textColor = ColorUtil.theme.fontColor $0.textAlignment = .center $0.text = text $0.numberOfLines = 0 } self.view.addSubview(textView) self.view.addSubview(videoContainer) self.subTextView = UILabel().then { $0.font = UIFont.systemFont(ofSize: 15) $0.textColor = ColorUtil.theme.fontColor $0.textAlignment = .center $0.text = subText $0.numberOfLines = 0 } self.view.addSubview(subTextView) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if !frameSet { frameSet = true layer?.frame = videoContainer.bounds } } func setupConstraints() { textView.horizontalAnchors == self.view.horizontalAnchors + 16 textView.topAnchor == self.view.safeTopAnchor + 8 videoContainer.topAnchor == textView.bottomAnchor + 32 videoContainer.bottomAnchor == self.subTextView.topAnchor - 32 videoContainer.widthAnchor == self.videoContainer.heightAnchor * aspectRatio videoContainer.centerXAnchor == self.view.centerXAnchor subTextView.bottomAnchor == self.view.safeBottomAnchor - 8 subTextView.horizontalAnchors == self.view.horizontalAnchors + 16 } func startVideos() { let bundle = Bundle.main if let videoPath = bundle.path(forResource: video, ofType: "mp4") { videoPlayer = AVPlayer(url: URL(fileURLWithPath: videoPath)) layer = AVPlayerLayer(player: videoPlayer) layer!.needsDisplayOnBoundsChange = true layer!.videoGravity = .resizeAspect layer!.cornerRadius = 20 layer!.masksToBounds = true videoContainer.layer.addSublayer(layer!) videoContainer.clipsToBounds = true videoContainer.layer.masksToBounds = true videoContainer.layer.cornerRadius = 20 videoPlayer.play() videoPlayer.actionAtItemEnd = .none NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd(notification:)), name: .AVPlayerItemDidPlayToEndTime, object: videoPlayer.currentItem) } } deinit { NotificationCenter.default.removeObserver(self) } @objc func playerItemDidReachEnd(notification: Notification) { if let playerItem = notification.object as? AVPlayerItem { playerItem.seek(to: CMTime.zero, completionHandler: nil) } } }
4c5d25dcbf368e3a42c6187ba444d8ed
31.700491
232
0.602302
false
false
false
false
Elm-Tree-Island/Shower
refs/heads/master
Carthage/Checkouts/ReactiveCocoa/Carthage/Checkouts/ReactiveSwift/Tests/ReactiveSwiftTests/UnidirectionalBindingSpec.swift
gpl-3.0
4
import Dispatch import Result import Nimble import Quick @testable import ReactiveSwift private class Object { var value: Int = 0 } class UnidirectionalBindingSpec: QuickSpec { override func spec() { describe("BindingTarget") { var token: Lifetime.Token! var lifetime: Lifetime! beforeEach { token = Lifetime.Token() lifetime = Lifetime(token) } describe("closure binding target") { var target: BindingTarget<Int>! var optionalTarget: BindingTarget<Int?>! var value: Int? beforeEach { target = BindingTarget(lifetime: lifetime, action: { value = $0 }) optionalTarget = BindingTarget(lifetime: lifetime, action: { value = $0 }) value = nil } describe("non-optional target") { it("should pass through the lifetime") { expect(target.lifetime).to(beIdenticalTo(lifetime)) } it("should trigger the supplied setter") { expect(value).to(beNil()) target.action(1) expect(value) == 1 } it("should accept bindings from properties") { expect(value).to(beNil()) let property = MutableProperty(1) target <~ property expect(value) == 1 property.value = 2 expect(value) == 2 } } describe("optional target") { it("should pass through the lifetime") { expect(optionalTarget.lifetime).to(beIdenticalTo(lifetime)) } it("should trigger the supplied setter") { expect(value).to(beNil()) optionalTarget.action(1) expect(value) == 1 } it("should accept bindings from properties") { expect(value).to(beNil()) let property = MutableProperty(1) optionalTarget <~ property expect(value) == 1 property.value = 2 expect(value) == 2 } } } describe("key path binding target") { var target: BindingTarget<Int>! var object: Object! beforeEach { object = Object() target = BindingTarget(lifetime: lifetime, object: object, keyPath: \.value) } it("should pass through the lifetime") { expect(target.lifetime).to(beIdenticalTo(lifetime)) } it("should trigger the supplied setter") { expect(object.value) == 0 target.action(1) expect(object.value) == 1 } it("should accept bindings from properties") { expect(object.value) == 0 let property = MutableProperty(1) target <~ property expect(object.value) == 1 property.value = 2 expect(object.value) == 2 } } it("should not deadlock on the same queue") { var value: Int? let target = BindingTarget(on: UIScheduler(), lifetime: lifetime, action: { value = $0 }) let property = MutableProperty(1) target <~ property expect(value) == 1 } it("should not deadlock on the main thread even if the context was switched to a different queue") { var value: Int? let queue = DispatchQueue(label: #file) let target = BindingTarget(on: UIScheduler(), lifetime: lifetime, action: { value = $0 }) let property = MutableProperty(1) queue.sync { _ = target <~ property } expect(value).toEventually(equal(1)) } it("should not deadlock even if the value is originated from the same queue indirectly") { var value: Int? let key = DispatchSpecificKey<Void>() DispatchQueue.main.setSpecific(key: key, value: ()) let mainQueueCounter = Atomic(0) let setter: (Int) -> Void = { value = $0 mainQueueCounter.modify { $0 += DispatchQueue.getSpecific(key: key) != nil ? 1 : 0 } } let target = BindingTarget(on: UIScheduler(), lifetime: lifetime, action: setter) let scheduler: QueueScheduler if #available(OSX 10.10, *) { scheduler = QueueScheduler() } else { scheduler = QueueScheduler(queue: DispatchQueue(label: "com.reactivecocoa.ReactiveSwift.UnidirectionalBindingSpec")) } let property = MutableProperty(1) target <~ property.producer .start(on: scheduler) .observe(on: scheduler) expect(value).toEventually(equal(1)) expect(mainQueueCounter.value).toEventually(equal(1)) property.value = 2 expect(value).toEventually(equal(2)) expect(mainQueueCounter.value).toEventually(equal(2)) } } } }
9b1798e3e562889c907e1edddf2455db
23.31694
121
0.61236
false
false
false
false
JaSpa/swift
refs/heads/master
stdlib/public/SDK/CryptoTokenKit/TKSmartCard.swift
apache-2.0
25
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import CryptoTokenKit import Foundation @available(OSX 10.10, *) extension TKSmartCard { public func send(ins: UInt8, p1: UInt8, p2: UInt8, data: Data? = nil, le: Int? = nil, reply: @escaping (Data?, UInt16, Error?) -> Void) { self.__sendIns(ins, p1: p1, p2: p2, data: data, le: le.map { NSNumber(value: $0) }, reply: reply) } @available(OSX 10.12, *) public func send(ins: UInt8, p1: UInt8, p2: UInt8, data: Data? = nil, le: Int? = nil) throws -> (sw: UInt16, response: Data) { var sw: UInt16 = 0 let response = try self.__sendIns(ins, p1: p1, p2: p2, data: data, le: le.map { NSNumber(value: $0) }, sw: &sw) return (sw: sw, response: response) } @available(OSX 10.12, *) public func withSession<T>(_ body: @escaping () throws -> T) throws -> T { var result: T? try self.__inSession(executeBlock: { (errorPointer: NSErrorPointer) -> Bool in do { result = try body() return true } catch let error as NSError { errorPointer?.pointee = error return false } }) // it is safe to force unwrap the result here, as the self.__inSession // function rethrows the errors which happened inside the block return result! } }
e2bc718d7c889a081303bef79274095f
32
80
0.578002
false
false
false
false
tomohisa/SwiftSlackBotter
refs/heads/master
Sources/EventObserver.swift
mit
1
// EventObserver.swift // The MIT License (MIT) // // Copyright (c) 2016 J-Tech Creations, Inc. // // 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 Axis public protocol EventObserver { func onEvent(event:RTMEvent, bot:Bot) throws } public class DefaultEventObserver : EventObserver { public var onMessage : ((MessageEvent, Bot) throws -> Void)? = nil public var onOwnMessage : ((MessageEvent, Bot) throws -> Void)? = nil public var onHello : ((HelloEvent, Bot) throws -> Void)? = nil public init(onMessage:((MessageEvent, Bot) throws -> Void)? = nil) { self.onMessage = onMessage } public func onEvent(event:RTMEvent, bot:Bot) throws { logger.debug("botid=\(bot.botInfo.botId)") switch event { case let hello as HelloEvent: try onHello?(hello, bot) case let message as MessageEvent: if message.user == bot.botInfo.botId || message.isBotMessage { logger.debug("bot message") try onOwnMessage?(message, bot) } else { logger.debug("user message") try onMessage?(message, bot) } default: break; } } }
61d5cedd5251a8399d9d341af4aa1ccf
39.735849
81
0.704493
false
false
false
false
gbuela/kanjiryokucha
refs/heads/master
KanjiRyokucha/BackgroundFetcher.swift
mit
1
// // BackgroundFetcher.swift // KanjiRyokucha // // Created by German Buela on 8/17/17. // Copyright © 2017 German Buela. All rights reserved. // import Foundation import ReactiveSwift enum BackgroundFetcherResult { case notChecked case failure case success(oldCount: Int, newCount: Int) } typealias BackgroundFetcherCompletion = (BackgroundFetcherResult) -> () /** Goal is to get access to latest due count (saved in Global) and fetch current due count from backend. All execution paths should lead to completion closure. Prior to fetching status we log in to ensure active session. For the purpose of background fetch, we don't care about reasons for failures -- we either get the values or not. We don't care about the UI either. If the user opens the app, it will update its UI as usual. */ class BackgroundFetcher { // we prevent the notification that is meant for presenting credentials vc let loginViewModel = LoginViewModel(sendLoginNotification: false) var statusAction: Action<Void, Response, FetchError>? let completion: BackgroundFetcherCompletion init(completion: @escaping BackgroundFetcherCompletion) { self.completion = completion } func start() { log("Starting BackgroundFetcher") loginViewModel.state.react { [weak self] loginState in switch loginState { case .loggedIn: log("Logged in!") if Database.getGlobal().useNotifications { self?.getCurrentStatus() } else { self?.completion(.notChecked) } break case let .failure(err): log("Login failed with: \(err)") self?.completion(.failure) break default: break } } log("Autologin...") loginViewModel.autologin() } func getCurrentStatus() { let oldCount = Database.getGlobal().latestDueCount statusAction = Action<Void, Response, FetchError>(execute: { _ in return GetStatusRequest().requestProducer()! }) statusAction?.react { [weak self] response in if let model = response.model as? GetStatusModel { log("Status succeeded!") self?.completion(.success(oldCount: oldCount, newCount: model.expiredCards)) } else { log("Status not getting expected model") self?.completion(.failure) } } statusAction?.completed.react { log("Status completed") } statusAction?.errors.react { [weak self] err in log("Status failed with: \(err)") self?.completion(.failure) } let delayInSeconds = 4.0 DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + delayInSeconds) { log("Getting status...") self.statusAction?.apply().start() } } }
62f85357f2fd1e632d142bcd73b190da
31.410526
94
0.597597
false
false
false
false
bordplate/sociabl
refs/heads/master
Sources/App/Renderer.swift
mit
1
// // Renderer.swift // sociabl // // Created by Vetle Økland on 20/03/2017. // // import Vapor import Leaf import HTTP import Auth /// A custom renderer that injects authentication details if any public final class Renderer: ViewRenderer { public let stem: Stem public init(viewsDir: String = drop.workDir + "Resources/Views") { stem = Stem(workingDirectory: viewsDir) } public func make(_ path: String, _ context: Node) throws -> View { var appendingContext = context appendingContext["authorized"] = false if let storage = context["request"]?["storage"] { if storage["authorized"] == true { appendingContext["authorized"] = true appendingContext["logged_user"] = storage["authorized_user"] } } let leaf = try stem.spawnLeaf(named: path) let context = Context(appendingContext.makeNode()) let bytes = try stem.render(leaf, with: context) return View(data: bytes) } }
dca8fa72160486b6fe05e7c960ae78c8
26.631579
76
0.609524
false
false
false
false
applivery/applivery-ios-sdk
refs/heads/master
AppliverySDK/Applivery/Interactors/StartInteractor.swift
mit
1
// // StartInteractor.swift // AppliverySDK // // Created by Alejandro Jiménez on 4/10/15. // Copyright © 2015 Applivery S.L. All rights reserved. // import Foundation protocol StartInteractorOutput { func forceUpdate() func otaUpdate() func feedbackEvent() func credentialError(message: String) } class StartInteractor { var output: StartInteractorOutput! private let configDataManager: PConfigDataManager private let globalConfig: GlobalConfig private let eventDetector: EventDetector private let sessionPersister: SessionPersister private let updateInteractor: PUpdateInteractor // MARK: Initializers init(configDataManager: PConfigDataManager = ConfigDataManager(), globalConfig: GlobalConfig = GlobalConfig.shared, eventDetector: EventDetector = ScreenshotDetector(), sessionPersister: SessionPersister = SessionPersister(userDefaults: UserDefaults.standard), updateInteractor: PUpdateInteractor = Configurator.updateInteractor() ) { self.configDataManager = configDataManager self.globalConfig = globalConfig self.eventDetector = eventDetector self.sessionPersister = sessionPersister self.updateInteractor = updateInteractor } // MARK: Internal Methods func start() { logInfo("Applivery is starting... ") logInfo("SDK Version: \(GlobalConfig.shared.app.getSDKVersion())") guard !self.globalConfig.appToken.isEmpty else { return self.output.credentialError(message: kLocaleErrorEmptyCredentials) } self.eventDetector.listenEvent(self.output.feedbackEvent) self.updateConfig() } func disableFeedback() { guard self.globalConfig.feedbackEnabled else { return } self.globalConfig.feedbackEnabled = false self.eventDetector.endListening() } // MARK: Private Methods private func updateConfig() { self.globalConfig.accessToken = self.sessionPersister.loadAccessToken() self.configDataManager.updateConfig { response in switch response { case .success(let configResponse): self.checkUpdate(for: configResponse) case .error(let error): self.output.credentialError(message: error.message()) let currentConfig = self.configDataManager.getCurrentConfig() self.checkUpdate(for: currentConfig) } } } private func checkUpdate(for updateConfig: UpdateConfigResponse) { if self.updateInteractor.checkForceUpdate(updateConfig.config, version: updateConfig.version) { self.output.forceUpdate() } else if self.updateInteractor.checkOtaUpdate(updateConfig.config, version: updateConfig.version) { self.output.otaUpdate() } } }
b9f1508562549e9c7bfd72aeb63e24db
31.32967
108
0.673012
false
true
false
false
Bluthwort/Bluthwort
refs/heads/master
Sources/Classes/Core/UIImage.swift
mit
1
// // UIImage.swift // // Copyright (c) 2018 Bluthwort // // 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. // extension UIImage { public enum GradientType { /// Top to bottom. case vertical /// Left to right. case horizontal /// Top left to bottom right. case diagonal1 /// Bottom left to top right. case diagonal2 } } extension Bluthwort where Base: UIImage { /// Creates a pure color image. /// /// - Parameters: /// - color: The color of the image. /// - size: The size of the image. `(1.0, 1.0)` by default. /// - Returns: The created `UIImage`. public static func `init`(color: UIColor, size: CGSize = .init(width: 1.0, height: 1.0)) -> Base? { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image as? Base } /// Creates a gradient image. /// /// - Parameters: /// - colors: The colors of the image. /// - size: The size of the image. `(1.0, 1.0)` by default. /// - type: The gradient type of the image. `UIImage.GradientType.vertical` by default. /// - Returns: The created `UIImage`. public static func `init`(colors: [UIColor], size: CGSize = .init(width: 1.0, height: 1.0), type: UIImage.GradientType = .vertical) -> Base? { var cgColors = [CGColor]() colors.forEach { let red = $0.bw.red, green = $0.bw.green, blue = $0.bw.blue, alpha = $0.bw.alpha let cgColor = UIColor(red: red, green: green, blue: blue, alpha: alpha).cgColor cgColors.append(cgColor) } UIGraphicsBeginImageContextWithOptions(size, true, 1.0) let context = UIGraphicsGetCurrentContext() context?.saveGState() guard let gradient = CGGradient(colorsSpace: cgColors.last?.colorSpace, colors: cgColors as CFArray, locations: nil) else { return nil } var startPoint = CGPoint.zero, endPoint = CGPoint.zero switch type { case .vertical: endPoint.y = size.height case .horizontal: endPoint.x = size.width case .diagonal1: endPoint.x = size.width endPoint.y = size.height case .diagonal2: startPoint.y = size.height endPoint.x = size.width } context?.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: [.drawsBeforeStartLocation, .drawsAfterEndLocation]) let image = UIGraphicsGetImageFromCurrentImageContext() context?.restoreGState() UIGraphicsEndImageContext() return image as? Base } /// Creates an instance from view. /// /// - Parameters: /// - view: The view to create image. /// - size: The size of image. `view.bounds.size` by default. /// - Returns: The created `UIImage`. public static func `init`(view: UIView, size: CGSize? = nil) -> Base? { let imageSize = size ?? view.bounds.size UIGraphicsBeginImageContextWithOptions(imageSize, false, 0.0) guard UIGraphicsGetCurrentContext() != nil else { return nil } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image as? Base } /// Creates a QR code image. /// /// - Parameters: /// - qrCodeString: The QR code message. /// - scaleX: The scale of the X axis. `10.0` by default. /// - scaleY: The scale of the Y axis. `10.0` by default. /// - Returns: The created `UIImage`. public static func `init`(qrCodeString: String, scaleX: CGFloat = 10.0, scaleY: CGFloat = 10.0) -> Base? { let data = qrCodeString.data(using: .utf8) let filter = CIFilter(name: "CIQRCodeGenerator") filter?.setValue(data, forKey: "inputMessage") let outputImage = filter?.outputImage guard let ciImage = outputImage?.transformed(by: .init(scaleX: scaleX, y: scaleY)) else { return nil } let context = CIContext(options: nil) guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else { return nil } return Base(cgImage: cgImage) } /// Resize image to a new size. /// /// - Parameter size: The new size. /// - Returns: The resized image. public func resize(to size: CGSize) -> Base? { UIGraphicsBeginImageContext(size) base.draw(in: .init(origin: .zero, size: size)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resizedImage as? Base } /// Resie image by a scale. /// /// - Parameter scale: The scale. /// - Returns: The resized image. public func resize(by scale: CGFloat) -> Base? { let width = base.size.width * scale, height = base.size.height * scale let size = CGSize(width: width, height: height) return resize(to: size) } }
75d7745976661cb114cbe1333fab7f22
36.971264
97
0.600727
false
false
false
false
xuzhuoxi/SearchKit
refs/heads/master
Source/ExSwift/Range.swift
mit
1
// // Range.swift // ExSwift // // Created by pNre on 04/06/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation public extension CountableRange { /** For each element in the range invokes function. - parameter function: Function to call */ public func times (_ function: () -> ()) { each { (current: Bound) -> () in function() } } /** For each element in the range invokes function passing the element as argument. - parameter function: Function to invoke */ public func times (_ function: (Bound) -> ()) { each (function) } /** For each element in the range invokes function passing the element as argument. - parameter function: Function to invoke */ public func each (_ function: (Bound) -> ()) { for i in self { function(i) } } /** Returns each element of the range in an array - returns: Each element of the range in an array */ public func toArray () -> [Bound] { var result: [Bound] = [] for i in self { result.append(i) } return result } /** Range of Int with random bounds between from and to (inclusive). - parameter from: Lower bound - parameter to: Upper bound - returns: Random range */ public static func random (_ from: Int, to: Int) -> CountableClosedRange<Int> { let lowerBound = Int.random(from, max: to) let upperBound = Int.random(lowerBound, max: to) return lowerBound...upperBound } } public extension CountableClosedRange { /** For each element in the range invokes function. - parameter function: Function to call */ public func times (_ function: () -> ()) { each { (current: Bound) -> () in function() } } /** For each element in the range invokes function passing the element as argument. - parameter function: Function to invoke */ public func times (_ function: (Bound) -> ()) { each (function) } /** For each element in the range invokes function passing the element as argument. - parameter function: Function to invoke */ public func each (_ function: (Bound) -> ()) { for i in self { function(i) } } /** Returns each element of the range in an array - returns: Each element of the range in an array */ public func toArray () -> [Bound] { var result: [Bound] = [] for i in self { result.append(i) } return result } /** Range of Int with random bounds between from and to (inclusive). - parameter from: Lower bound - parameter to: Upper bound - returns: Random range */ public static func random (_ from: Int, to: Int) -> CountableClosedRange<Int> { let lowerBound = Int.random(from, max: to) let upperBound = Int.random(lowerBound, max: to) return lowerBound...upperBound } } /** * Operator == to compare 2 ranges first, second by start & end indexes. If first.startIndex is equal to * second.startIndex and first.endIndex is equal to second.endIndex the ranges are considered equal. */ public func == <U: Comparable> (first: Range<U>, second: Range<U>) -> Bool { return first.lowerBound == second.lowerBound && first.upperBound == second.upperBound }
1eff9e45e82abdc85e4c57b691892e4f
21.838028
105
0.633056
false
false
false
false
neonichu/trousers
refs/heads/master
Code/PantsLoginViewController.swift
mit
1
// // PantsLoginViewController.swift // Trousers // // Created by Boris Bügling on 27/08/14. // Copyright (c) 2014 Boris Bügling. All rights reserved. // import UIKit class PantsLoginViewController: UIViewController, UITextFieldDelegate { var domainTextField : UITextField? var passwordTextField : UITextField? func buildLabel() -> UILabel { var label = UILabel(frame: insetRect(self.view.width())) label.font = UIFont(name: "Marion", size: 20) label.frame.size.height = 20 label.textAlignment = NSTextAlignment.Center label.textColor = UIColor.lightGrayColor() return label } func buildTextField(after: UILabel) -> UITextField { var textField = UITextField(frame: after.nextVerticalRect()) textField.delegate = self textField.font = after.font textField.placeholder = after.text return textField } func loginTapped(sender : UIButton!) -> Void { SSKeychain.setPassword(self.passwordTextField!.text, forService: PantsDomainKey, account: self.domainTextField!.text) PantsSessionManager.sharedManager.login(self.passwordTextField!.text, handler: { (response, error) -> (Void) in self.navigationController.pushViewController(PantsPostsViewController(), animated: true) }) } override func viewDidLoad() { self.edgesForExtendedLayout = UIRectEdge.None self.title = NSLocalizedString("#pants Login", comment: "") self.view.backgroundColor = UIColor.whiteColor() var domainLabel = self.buildLabel() domainLabel.frame.origin.y = 100 domainLabel.text = NSLocalizedString("Domain", comment: "") self.view.addSubview(domainLabel) self.domainTextField = self.buildTextField(domainLabel) self.domainTextField!.returnKeyType = UIReturnKeyType.Next self.view.addSubview(self.domainTextField!) var passwordLabel = self.buildLabel() passwordLabel.frame.origin.y = CGRectGetMaxY(self.domainTextField!.frame) + 10 passwordLabel.text = NSLocalizedString("Password", comment: "") self.view.addSubview(passwordLabel) self.passwordTextField = self.buildTextField(passwordLabel) self.passwordTextField!.returnKeyType = UIReturnKeyType.Go self.passwordTextField!.secureTextEntry = true self.view.addSubview(self.passwordTextField!) var loginButton = UIButton.buttonWithType(UIButtonType.System) as UIButton loginButton.addTarget(self, action: "loginTapped:", forControlEvents: UIControlEvents.TouchUpInside) loginButton.backgroundColor = buttonColor() loginButton.titleLabel.font = domainLabel.font loginButton.frame = self.passwordTextField!.nextVerticalRect() loginButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) loginButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Highlighted) loginButton.setTitle(NSLocalizedString("Login", comment: ""), forState: UIControlState.Normal) loginButton.frame.size = CGSize(width: 150.0, height: 44.0) loginButton.frame.origin.x = (self.view.width() - loginButton.width()) / 2 self.view.addSubview(loginButton) } func textFieldShouldReturn(textField: UITextField!) -> Bool { if (textField.returnKeyType == UIReturnKeyType.Next) { self.passwordTextField!.becomeFirstResponder() } else { self.loginTapped(nil) } return false } }
37b18a44437830154a7da91f29930c11
38.5
93
0.681618
false
false
false
false