repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
SwiftBond/Bond
Sources/Bond/Data Structures/TreeNodeProtocol.swift
1
11401
// // The MIT License (MIT) // // Copyright (c) 2018 DeclarativeHub/Bond // // 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 /// A tree node represents a node in a tree structure. /// A tree node has a value associated with itself and zero or more child tree nodes. public protocol TreeNodeProtocol { /// Type of the node value. associatedtype Value /// Index type used to iterate over child nodes. associatedtype Index: Equatable /// Type of the child node. associatedtype ChildNode: TreeNodeProtocol /// All child nodes of the node. var children: [ChildNode] { get } /// Value of the node, i.e. data that the node contains. var value: Value { get } /// Index of the first child node. var startIndex: Index { get } /// Index beyond last child node. var endIndex: Index { get } /// True if node has not child nodes, false otherwise. var isEmpty: Bool { get } /// Number of child nodes. var count: Int { get } /// Index after the given index assuming depth-first tree search. func index(after i: Index) -> Index /// Index before the given index assuming depth-first tree search. func index(before i: Index) -> Index /// Indices of all nodes in the tree in DFS order. Does not include index of root node (self). var indices: [Index] { get } /// Access tree node at the given index. subscript(_ index: Index) -> ChildNode { get } } extension TreeNodeProtocol { /// Access value of a tree node at the given index. public subscript(valueAt index: Index) -> ChildNode.Value { return self[index].value } /// Returns index of the first child that passes the given test. /// - complexity: O(n) public func firstIndex(where test: (ChildNode) -> Bool) -> Index? { var index = startIndex while index != endIndex { if test(self[index]) { return index } else { index = self.index(after: index) } } return nil } } public protocol MutableTreeNodeProtocol: TreeNodeProtocol { var value: Value { get set } subscript(_ index: Index) -> ChildNode { get set } } public protocol RangeReplaceableTreeNode: MutableTreeNodeProtocol where Index: Comparable, ChildNode.Index == Index, ChildNode.ChildNode == ChildNode, ChildNode: RangeReplaceableTreeNode { /// Replace children at the given subrange with new children. /// Range lowerBound and upperBound must be at the same level. mutating func replaceChildrenSubrange<C>(_ subrange: Range<Index>, with newChildren: C) where C: Collection, C.Element == ChildNode /// Index of the child node that follows the child node at the given index at the same level in the tree. func indexAtSameLevel(after i: Index) -> Index } extension RangeReplaceableTreeNode where Index == IndexPath { public func indexAtSameLevel(after i: IndexPath) -> IndexPath { return i.advanced(by: 1, atLevel: i.count-1) } } extension RangeReplaceableTreeNode { /// Insert the new node into the tree as the last child of self. public mutating func append(_ newNode: ChildNode) { insert(newNode, at: endIndex) } /// Insert the new node into the tree at the given index. public mutating func insert(_ newNode: ChildNode, at index: Index) { replaceChildrenSubrange(index..<index, with: [newNode]) } /// Insert the array of nodes into the tree at the given index. public mutating func insert(contentsOf newNodes: [ChildNode], at index: Index) { replaceChildrenSubrange(index..<index, with: newNodes) } /// Replace the node at the given index with the new node. @discardableResult public mutating func update(at index: Index, newNode: ChildNode) -> ChildNode { let subtree = self[index] replaceChildrenSubrange(index..<indexAtSameLevel(after: index), with: [newNode]) return subtree } /// Remove the node (including its subtree) at the given index. @discardableResult public mutating func remove(at index: Index) -> ChildNode { let subtree = self[index] replaceChildrenSubrange(index..<indexAtSameLevel(after: index), with: []) return subtree } /// Remove the nodes (including their subtrees) at the given indexes. @discardableResult public mutating func remove(at indexes: [Index]) -> [ChildNode] { return indexes.sorted().reversed().map { self.remove(at:$0) }.reversed() } /// Remove all child node. Only the tree root node (self) will remain. public mutating func removeAll() { replaceChildrenSubrange(startIndex..<endIndex, with: []) } /// Move the node from one position to another. public mutating func move(from fromIndex: Index, to toIndex: Index) { let subtree = remove(at: fromIndex) insert(subtree, at: toIndex) } /// Gather the nodes with the given indices and move them to the given index. public mutating func move(from fromIndices: [Index], to toIndex: Index) { let items = remove(at: fromIndices) insert(contentsOf: items, at: toIndex) } } public protocol ArrayBasedTreeNode: RangeReplaceableTreeNode where Index == IndexPath { /// Child nodes of `self`. var children: [ChildNode] { get set } } extension ArrayBasedTreeNode { public var startIndex: IndexPath { return IndexPath(index: children.startIndex) } public var endIndex: IndexPath { return IndexPath(index: children.endIndex) } public var isEmpty: Bool { return children.isEmpty } public var count: Int { return children.count } public var indices: [IndexPath] { guard count > 0 else { return [] } return Array(sequence(first: startIndex, next: { let next = self.index(after: $0) return next == self.endIndex ? nil : next })) } public func index(after i: IndexPath) -> IndexPath { guard i.count > 0 else { fatalError("Invalid index path.") } if self[i].isEmpty == false { return i + [0] } else { var i = i while i.count > 1 { let parent = self[i.dropLast()] let indexInParent = i.last! if indexInParent < parent.count - 1 { return i.dropLast().appending(indexInParent + 1) } else { i = i.dropLast() } } return i.advanced(by: 1, atLevel: 0) } } public func index(before i: IndexPath) -> IndexPath { guard i.count > 0 else { fatalError("Invalid index path.") } if i.last! == 0 { return i.dropLast() } else { var i = i.advanced(by: -1, atLevel: i.count - 1) while true { let potentialNode = self[i] if potentialNode.isEmpty { return i } else { i = i + [potentialNode.count - 1] // last child of potential node is next potential node } } } } public mutating func replaceChildrenSubrange<C>(_ subrange: Range<IndexPath>, with newChildren: C) where C: Collection, C.Element == ChildNode { guard !subrange.lowerBound.isEmpty else { fatalError("Invalid index") } guard subrange.lowerBound.count == subrange.upperBound.count else { if index(after: subrange.lowerBound) == subrange.upperBound { // deleting last child let endIndex = subrange.lowerBound.count > 1 ? self[subrange.lowerBound.dropLast()].count : count var upperBound = subrange.lowerBound upperBound[upperBound.count-1] = endIndex replaceChildrenSubrange(subrange.lowerBound..<upperBound, with: newChildren) return } else { fatalError("Range lowerBound and upperBound of \(subrange) must be at the same level!") } } if subrange.lowerBound.count == 1 { children.replaceSubrange(subrange.lowerBound[0]..<subrange.upperBound[0], with: newChildren) } else { guard subrange.lowerBound[0] == subrange.upperBound[0] else { fatalError("Range lowerBound and upperBound must point to the same subtree!") } children[subrange.lowerBound[0]].replaceChildrenSubrange(subrange.lowerBound.dropFirst()..<subrange.upperBound.dropFirst(), with: newChildren) } } } extension ArrayBasedTreeNode where ChildNode: ArrayBasedTreeNode, ChildNode.Value: Equatable { public func first(matching filter: (ChildNode) -> Bool) -> ChildNode? { for child in children { guard let matchingItem = child.first(matching: filter) else { continue } return matchingItem } return nil } public func index(of node: ChildNode, startingPath: IndexPath = IndexPath()) -> IndexPath? { for (index, child) in children.enumerated() { guard let childPath = child.index(of: node, startingPath: startingPath.appending(index)) else { continue } return childPath } return nil } } extension ArrayBasedTreeNode where Value: Equatable, ChildNode == Self { public func first(matching filter: (ChildNode) -> Bool) -> ChildNode? { guard filter(self) == false else { return self } for child in children { guard let matchingChild = child.first(matching: filter) else { continue } return matchingChild } return nil } public func index(of node: ChildNode, startingPath: IndexPath = IndexPath()) -> IndexPath? { guard node.value != value else { return startingPath } for (index, child) in children.enumerated() { guard let childPath = child.index(of: node, startingPath: startingPath.appending(index)) else { continue } return childPath } return nil } }
mit
a41938182f5633ad903a079a4dab5233
33.340361
188
0.626261
4.615789
false
false
false
false
maitruonghcmus/QuickChat
QuickChat/Helper files/Helper Files.swift
1
1275
import Foundation import UIKit //Global variables struct GlobalVariables { static let blue = UIColor.rbg(r: 0, g: 123, b: 255) static let purple = UIColor.rbg(r: 0, g: 123, b: 255) } //Extensions extension UIColor{ class func rbg(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor { let color = UIColor.init(red: r/255, green: g/255, blue: b/255, alpha: 1) return color } } class RoundedImageView: UIImageView { override func layoutSubviews() { super.layoutSubviews() let radius: CGFloat = self.bounds.size.width / 2.0 self.layer.cornerRadius = radius self.clipsToBounds = true } } class RoundedButton: UIButton { override func layoutSubviews() { super.layoutSubviews() let radius: CGFloat = self.bounds.size.height / 2.0 self.layer.cornerRadius = radius self.clipsToBounds = true } } //Enums enum ViewControllerType { case welcome case conversations case login case tabbar } enum PhotoSource { case library case camera } enum ShowExtraView { case contacts case profile case preview case map } enum MessageType { case photo case text case location } enum MessageOwner { case sender case receiver }
mit
0f9a17ed6268f6fb328b746a7792fa4b
18.615385
81
0.650196
3.959627
false
false
false
false
dtrauger/Charts
Source/Charts/Renderers/YAxisRendererHorizontalBarChart.swift
1
13275
// // YAxisRendererHorizontalBarChart.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class YAxisRendererHorizontalBarChart: YAxisRenderer { public override init(viewPortHandler: ViewPortHandler?, yAxis: YAxis?, transformer: Transformer?) { super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: transformer) } /// Computes the axis values. open override func computeAxis(min: Double, max: Double, inverted: Bool) { guard let viewPortHandler = self.viewPortHandler, let transformer = self.transformer else { return } var min = min, max = max // calculate the starting and entry point of the y-labels (depending on zoom / contentrect bounds) if viewPortHandler.contentHeight > 10.0 && !viewPortHandler.isFullyZoomedOutX { let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) if !inverted { min = Double(p1.x) max = Double(p2.x) } else { min = Double(p2.x) max = Double(p1.x) } } computeAxisValues(min: min, max: max) } /// draws the y-axis labels to the screen open override func renderAxisLabels(context: CGContext) { guard let yAxis = axis as? YAxis, let viewPortHandler = self.viewPortHandler else { return } if !yAxis.isEnabled || !yAxis.isDrawLabelsEnabled { return } let lineHeight = yAxis.labelFont.lineHeight let baseYOffset: CGFloat = 2.5 let dependency = yAxis.axisDependency let labelPosition = yAxis.labelPosition var yPos: CGFloat = 0.0 if dependency == .left { if labelPosition == .outsideChart { yPos = viewPortHandler.contentTop - baseYOffset } else { yPos = viewPortHandler.contentTop - baseYOffset } } else { if labelPosition == .outsideChart { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } else { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } } // For compatibility with Android code, we keep above calculation the same, // And here we pull the line back up yPos -= lineHeight drawYLabels( context: context, fixedPosition: yPos, positions: transformedPositions(), offset: yAxis.yOffset) } open override func renderAxisLine(context: CGContext) { guard let yAxis = axis as? YAxis, let viewPortHandler = self.viewPortHandler else { return } if !yAxis.isEnabled || !yAxis.drawAxisLineEnabled { return } context.saveGState() context.setStrokeColor(yAxis.axisLineColor.cgColor) context.setLineWidth(yAxis.axisLineWidth) if yAxis.axisLineDashLengths != nil { context.setLineDash(phase: yAxis.axisLineDashPhase, lengths: yAxis.axisLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } if yAxis.axisDependency == .left { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) context.strokePath() } else { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom)) context.strokePath() } context.restoreGState() } /// draws the y-labels on the specified x-position open func drawYLabels( context: CGContext, fixedPosition: CGFloat, positions: [CGPoint], offset: CGFloat) { guard let yAxis = axis as? YAxis else { return } let labelFont = yAxis.labelFont let labelTextColor = yAxis.labelTextColor for i in 0 ..< yAxis.entryCount { let text = yAxis.getFormattedLabel(i) if !yAxis.isDrawTopYLabelEntryEnabled && i >= yAxis.entryCount - 1 { return } ChartUtils.drawText( context: context, text: text, point: CGPoint(x: positions[i].x, y: fixedPosition - offset), align: .center, attributes: [convertFromNSAttributedStringKey(NSAttributedString.Key.font): labelFont, convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): labelTextColor]) } } open override var gridClippingRect: CGRect { var contentRect = viewPortHandler?.contentRect ?? CGRect.zero let dx = self.axis?.gridLineWidth ?? 0.0 contentRect.origin.x -= dx / 2.0 contentRect.size.width += dx return contentRect } open override func drawGridLine( context: CGContext, position: CGPoint) { guard let viewPortHandler = self.viewPortHandler else { return } context.beginPath() context.move(to: CGPoint(x: position.x, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: position.x, y: viewPortHandler.contentBottom)) context.strokePath() } open override func transformedPositions() -> [CGPoint] { guard let yAxis = self.axis as? YAxis, let transformer = self.transformer else { return [CGPoint]() } var positions = [CGPoint]() positions.reserveCapacity(yAxis.entryCount) let entries = yAxis.entries for i in stride(from: 0, to: yAxis.entryCount, by: 1) { positions.append(CGPoint(x: entries[i], y: 0.0)) } transformer.pointValuesToPixel(&positions) return positions } /// Draws the zero line at the specified position. open override func drawZeroLine(context: CGContext) { guard let yAxis = self.axis as? YAxis, let viewPortHandler = self.viewPortHandler, let transformer = self.transformer, let zeroLineColor = yAxis.zeroLineColor else { return } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.x -= yAxis.zeroLineWidth / 2.0 clippingRect.size.width += yAxis.zeroLineWidth context.clip(to: clippingRect) context.setStrokeColor(zeroLineColor.cgColor) context.setLineWidth(yAxis.zeroLineWidth) let pos = transformer.pixelForValues(x: 0.0, y: 0.0) if yAxis.zeroLineDashLengths != nil { context.setLineDash(phase: yAxis.zeroLineDashPhase, lengths: yAxis.zeroLineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.move(to: CGPoint(x: pos.x - 1.0, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: pos.x - 1.0, y: viewPortHandler.contentBottom)) context.drawPath(using: CGPathDrawingMode.stroke) } fileprivate var _limitLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2) open override func renderLimitLines(context: CGContext) { guard let yAxis = axis as? YAxis, let viewPortHandler = self.viewPortHandler, let transformer = self.transformer else { return } var limitLines = yAxis.limitLines if limitLines.count <= 0 { return } context.saveGState() let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for i in 0 ..< limitLines.count { let l = limitLines[i] if !l.isEnabled { continue } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.x -= l.lineWidth / 2.0 clippingRect.size.width += l.lineWidth context.clip(to: clippingRect) position.x = CGFloat(l.limit) position.y = 0.0 position = position.applying(trans) context.beginPath() context.move(to: CGPoint(x: position.x, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: position.x, y: viewPortHandler.contentBottom)) context.setStrokeColor(l.lineColor.cgColor) context.setLineWidth(l.lineWidth) if l.lineDashLengths != nil { context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.strokePath() let label = l.label // if drawing the limit-value label is enabled if l.drawLabelEnabled && label.count > 0 { let labelLineHeight = l.valueFont.lineHeight let xOffset: CGFloat = l.lineWidth + l.xOffset let yOffset: CGFloat = 2.0 + l.yOffset if l.labelPosition == .rightTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentTop + yOffset), align: .left, attributes: [convertFromNSAttributedStringKey(NSAttributedString.Key.font): l.valueFont, convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): l.valueTextColor]) } else if l.labelPosition == .rightBottom { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .left, attributes: [convertFromNSAttributedStringKey(NSAttributedString.Key.font): l.valueFont, convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): l.valueTextColor]) } else if l.labelPosition == .leftTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentTop + yOffset), align: .right, attributes: [convertFromNSAttributedStringKey(NSAttributedString.Key.font): l.valueFont, convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .right, attributes: [convertFromNSAttributedStringKey(NSAttributedString.Key.font): l.valueFont, convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): l.valueTextColor]) } } } context.restoreGState() } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue }
apache-2.0
bdefe4068b6c5a1b0d6d2ab8c39d1082
33.125964
205
0.551337
5.648936
false
false
false
false
nbhasin2/NBNavigationController
Example/GobstonesSwift/Extensions/StringExtension.swift
1
6224
// // StringExtension.swift // GobstonesSwift // // Created by Nishant Bhasin on 2016-12-27. // Copyright © 2016 Nishant Bhasin. All rights reserved. // import Foundation extension String { //To check text field or String is blank or not var isBlank: Bool { get { let trimmed = trimmingCharacters(in: CharacterSet.whitespaces) return trimmed.isEmpty } } //Validate Email var isEmail: Bool { do { let regex = try NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive) return regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil } catch { return false } } /** Converts a ruby date string to an NSDate object. See rubyFormatter for accepted format. - returns: A NSDate or nil if the string is empty or cannot be formatted. */ func convertDateFromString() -> Date? { if (self.isEmpty) { return nil } // Grab the shared formatter which will speed up the conversion since we don't have to keep initializing it else { let formatter = DateFormatter() return formatter.date(from: self) } } // MARK: - Variables /// The first character of the string var first: String { return String(characters.prefix(1)) } /// The last character of the string var last: String { return String(characters.suffix(1)) } /// Capitalizes only the first letter of the string that invokes the computation. var capitalizeFirst: String { return first.uppercased() + String(characters.dropFirst()) } /// This string as a Float var floatValue: Float { return (self as NSString).floatValue } /// This string as an Int var intValue: Int { return (self as NSString).integerValue } /// This string as a Double var doubleValue: Double { return (self as NSString).doubleValue } /// True if this string is a postive float var isValidPostiveFloat: Bool { let regex = try? NSRegularExpression(pattern: "^(?=.+)(?:[1-9]\\d*|0)?(?:\\.\\d+)?$", options: .caseInsensitive) return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.characters.count)) != nil } /// True if this string is a postive int var isValidPostiveInt: Bool { let regex = try? NSRegularExpression(pattern: "^\\d+$", options: .caseInsensitive) return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.characters.count)) != nil } /// True if this string contains only numbers and letters var isAlphaNumeric: Bool { let alpaNumericSet = CharacterSet.alphanumerics.inverted let string = (self as NSString) return (string.rangeOfCharacter(from: alpaNumericSet).location == NSNotFound) } /// True if this string is only letters and between 1 - 255 characeters var isValidName: Bool { let regex = try? NSRegularExpression(pattern: "^([a-zA-ZÀ-ÿ-]){1,255}$", options: .caseInsensitive) return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.characters.count)) != nil } /// True if this string is a valid email var isValidEmail: Bool { let regex = try? NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$", options: .caseInsensitive) return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.characters.count)) != nil } /// True if this string is a valid email for develop var isValidEmailDev: Bool { let regex = try? NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}([#][A-Z]+)?$", options: .caseInsensitive) return regex?.firstMatch(in: self, options: [], range: NSMakeRange(0, self.characters.count)) != nil } /// True if this string is a valid password. var isPasswordValid: Bool { return (self.characters.count > 7 && self.characters.count < 128) } /// True if this string contains only white space. var containsWhitespaceOnly: Bool { let whitespace = CharacterSet.whitespaces return self.trimmingCharacters(in: whitespace).isEmpty } // MARK: - Subscripts /** Returns the character at the given index. - parameter integerIndex: The index of the character you want - returns: A character */ subscript(integerIndex: Int) -> Character { let index = characters.index(startIndex, offsetBy: integerIndex) return self[index] } subscript(integerRange: Range<Int>) -> String { let start = characters.index(startIndex, offsetBy: integerRange.lowerBound) let end = characters.index(startIndex, offsetBy: integerRange.upperBound) let range = start..<end return self[range] } // MARK: - Functions func contains(_ s: String) -> Bool { return (self.range(of: s) != nil) ? true : false } /** Splits a string into compoenats based on the separator given. - parameter separator: A string to split at. - returns: A array of string split */ public func split(_ separator: String) -> [String] { if separator.isEmpty { return self.characters.map { String($0) } } if var pre = self.range(of: separator) { var parts = [self.substring(to: pre.lowerBound)] while let rng = self.range(of: separator, range: pre.upperBound..<endIndex) { parts.append(self.substring(with: pre.upperBound..<rng.lowerBound)) pre = rng } parts.append(self.substring(with: pre.upperBound..<endIndex)) return parts } else { return [self] } } }
mit
28c0f4ebb99e3f86bf3b408b42f2a3a5
32.994536
220
0.596689
4.341242
false
false
false
false
loudnate/Loop
LoopUI/Charts/IOBChart.swift
1
4700
// // IOBChart.swift // LoopUI // // Copyright © 2019 LoopKit Authors. All rights reserved. // import Foundation import LoopKit import SwiftCharts public class IOBChart: ChartProviding { public init() { } /// The chart points for IOB public private(set) var iobPoints: [ChartPoint] = [] { didSet { if let lastDate = iobPoints.last?.x as? ChartAxisValueDate { endDate = lastDate.date } } } /// The minimum range to display for insulin values. private let iobDisplayRangePoints: [ChartPoint] = [0, 1].map { return ChartPoint( x: ChartAxisValue(scalar: 0), y: ChartAxisValueInt($0) ) } public private(set) var endDate: Date? private var iobChartCache: ChartPointsTouchHighlightLayerViewCache? } public extension IOBChart { func didReceiveMemoryWarning() { iobPoints = [] iobChartCache = nil } func generate(withFrame frame: CGRect, xAxisModel: ChartAxisModel, xAxisValues: [ChartAxisValue], axisLabelSettings: ChartLabelSettings, guideLinesLayerSettings: ChartGuideLinesLayerSettings, colors: ChartColorPalette, chartSettings: ChartSettings, labelsWidthY: CGFloat, gestureRecognizer: UIGestureRecognizer?, traitCollection: UITraitCollection) -> Chart { let yAxisValues = ChartAxisValuesStaticGenerator.generateYAxisValuesWithChartPoints(iobPoints + iobDisplayRangePoints, minSegmentCount: 2, maxSegmentCount: 3, multiple: 0.5, axisValueGenerator: { ChartAxisValueDouble($0, labelSettings: axisLabelSettings) }, addPaddingSegmentIfEdge: false) let yAxisModel = ChartAxisModel(axisValues: yAxisValues, lineColor: colors.axisLine, labelSpaceReservationMode: .fixed(labelsWidthY)) let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: frame, xModel: xAxisModel, yModel: yAxisModel) let (xAxisLayer, yAxisLayer, innerFrame) = (coordsSpace.xAxisLayer, coordsSpace.yAxisLayer, coordsSpace.chartInnerFrame) // The IOB area let lineModel = ChartLineModel(chartPoints: iobPoints, lineColor: UIColor.IOBTintColor, lineWidth: 2, animDuration: 0, animDelay: 0) let iobLine = ChartPointsLineLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, lineModels: [lineModel]) let iobArea = ChartPointsFillsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, fills: [ChartPointsFill(chartPoints: iobPoints, fillColor: UIColor.IOBTintColor.withAlphaComponent(0.5))]) // Grid lines let gridLayer = ChartGuideLinesForValuesLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, settings: guideLinesLayerSettings, axisValuesX: Array(xAxisValues.dropFirst().dropLast()), axisValuesY: yAxisValues) // 0-line let dummyZeroChartPoint = ChartPoint(x: ChartAxisValueDouble(0), y: ChartAxisValueDouble(0)) let zeroGuidelineLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: [dummyZeroChartPoint], viewGenerator: {(chartPointModel, layer, chart) -> UIView? in let width: CGFloat = 0.5 let viewFrame = CGRect(x: chart.contentView.bounds.minX, y: chartPointModel.screenLoc.y - width / 2, width: chart.contentView.bounds.size.width, height: width) let v = UIView(frame: viewFrame) v.layer.backgroundColor = UIColor.IOBTintColor.cgColor return v }) if gestureRecognizer != nil { iobChartCache = ChartPointsTouchHighlightLayerViewCache( xAxisLayer: xAxisLayer, yAxisLayer: yAxisLayer, axisLabelSettings: axisLabelSettings, chartPoints: iobPoints, tintColor: UIColor.IOBTintColor, gestureRecognizer: gestureRecognizer ) } let layers: [ChartLayer?] = [ gridLayer, xAxisLayer, yAxisLayer, zeroGuidelineLayer, iobChartCache?.highlightLayer, iobArea, iobLine, ] return Chart(frame: frame, innerFrame: innerFrame, settings: chartSettings, layers: layers.compactMap { $0 }) } } public extension IOBChart { func setIOBValues(_ iobValues: [InsulinValue]) { let dateFormatter = DateFormatter(timeStyle: .short) let doseFormatter = NumberFormatter.dose iobPoints = iobValues.map { return ChartPoint( x: ChartAxisValueDate(date: $0.startDate, formatter: dateFormatter), y: ChartAxisValueDoubleUnit($0.value, unitString: "U", formatter: doseFormatter) ) } } }
apache-2.0
b1d04d8c3bb3b67165f94151d7fd6825
40.955357
361
0.681422
5.091008
false
false
false
false
Constructor-io/constructorio-client-swift
AutocompleteClient/FW/DependencyInjection/DependencyContainer.swift
1
1146
// // DependencyContainer.swift // Constructor.io // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import Foundation class DependencyContainer { static let sharedInstance = DependencyContainer() private init() {} var networkClient: () -> NetworkClient = { return URLSessionNetworkClient() } var autocompleteResponseParser: () -> AbstractAutocompleteResponseParser = { return CIOAutocompleteResponseParser() } var searchResponseParser: () -> AbstractSearchResponseParser = { return SearchResponseParser() } var browseResponseParser: () -> AbstractBrowseResponseParser = { return BrowseResponseParser() } var recommendationsResponseParser: () -> AbstractRecommendationsResponseParser = { return RecommendationsResponseParser() } var sessionManager: () -> SessionManager = { return CIOSessionManager(dateProvider: CurrentTimeDateProvider(), timeout: Constants.Query.sessionIncrementTimeoutInSeconds) } var clientIDGenerator: () -> IDGenerator = { return ClientIDGenerator() } }
mit
3dd9cbc2212946265bc572b232d4b22f
25.022727
132
0.695197
5.504808
false
false
false
false
cmidt-veasna/SwiftFlatbuffer
XCodeFlatbuffer/FlatbufferSwift/Sources/base.swift
1
3243
// // File.swift // FlatbufferSwift // // Created by Veasna Sreng on 2/14/17. // // import Foundation // Data extension helper extension Data { public func get<T>(at: Int, withType: T.Type) -> T? { let numberOfByte = at + MemoryLayout<T>.stride if count <= numberOfByte || numberOfByte < 1 { return nil } // TODO: investigate this option. Which cause memory allocation increate as it seem no deallocation has been perform return withUnsafeBytes { (ptr: UnsafePointer<T>) -> T in return ptr.advanced(by: (at/MemoryLayout<T>.stride)).pointee } } public func getInteger<T: Integer>(at: Int) -> T { let numberOfByte = at + MemoryLayout<T>.stride if count <= numberOfByte || numberOfByte < 1 { return 0 } let copyCount = MemoryLayout<T>.stride var bytes: [UInt8] = [UInt8](repeating: 0, count: copyCount) copyBytes(to: &bytes, from: at ..< Data.Index(at + copyCount)) return UnsafePointer(bytes).withMemoryRebound(to: T.self, capacity: 1) { $0.pointee } } public func getFloatingPoint<T: FloatingPoint>(at: Int) -> T { let numberOfByte = at + MemoryLayout<T>.stride if count <= numberOfByte || numberOfByte < 1 { return 0 } let copyCount = MemoryLayout<T>.stride var bytes: [UInt8] = [UInt8](repeating: 0, count: copyCount) copyBytes(to: &bytes, from: at ..< Data.Index(at + copyCount)) return UnsafePointer(bytes).withMemoryRebound(to: T.self, capacity: 1) { $0.pointee } } public func getByte(at: Int) -> Int8 { return getInteger(at: at) } public func getUnsignedByte(at: Int) -> UInt8 { return getInteger(at: at) } public func getShort(at: Int) -> Int16 { return getInteger(at: at) } public func getUsignedShort(at: Int) -> UInt16 { return getInteger(at: at) } public func getInt(at: Int) -> Int32 { return getInteger(at: at) } public func getUnsignedInt(at: Int) -> UInt32 { return getInteger(at: at) } public func getLong(at: Int) -> Int64 { return getInteger(at: at) } public func getUnsignedLong(at: Int) -> UInt64 { return getInteger(at: at) } public func getVirtualTaleOffset(at: Int) -> Int { return Int(getShort(at: at)) } public func getOffset(at: Int) -> Int { return Int(getInt(at: at)) } public func getFloat(at: Int) -> Float { return getFloatingPoint(at: at) } public func getDouble(at: Int) -> Double { return getFloatingPoint(at: at) } public func getArray(at: Int, count: Int, withType: UInt8.Type) -> [UInt8]? { var bytes: [UInt8] = [UInt8](repeating: 0, count: count) copyBytes(to: &bytes, from: at ..< Data.Index(at + count)) return bytes } } // String helper to extract Character by index of a string extension String { subscript (i: Int) -> Character { return self[self.characters.index(self.startIndex, offsetBy: i)] } }
apache-2.0
da1a3dc0b8c5413cea9ce79ce333b436
26.956897
124
0.580019
3.83787
false
false
false
false
macc704/iKF
iKF/KFReference.swift
1
3161
// // KFReference.swift // iKF // // Created by Yoshiaki Matsuzawa on 2014-06-09. // Copyright (c) 2014 Yoshiaki Matsuzawa. All rights reserved. // import UIKit class KFReference: KFModel { let HIDDEN_BIT = 0x01; let LOCKED_BIT = 0x02; let SHOWINPLACE_BIT = 0x04; let OPERATABLE_BIT = 0x08; let BORDER_BIT = 0x10; let FITSCALE_BIT = 0x20; var post:KFPost?{ willSet{ unhook(); } didSet{ hook(); } }; var location = CGPoint(x:0, y:0); var width = CGFloat(0); var height = CGFloat(0); var rotation = CGFloat(0); var displayFlags = Int(0); override init(){ } deinit{ unhook(); post = nil; } func marge(another: KFReference) { location = another.location; width = another.width; height = another.height; rotation = another.rotation; displayFlags = another.displayFlags; } private func unhook(){ if(self.post != nil){ self.post!.detach(self); } } private func hook(){ if(self.post != nil){ self.post!.attach(self, selector: "postChanged"); } } func postChanged(){ self.notify(); } func isHidden() -> Bool{ return displayFlags & HIDDEN_BIT == HIDDEN_BIT; } func setHidden(hidden:Bool){ if(hidden){ displayFlags = displayFlags | HIDDEN_BIT; }else{ displayFlags = displayFlags & ~HIDDEN_BIT; } } func isLocked() -> Bool{ return displayFlags & LOCKED_BIT == LOCKED_BIT; } func setLocked(locked:Bool){ if(locked){ displayFlags = displayFlags | LOCKED_BIT; }else{ displayFlags = displayFlags & ~LOCKED_BIT; } } func isShowInPlace() -> Bool{ return displayFlags & SHOWINPLACE_BIT == SHOWINPLACE_BIT; } func setShowInPlace(showInPlace:Bool){ if(showInPlace){ displayFlags = displayFlags | SHOWINPLACE_BIT; }else{ displayFlags = displayFlags & ~SHOWINPLACE_BIT; } } func isOperatable() -> Bool{ return displayFlags & OPERATABLE_BIT == OPERATABLE_BIT; } func setOperatable(operatable:Bool){ if(operatable){ displayFlags = displayFlags | OPERATABLE_BIT; }else{ displayFlags = displayFlags & ~OPERATABLE_BIT; } } func isBorder() -> Bool{ return displayFlags & BORDER_BIT == BORDER_BIT; } func setBorder(border:Bool){ if(border){ displayFlags = displayFlags | BORDER_BIT; }else{ displayFlags = displayFlags & ~BORDER_BIT; } } func isFitScale() -> Bool{ return displayFlags & FITSCALE_BIT == FITSCALE_BIT; } func setFitScale(fitscale:Bool){ if(fitscale){ displayFlags = displayFlags | FITSCALE_BIT; }else{ displayFlags = displayFlags & ~FITSCALE_BIT; } } }
gpl-2.0
8a2620d62b0f062f3adc814337289a94
21.741007
65
0.534008
3.921836
false
false
false
false
loudnate/LoopKit
LoopKitUI/Views/RepeatingScheduleValueTableViewCell.swift
1
3236
// // RepeatingScheduleValueTableViewCell.swift // Naterade // // Created by Nathan Racklyeft on 2/6/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import UIKit protocol RepeatingScheduleValueTableViewCellDelegate: DatePickerTableViewCellDelegate { func repeatingScheduleValueTableViewCellDidUpdateValue(_ cell: RepeatingScheduleValueTableViewCell) } class RepeatingScheduleValueTableViewCell: DatePickerTableViewCell, UITextFieldDelegate { weak var delegate: RepeatingScheduleValueTableViewCellDelegate? var timeZone: TimeZone! { didSet { dateFormatter.timeZone = timeZone datePicker.timeZone = timeZone } } private lazy var dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .none dateFormatter.timeStyle = .short return dateFormatter }() override func updateDateLabel() { dateLabel.text = dateFormatter.string(from: date) } override func dateChanged(_ sender: UIDatePicker) { super.dateChanged(sender) delegate?.datePickerTableViewCellDidUpdateDate(self) } var value: Double = 0 { didSet { textField.text = valueNumberFormatter.string(from: value) } } var datePickerInterval: TimeInterval { return TimeInterval(minutes: Double(datePicker.minuteInterval)) } var isReadOnly = false { didSet { if isReadOnly, textField.isFirstResponder { textField.resignFirstResponder() } } } lazy var valueNumberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.minimumFractionDigits = 1 return formatter }() @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var unitLabel: UILabel! { didSet { // Setting this color in code because the nib isn't being applied correctly if #available(iOSApplicationExtension 13.0, *) { unitLabel.textColor = .secondaryLabel } } } @IBOutlet weak var textField: UITextField! { didSet { // Setting this color in code because the nib isn't being applied correctly if #available(iOSApplicationExtension 13.0, *) { textField.textColor = .label } } } var unitString: String? { get { return unitLabel.text } set { unitLabel.text = newValue } } // MARK: - UITextFieldDelegate func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return !isReadOnly } func textFieldDidBeginEditing(_ textField: UITextField) { DispatchQueue.main.async { textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument) } } func textFieldDidEndEditing(_ textField: UITextField) { value = valueNumberFormatter.number(from: textField.text ?? "")?.doubleValue ?? 0 delegate?.repeatingScheduleValueTableViewCellDidUpdateValue(self) } }
mit
7a204257915b288a51fad55023b28918
26.415254
127
0.646059
5.766488
false
false
false
false
HaloWang/Halo
Halo/Classes/UITextField+Halo.swift
1
1680
import UIKit public extension UITextField { @discardableResult func placeholder(_ placeholder: String) -> Self { self.placeholder = placeholder return self } /// 设定文本距离左侧的距离 @discardableResult func leftWidth(_ leftWidth: CGFloat) -> Self { leftView = UIView(frame: CGRect(x: 0, y: 0, width: leftWidth, height: 5)) leftViewMode = UITextFieldViewMode.always return self } @discardableResult func keyboardType(_ keyboardType: UIKeyboardType) -> Self { self.keyboardType = keyboardType return self } @discardableResult func secureTextEntry(_ secureTextEntry: Bool) -> Self { self.isSecureTextEntry = secureTextEntry return self } @discardableResult func returnKeyType(_ returnKeyType: UIReturnKeyType) -> Self { self.returnKeyType = returnKeyType return self } @discardableResult func delegate(_ delegate: UITextFieldDelegate) -> Self { self.delegate = delegate return self } } extension UITextField : HasText { public var h_text: String { get { return text ?? "" } set { text = newValue } } public var h_textColor: UIColor { get { return textColor ?? .black } set { textColor = newValue } } public var h_font: UIFont { get { return font! } set { font = newValue } } public var h_textAlignment: NSTextAlignment { get { return textAlignment } set { textAlignment = newValue } } }
mit
a41d4e51e1f709b1b7a7b80fb11acfb3
19.219512
75
0.580217
4.949254
false
false
false
false
Noobish1/KeyedMapper
KeyedMapperTests/Extensions/KeyedMapper/KeyedMapper+MappableSpec.swift
1
4946
import Quick import Nimble @testable import KeyedMapper private struct SubModel: Mappable { fileprivate enum Key: String, JSONKey { case stringProperty } fileprivate let stringProperty: String fileprivate init(map: KeyedMapper<SubModel>) throws { try self.stringProperty = map.from(.stringProperty) } } private struct Model: Mappable { fileprivate enum Key: String, JSONKey { case mappableProperty } fileprivate let mappableProperty: SubModel fileprivate init(map: KeyedMapper<Model>) throws { try self.mappableProperty = map.from(.mappableProperty) } } private struct ModelWithArrayProperty: Mappable { fileprivate enum Key: String, JSONKey { case arrayMappableProperty } fileprivate let arrayMappableProperty: [SubModel] fileprivate init(map: KeyedMapper<ModelWithArrayProperty>) throws { try self.arrayMappableProperty = map.from(.arrayMappableProperty) } } private struct ModelWithTwoDArrayProperty: Mappable { fileprivate enum Key: String, JSONKey { case twoDArrayMappableProperty } fileprivate let twoDArrayMappableProperty: [[SubModel]] fileprivate init(map: KeyedMapper<ModelWithTwoDArrayProperty>) throws { try self.twoDArrayMappableProperty = map.from(.twoDArrayMappableProperty) } } class KeyedMapper_MappableSpec: QuickSpec { override func spec() { describe("from<T: Mappable> -> T") { it("should map correctly") { let field = Model.Key.mappableProperty let expectedValue = [SubModel.Key.stringProperty.stringValue: ""] let dict: NSDictionary = [field.stringValue: expectedValue] let mapper = KeyedMapper(JSON: dict, type: Model.self) let model: SubModel = try! mapper.from(field) expect(model).toNot(beNil()) } } describe("from<T: Mappable> -> [T]") { it("should map correctly") { let field = ModelWithArrayProperty.Key.arrayMappableProperty let expectedValue = [[SubModel.Key.stringProperty.stringValue: ""]] let dict: NSDictionary = [field.stringValue: expectedValue] let mapper = KeyedMapper(JSON: dict, type: ModelWithArrayProperty.self) let models: [SubModel] = try! mapper.from(field) expect(models).toNot(beNil()) expect(models.count) == expectedValue.count } } describe("from<T: Mappable> -> [[T]]") { it("should map correctly") { let field = ModelWithTwoDArrayProperty.Key.twoDArrayMappableProperty let expectedValue = [[[SubModel.Key.stringProperty.rawValue: ""]]] let dict: NSDictionary = [field.stringValue: expectedValue] let mapper = KeyedMapper(JSON: dict, type: ModelWithTwoDArrayProperty.self) let models: [[SubModel]] = try! mapper.from(field) expect(models).toNot(beNil()) expect(models.count) == expectedValue.count } } describe("optionalFrom<T: Mappable> -> T?") { it("should map correctly") { let field = Model.Key.mappableProperty let expectedValue = [SubModel.Key.stringProperty.stringValue: ""] let dict: NSDictionary = [field.rawValue: expectedValue] let mapper = KeyedMapper(JSON: dict, type: Model.self) let model: SubModel? = mapper.optionalFrom(field) expect(model).toNot(beNil()) } } describe("optionalFrom<T: Mappable> -> [T]?") { it("should map correctly") { let field = ModelWithArrayProperty.Key.arrayMappableProperty let expectedValue = [[SubModel.Key.stringProperty.stringValue: ""]] let dict: NSDictionary = [field.stringValue: expectedValue] let mapper = KeyedMapper(JSON: dict, type: ModelWithArrayProperty.self) let models: [SubModel]? = mapper.optionalFrom(field) expect(models).toNot(beNil()) expect(models?.count) == expectedValue.count } } describe("optionalFrom<T: Mappable> -> [[T]]?") { it("should map correctly") { let field = ModelWithTwoDArrayProperty.Key.twoDArrayMappableProperty let expectedValue = [[[SubModel.Key.stringProperty.stringValue: ""]]] let dict: NSDictionary = [field.stringValue: expectedValue] let mapper = KeyedMapper(JSON: dict, type: ModelWithTwoDArrayProperty.self) let models: [[SubModel]]? = mapper.optionalFrom(field) expect(models).toNot(beNil()) expect(models?.count) == expectedValue.count } } } }
mit
d9001e4bc411c0b8c7cfe5aa467852af
36.755725
91
0.609381
4.797284
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Util/BusStopDistance.swift
1
1355
// // BusStationDistance.swift // SASAbus // // Copyright (C) 2011-2015 Raiffeisen Online GmbH (Norman Marmsoler, Jürgen Sprenger, Aaron Falk) <[email protected]> // // This file is part of SASAbus. // // SASAbus is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // SASAbus is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with SASAbus. If not, see <http://www.gnu.org/licenses/>. // import Foundation import CoreLocation class BusStopDistance { let distance: CLLocationDistance! let busStop: BBusStop! init(busStop: BBusStop, distance: CLLocationDistance) { self.busStop = busStop self.distance = distance } } extension BusStopDistance: Hashable { var hashValue: Int { return busStop.family } public static func ==(lhs: BusStopDistance, rhs: BusStopDistance) -> Bool { return lhs.busStop.family == rhs.busStop.family } }
gpl-3.0
352cf3b6581b78896a9dfa4e8f9a4306
28.434783
118
0.711226
4.017804
false
false
false
false
cp3hnu/Bricking
Bricking/Source/NSLayoutYAxisAnchor+OP.swift
1
1892
// // NSLayoutYAxisAnchor+OP.swift // Bricking-iOS // // Created by CP3 on 2018/6/14. // Copyright © 2018年 CP3. All rights reserved. // import Foundation #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif public typealias CPLayoutYAxisAnchor = CPLayoutAnchor<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> public typealias PriorityYAxisAnchor = PriorityAnchor<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> // MARK: - NSLayoutYAxisAnchor => PriorityYAxisAnchor extension NSLayoutYAxisAnchor { static public func !! (left: NSLayoutYAxisAnchor, right: LayoutPriority) -> PriorityYAxisAnchor { return PriorityYAxisAnchor(anchor: CPLayoutYAxisAnchor(anchor: left), priority: right) } } // MARK: - NSLayoutYAxisAnchor => CPLayoutYAxisAnchor public extension NSLayoutYAxisAnchor { static func + (left: NSLayoutYAxisAnchor, right: CGFloat) -> CPLayoutYAxisAnchor { return CPLayoutYAxisAnchor(anchor: left, constant: right) } static func + (left: CGFloat, right: NSLayoutYAxisAnchor) -> CPLayoutYAxisAnchor { return right + left } static func - (left: NSLayoutYAxisAnchor, right: CGFloat) -> CPLayoutYAxisAnchor { return left + (-right) } } // MARK: - NSLayoutYAxisAnchor ~ NSLayoutYAxisAnchor public extension NSLayoutYAxisAnchor { @discardableResult static func == (left: NSLayoutYAxisAnchor, right: NSLayoutYAxisAnchor) -> NSLayoutConstraint { return left == CPLayoutYAxisAnchor(anchor: right) } @discardableResult static func >= (left: NSLayoutYAxisAnchor, right: NSLayoutYAxisAnchor) -> NSLayoutConstraint { return left >= CPLayoutYAxisAnchor(anchor: right) } @discardableResult static func <= (left: NSLayoutYAxisAnchor, right: NSLayoutYAxisAnchor) -> NSLayoutConstraint { return left <= CPLayoutYAxisAnchor(anchor: right) } }
mit
762c8950206c0049c0cbfa2fd904f1c6
31.568966
101
0.722075
4.971053
false
false
false
false
gkaimakas/SwiftValidatorsReactiveExtensions
Example/SwiftValidatorsReactiveExtensions/Views/HeaderView/HeaderView.swift
1
1472
// // HeaderView.swift // SwiftValidatorsReactiveExtensions // // Created by George Kaimakas on 05/04/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import ReactiveCocoa import ReactiveSwift import Result import UIKit public class HeaderView: UIView { @IBOutlet weak var leftImageView: UIImageView! @IBOutlet weak var rightImageView: UIImageView! @IBOutlet weak var leftImageViewXConstraint: NSLayoutConstraint! @IBOutlet weak var rightImageViewXConstraint: NSLayoutConstraint! var viewModel: FormViewModel? { didSet { guard let viewModel = viewModel else { return } } } public override init(frame: CGRect) { super.init(frame: frame) initializeView() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializeView() } func initializeView() { let view: UIView? = Bundle(for: HeaderView.self) .loadNibNamed(String(describing: HeaderView.self), owner: self, options: nil)?.last as? UIView if let view = view { view.frame = self.bounds view.autoresizingMask = [.flexibleHeight, .flexibleWidth] addSubview(view) } self.backgroundColor = UIColor.clear self.leftImageView.bordered(width: 1) self.rightImageView.bordered(width: 1) } }
mit
ba6573350a22459f4682d85fd80fadc1
26.240741
106
0.635622
4.903333
false
false
false
false
rectinajh/leetCode_Swift
Find Minimum in Rotated Sorted Array II/Find Minimum in Rotated Sorted Array II/Find Minimum in Rotated Sorted Array II.swift
1
2336
// // Find Minimum in Rotated Sorted Array II.swift // Find Minimum in Rotated Sorted Array II // // Created by hua on 16/8/31. // Copyright © 2016年 212. All rights reserved. // import Foundation /** Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. 这道题目中元素会有重复的情况出现。不过正是因为这个条件的出现,影响到了算法的时间复杂度。原来我们是依靠中间和边缘元素的大小关系,来判断哪一半是不受rotate影响,仍然有序的。而现在因为重复的出现,如果我们遇到中间和边缘相等的情况,我们就无法判断哪边有序,因为哪边都有可能有序。假设原数组是{1,2,3,3,3,3,3},那么旋转之后有可能是{3,3,3,3,3,1,2},或者{3,1,2,3,3,3,3},这样的我们判断左边缘和中心的时候都是3,我们并不知道应该截掉哪一半。解决的办法只能是对边缘移动一步,直到边缘和中间不在相等或者相遇,这就导致了会有不能切去一半的可能。所以最坏情况就会出现每次移动一步,总共移动n此,算法的时间复杂度变成O(n)。 * Question Link: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ * Primary idea: Classic Binary Search,二分法 * * Time Complexity: O(logn), Space Complexity: O(1) * inspired by http://blog.csdn.net/linhuanmars/article/details/40449299 */ class Solution { func findMin(nums:[Int]) -> Int { var left = 0 var right = nums.count - 1 var mid = 0 var minVal = Int.max if nums.count == 0 { return 0 } while left + 1 < right { mid = (right - left) / 2 + left if nums[mid] > nums[left] { minVal = min(nums[left], minVal) left = mid + 1 } else if nums[mid] < nums[left] { minVal = min(nums[mid], minVal) right = mid - 1 } else { left += 1 } } return min(minVal, nums[left], nums[right]) } }
mit
296adec6b4006b85c9d34704127c57b7
32.074074
328
0.613445
2.897727
false
false
false
false
vsouza/horizon
Sources/Logger.swift
1
447
import Log import StandardOutputAppender let logger = Logger(name: "horizon-logger", appender: StandardOutputAppender(), levels: .all) extension Horizon { public func success(url: String?) { var msg = "passed √" if let target = url { msg = "\(target) \(msg)" } logger.info(msg) } public func fail(url: String?) { var msg = "fail x" if let target = url { msg = "\(target) \(msg)" } logger.warning(msg) } }
mit
8ac8f0e9f209d81ef1c4d0db2b6b0ea3
20.190476
93
0.622472
3.047945
false
false
false
false
gribozavr/swift
stdlib/public/core/OutputStream.swift
1
20605
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims //===----------------------------------------------------------------------===// // Input/Output interfaces //===----------------------------------------------------------------------===// /// A type that can be the target of text-streaming operations. /// /// You can send the output of the standard library's `print(_:to:)` and /// `dump(_:to:)` functions to an instance of a type that conforms to the /// `TextOutputStream` protocol instead of to standard output. Swift's /// `String` type conforms to `TextOutputStream` already, so you can capture /// the output from `print(_:to:)` and `dump(_:to:)` in a string instead of /// logging it to standard output. /// /// var s = "" /// for n in 1...5 { /// print(n, terminator: "", to: &s) /// } /// // s == "12345" /// /// Conforming to the TextOutputStream Protocol /// =========================================== /// /// To make your custom type conform to the `TextOutputStream` protocol, /// implement the required `write(_:)` method. Functions that use a /// `TextOutputStream` target may call `write(_:)` multiple times per writing /// operation. /// /// As an example, here's an implementation of an output stream that converts /// any input to its plain ASCII representation before sending it to standard /// output. /// /// struct ASCIILogger: TextOutputStream { /// mutating func write(_ string: String) { /// let ascii = string.unicodeScalars.lazy.map { scalar in /// scalar == "\n" /// ? "\n" /// : scalar.escaped(asASCII: true) /// } /// print(ascii.joined(separator: ""), terminator: "") /// } /// } /// /// The `ASCIILogger` type's `write(_:)` method processes its string input by /// escaping each Unicode scalar, with the exception of `"\n"` line returns. /// By sending the output of the `print(_:to:)` function to an instance of /// `ASCIILogger`, you invoke its `write(_:)` method. /// /// let s = "Hearts ♡ and Diamonds ♢" /// print(s) /// // Prints "Hearts ♡ and Diamonds ♢" /// /// var asciiLogger = ASCIILogger() /// print(s, to: &asciiLogger) /// // Prints "Hearts \u{2661} and Diamonds \u{2662}" public protocol TextOutputStream { mutating func _lock() mutating func _unlock() /// Appends the given string to the stream. mutating func write(_ string: String) mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) } extension TextOutputStream { public mutating func _lock() {} public mutating func _unlock() {} public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) { write(String._fromASCII(buffer)) } } /// A source of text-streaming operations. /// /// Instances of types that conform to the `TextOutputStreamable` protocol can /// write their value to instances of any type that conforms to the /// `TextOutputStream` protocol. The Swift standard library's text-related /// types, `String`, `Character`, and `Unicode.Scalar`, all conform to /// `TextOutputStreamable`. /// /// Conforming to the TextOutputStreamable Protocol /// ===================================== /// /// To add `TextOutputStreamable` conformance to a custom type, implement the /// required `write(to:)` method. Call the given output stream's `write(_:)` /// method in your implementation. public protocol TextOutputStreamable { /// Writes a textual representation of this instance into the given output /// stream. func write<Target: TextOutputStream>(to target: inout Target) } /// A type with a customized textual representation. /// /// Types that conform to the `CustomStringConvertible` protocol can provide /// their own representation to be used when converting an instance to a /// string. The `String(describing:)` initializer is the preferred way to /// convert an instance of *any* type to a string. If the passed instance /// conforms to `CustomStringConvertible`, the `String(describing:)` /// initializer and the `print(_:)` function use the instance's custom /// `description` property. /// /// Accessing a type's `description` property directly or using /// `CustomStringConvertible` as a generic constraint is discouraged. /// /// Conforming to the CustomStringConvertible Protocol /// ================================================== /// /// Add `CustomStringConvertible` conformance to your custom types by defining /// a `description` property. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library: /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(p) /// // Prints "Point(x: 21, y: 30)" /// /// After implementing the `description` property and declaring /// `CustomStringConvertible` conformance, the `Point` type provides its own /// custom representation. /// /// extension Point: CustomStringConvertible { /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// print(p) /// // Prints "(21, 30)" public protocol CustomStringConvertible { /// A textual representation of this instance. /// /// Calling this property directly is discouraged. Instead, convert an /// instance of any type to a string by using the `String(describing:)` /// initializer. This initializer works with any type, and uses the custom /// `description` property for types that conform to /// `CustomStringConvertible`: /// /// struct Point: CustomStringConvertible { /// let x: Int, y: Int /// /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// let p = Point(x: 21, y: 30) /// let s = String(describing: p) /// print(s) /// // Prints "(21, 30)" /// /// The conversion of `p` to a string in the assignment to `s` uses the /// `Point` type's `description` property. var description: String { get } } /// A type that can be represented as a string in a lossless, unambiguous way. /// /// For example, the integer value 1050 can be represented in its entirety as /// the string "1050". /// /// The description property of a conforming type must be a value-preserving /// representation of the original value. As such, it should be possible to /// re-create an instance from its string representation. public protocol LosslessStringConvertible: CustomStringConvertible { /// Instantiates an instance of the conforming type from a string /// representation. init?(_ description: String) } /// A type with a customized textual representation suitable for debugging /// purposes. /// /// Swift provides a default debugging textual representation for any type. /// That default representation is used by the `String(reflecting:)` /// initializer and the `debugPrint(_:)` function for types that don't provide /// their own. To customize that representation, make your type conform to the /// `CustomDebugStringConvertible` protocol. /// /// Because the `String(reflecting:)` initializer works for instances of *any* /// type, returning an instance's `debugDescription` if the value passed /// conforms to `CustomDebugStringConvertible`, accessing a type's /// `debugDescription` property directly or using /// `CustomDebugStringConvertible` as a generic constraint is discouraged. /// /// - Note: Calling the `dump(_:_:_:_:)` function and printing in the debugger /// uses both `String(reflecting:)` and `Mirror(reflecting:)` to collect /// information about an instance. If you implement /// `CustomDebugStringConvertible` conformance for your custom type, you may /// want to consider providing a custom mirror by implementing /// `CustomReflectable` conformance, as well. /// /// Conforming to the CustomDebugStringConvertible Protocol /// ======================================================= /// /// Add `CustomDebugStringConvertible` conformance to your custom types by /// defining a `debugDescription` property. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library: /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(reflecting: p)) /// // Prints "p: Point = { /// // x = 21 /// // y = 30 /// // }" /// /// After adding `CustomDebugStringConvertible` conformance by implementing the /// `debugDescription` property, `Point` provides its own custom debugging /// representation. /// /// extension Point: CustomDebugStringConvertible { /// var debugDescription: String { /// return "Point(x: \(x), y: \(y))" /// } /// } /// /// print(String(reflecting: p)) /// // Prints "Point(x: 21, y: 30)" public protocol CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. /// /// Calling this property directly is discouraged. Instead, convert an /// instance of any type to a string by using the `String(reflecting:)` /// initializer. This initializer works with any type, and uses the custom /// `debugDescription` property for types that conform to /// `CustomDebugStringConvertible`: /// /// struct Point: CustomDebugStringConvertible { /// let x: Int, y: Int /// /// var debugDescription: String { /// return "(\(x), \(y))" /// } /// } /// /// let p = Point(x: 21, y: 30) /// let s = String(reflecting: p) /// print(s) /// // Prints "(21, 30)" /// /// The conversion of `p` to a string in the assignment to `s` uses the /// `Point` type's `debugDescription` property. var debugDescription: String { get } } //===----------------------------------------------------------------------===// // Default (ad-hoc) printing //===----------------------------------------------------------------------===// @_silgen_name("swift_EnumCaseName") internal func _getEnumCaseName<T>(_ value: T) -> UnsafePointer<CChar>? @_silgen_name("swift_OpaqueSummary") internal func _opaqueSummary(_ metadata: Any.Type) -> UnsafePointer<CChar>? /// Do our best to print a value that cannot be printed directly. @_semantics("optimize.sil.specialize.generic.never") internal func _adHocPrint_unlocked<T, TargetStream: TextOutputStream>( _ value: T, _ mirror: Mirror, _ target: inout TargetStream, isDebugPrint: Bool ) { func printTypeName(_ type: Any.Type) { // Print type names without qualification, unless we're debugPrint'ing. target.write(_typeName(type, qualified: isDebugPrint)) } if let displayStyle = mirror.displayStyle { switch displayStyle { case .optional: if let child = mirror.children.first { _debugPrint_unlocked(child.1, &target) } else { _debugPrint_unlocked("nil", &target) } case .tuple: target.write("(") var first = true for (label, value) in mirror.children { if first { first = false } else { target.write(", ") } if let label = label { if !label.isEmpty && label[label.startIndex] != "." { target.write(label) target.write(": ") } } _debugPrint_unlocked(value, &target) } target.write(")") case .struct: printTypeName(mirror.subjectType) target.write("(") var first = true for (label, value) in mirror.children { if let label = label { if first { first = false } else { target.write(", ") } target.write(label) target.write(": ") _debugPrint_unlocked(value, &target) } } target.write(")") case .enum: if let cString = _getEnumCaseName(value), let caseName = String(validatingUTF8: cString) { // Write the qualified type name in debugPrint. if isDebugPrint { printTypeName(mirror.subjectType) target.write(".") } target.write(caseName) } else { // If the case name is garbage, just print the type name. printTypeName(mirror.subjectType) } if let (_, value) = mirror.children.first { if Mirror(reflecting: value).displayStyle == .tuple { _debugPrint_unlocked(value, &target) } else { target.write("(") _debugPrint_unlocked(value, &target) target.write(")") } } default: target.write(_typeName(mirror.subjectType)) } } else if let metatypeValue = value as? Any.Type { // Metatype printTypeName(metatypeValue) } else { // Fall back to the type or an opaque summary of the kind if let cString = _opaqueSummary(mirror.subjectType), let opaqueSummary = String(validatingUTF8: cString) { target.write(opaqueSummary) } else { target.write(_typeName(mirror.subjectType, qualified: true)) } } } @usableFromInline @_semantics("optimize.sil.specialize.generic.never") internal func _print_unlocked<T, TargetStream: TextOutputStream>( _ value: T, _ target: inout TargetStream ) { // Optional has no representation suitable for display; therefore, // values of optional type should be printed as a debug // string. Check for Optional first, before checking protocol // conformance below, because an Optional value is convertible to a // protocol if its wrapped type conforms to that protocol. // Note: _isOptional doesn't work here when T == Any, hence we // use a more elaborate formulation: if _openExistential(type(of: value as Any), do: _isOptional) { let debugPrintable = value as! CustomDebugStringConvertible debugPrintable.debugDescription.write(to: &target) return } if case let streamableObject as TextOutputStreamable = value { streamableObject.write(to: &target) return } if case let printableObject as CustomStringConvertible = value { printableObject.description.write(to: &target) return } if case let debugPrintableObject as CustomDebugStringConvertible = value { debugPrintableObject.debugDescription.write(to: &target) return } let mirror = Mirror(reflecting: value) _adHocPrint_unlocked(value, mirror, &target, isDebugPrint: false) } //===----------------------------------------------------------------------===// // `debugPrint` //===----------------------------------------------------------------------===// @_semantics("optimize.sil.specialize.generic.never") @inline(never) public func _debugPrint_unlocked<T, TargetStream: TextOutputStream>( _ value: T, _ target: inout TargetStream ) { if let debugPrintableObject = value as? CustomDebugStringConvertible { debugPrintableObject.debugDescription.write(to: &target) return } if let printableObject = value as? CustomStringConvertible { printableObject.description.write(to: &target) return } if let streamableObject = value as? TextOutputStreamable { streamableObject.write(to: &target) return } let mirror = Mirror(reflecting: value) _adHocPrint_unlocked(value, mirror, &target, isDebugPrint: true) } @_semantics("optimize.sil.specialize.generic.never") internal func _dumpPrint_unlocked<T, TargetStream: TextOutputStream>( _ value: T, _ mirror: Mirror, _ target: inout TargetStream ) { if let displayStyle = mirror.displayStyle { // Containers and tuples are always displayed in terms of their element // count switch displayStyle { case .tuple: let count = mirror.children.count target.write(count == 1 ? "(1 element)" : "(\(count) elements)") return case .collection: let count = mirror.children.count target.write(count == 1 ? "1 element" : "\(count) elements") return case .dictionary: let count = mirror.children.count target.write(count == 1 ? "1 key/value pair" : "\(count) key/value pairs") return case .`set`: let count = mirror.children.count target.write(count == 1 ? "1 member" : "\(count) members") return default: break } } if let debugPrintableObject = value as? CustomDebugStringConvertible { debugPrintableObject.debugDescription.write(to: &target) return } if let printableObject = value as? CustomStringConvertible { printableObject.description.write(to: &target) return } if let streamableObject = value as? TextOutputStreamable { streamableObject.write(to: &target) return } if let displayStyle = mirror.displayStyle { switch displayStyle { case .`class`, .`struct`: // Classes and structs without custom representations are displayed as // their fully qualified type name target.write(_typeName(mirror.subjectType, qualified: true)) return case .`enum`: target.write(_typeName(mirror.subjectType, qualified: true)) if let cString = _getEnumCaseName(value), let caseName = String(validatingUTF8: cString) { target.write(".") target.write(caseName) } return default: break } } _adHocPrint_unlocked(value, mirror, &target, isDebugPrint: true) } //===----------------------------------------------------------------------===// // OutputStreams //===----------------------------------------------------------------------===// internal struct _Stdout: TextOutputStream { internal init() {} internal mutating func _lock() { _swift_stdlib_flockfile_stdout() } internal mutating func _unlock() { _swift_stdlib_funlockfile_stdout() } internal mutating func write(_ string: String) { if string.isEmpty { return } var string = string _ = string.withUTF8 { utf8 in _swift_stdlib_fwrite_stdout(utf8.baseAddress!, 1, utf8.count) } } } extension String: TextOutputStream { /// Appends the given string to this string. /// /// - Parameter other: A string to append. public mutating func write(_ other: String) { self += other } public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) { self._guts.append(_StringGuts(buffer, isASCII: true)) } } //===----------------------------------------------------------------------===// // Streamables //===----------------------------------------------------------------------===// extension String: TextOutputStreamable { /// Writes the string into the given output stream. /// /// - Parameter target: An output stream. public func write<Target: TextOutputStream>(to target: inout Target) { target.write(self) } } extension Character: TextOutputStreamable { /// Writes the character into the given output stream. /// /// - Parameter target: An output stream. public func write<Target: TextOutputStream>(to target: inout Target) { target.write(String(self)) } } extension Unicode.Scalar: TextOutputStreamable { /// Writes the textual representation of the Unicode scalar into the given /// output stream. /// /// - Parameter target: An output stream. public func write<Target: TextOutputStream>(to target: inout Target) { target.write(String(Character(self))) } } /// A hook for playgrounds to print through. public var _playgroundPrintHook: ((String) -> Void)? = nil internal struct _TeeStream< L: TextOutputStream, R: TextOutputStream >: TextOutputStream { internal init(left: L, right: R) { self.left = left self.right = right } internal var left: L internal var right: R /// Append the given `string` to this stream. internal mutating func write(_ string: String) { left.write(string); right.write(string) } internal mutating func _lock() { left._lock(); right._lock() } internal mutating func _unlock() { right._unlock(); left._unlock() } }
apache-2.0
2221d82fab9e9ef9dcc20a34a6c595c7
33.271215
80
0.615818
4.600625
false
false
false
false
LipliStyle/Liplis-iOS
Liplis/LiplisFileManager.swift
1
4429
// // LiplisFileManager.swift // Liplis // // iOSのファイルにアクセスするためのクラス // //アップデート履歴 // 2015/05/03 ver0.1.0 作成 // 2015/05/09 ver1.0.0 リリース // 2015/05/16 ver1.4.0 リファクタリング // // Created by sachin on 2015/05/03. // Copyright (c) 2015年 sachin. All rights reserved. // import Foundation struct LiplisFileManager { /** 指定のフォルダにある全てのファイルを取得する */ internal static func getAllFileNamesFromDocumentPath(path: String) -> Array<String> { //初期リスト let resList : Array<String> = [] //結果を返す return getAllFileNamesFromTargetPath(path,inList: resList) } internal static func getAllFileNamesFromTargetPath(path: String, inList : Array<String>) -> Array<String> { //指定パスのファイル/ディレクトリのリスト let contents : Array<String>! = contentsOfDirectoryAtPath(path) //バッファリスト作成 var resList : Array<String> = [] //親リスト追加 resList.addRange(inList) //ファイルなら、コンテンツがnilとなる if contents == nil { //ファイルパスを設定して返す resList.append(path) return resList } else { //再帰的にファイルを取り出す for p in contents { resList = getAllFileNamesFromTargetPath(path + "/" + p,inList: resList) } } return resList } /** ドキュメントパスにある全てのファイルを取得する(サブフォルダも含めて全て取得) */ internal static func getAllFileNamesFromDocumentPath() -> Array<String> { //ドキュメントパスの取得 let documentsPath = getDocumentRoot() //結果を返す return getAllFileNamesFromDocumentPath(documentsPath) } /** ドキュメントパスにある全てのファイルを取得する フォルダ上のみ */ internal static func getFileNamesDocumentPath() -> Array<String>! { return contentsOfDirectoryAtPath(getDocumentRoot()) } /** 指定のフォルダにある全てのファイルを取得する (最もプリミティブな処理) */ internal static func contentsOfDirectoryAtPath(path: String) -> Array<String>!{ var error: NSError? = nil let fileManager = NSFileManager.defaultManager() let contents: [AnyObject]? do { contents = try fileManager.contentsOfDirectoryAtPath(path) } catch let error1 as NSError { error = error1 contents = nil } if contents == nil { return nil } else { let filenames = contents as! Array<String> return filenames } } /** 共有フォルダのパスを返す */ internal static func getDocumentRoot()->String { //共有フォルダをバックアップさせない設定 notBackupSetting() return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] } /** 共有フォルダのURLを返す */ internal static func getDocumentRootUrl()->NSURL { //共有フォルダをバックアップさせない設定 notBackupSetting() let fileManager = NSFileManager.defaultManager() return fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] //配下フォルダへのアクセス例 //url2 = url.URLByAppendingPathComponent("LiliRenew/skin.xml") } /** バックアップさせない設定 */ internal static func notBackupSetting() { let fileManager = NSFileManager.defaultManager() var error : NSError? let url : NSURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] do { //バックアップさせない! try url.setResourceValue(true, forKey : NSURLIsExcludedFromBackupKey) } catch let error1 as NSError { error = error1 } } }
mit
f2bb03f318c0d5e05f16fd18089b7292
24.383562
109
0.583536
3.975322
false
false
false
false
mluedke2/karenina
Karenina/ResultParser.swift
1
2047
// // ResultParser.swift // Karenina // // Created by Matt Luedke on 10/3/15. // Copyright © 2015 Razeware. All rights reserved. // import Foundation import ResearchKit struct ResultParser { static func findSoundFile(result: ORKTaskResult) -> NSURL? { if let results = result.results where results.count > 3, let stepResult = results[3] as? ORKStepResult, let subResults = stepResult.results where subResults.count > 0, let fileResult = subResults[0] as? ORKFileResult { return fileResult.fileURL } return nil } static func findWalkHeartFiles(result: ORKTaskResult) -> [NSURL] { var urls = [NSURL]() if let results = result.results where results.count > 4, let walkResult = results[3] as? ORKStepResult, let restResult = results[4] as? ORKStepResult { for result in walkResult.results! { if let result = result as? ORKFileResult, let fileUrl = result.fileURL { urls.append(fileUrl) } } for result in restResult.results! { if let result = result as? ORKFileResult, let fileUrl = result.fileURL { urls.append(fileUrl) } } } return urls } static func findClip(task: ORKTask?) -> MusicClip? { if let task = task as? ORKOrderedTask where task.steps.count > 1, let musicStep = task.steps[1] as? MusicStep { return musicStep.clip } else { return nil } } static func findMusicHeartFiles(result: ORKTaskResult) -> NSURL? { if let results = result.results where results.count > 1, let heartResult = results[1] as? ORKStepResult, let heartSubresults = heartResult.results where heartSubresults.count > 0, let fileResult = heartSubresults[0] as? ORKFileResult, let fileURL = fileResult.fileURL { return fileURL } return nil } }
mit
6d78b0062d62b423d53cf49713c4c16d
22.25
68
0.594819
4.298319
false
false
false
false
jbsohn/SteelSidekick
macOS/SteelSidekick/ScaleViewController.swift
1
1571
// // ScaleViewController.swift // SteelSidekick // // Created by John Sohn on 1/18/17. // Copyright © 2017 John Sohn. All rights reserved. // import Cocoa protocol ScaleViewControllerDelegate { func didUpdateScaleSettings(); } class ScaleViewController: NSViewController { @IBOutlet weak var scaleButton: NSPopUpButton! @IBOutlet weak var rootNoteButton: NSPopUpButton! // var delegate: ScaleViewControllerDelegate; override func viewDidLoad() { super.viewDidLoad() let sguitar = SGuitar.sharedInstance(); let scaleOptions = sguitar?.getScaleOptions(); let rootNote = (scaleOptions?.scaleRootNoteValue)!; // init scales let scales = (sguitar?.getScaleNames()) as! [String]; self.scaleButton.removeAllItems(); self.scaleButton.addItems(withTitles:scales); //self.scaleButton.selectItem(at:Int(rootNote)); // init root notes self.rootNoteButton.removeAllItems(); for i in NOTE_VALUE_C...NOTE_VALUE_B { let noteName = SGuitar.getNoteNameSharpFlat(Int32(i)); self.rootNoteButton.addItem(withTitle:noteName!); } self.rootNoteButton.selectItem(at:Int(rootNote)); } override func viewDidDisappear() { let sguitar = SGuitar.sharedInstance(); let scaleOptions = sguitar?.getScaleOptions(); let scaleRootNoteValue = self.rootNoteButton.indexOfSelectedItem scaleOptions?.scaleRootNoteValue = Int32(scaleRootNoteValue); } }
gpl-2.0
082e2a0a5dcb709ef2350cfbef1e5c95
28.074074
72
0.659873
4.460227
false
false
false
false
PiXeL16/PasswordTextField
PasswordTextField/RegexRule.swift
1
1281
// // RegexRule.swift // PasswordTextField // // Created by Chris Jimenez on 2/11/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // import Foundation /// Basic structure that represent a Regex Rule open class RegexRule : Ruleable { /// Default regex fileprivate var REGEX: String = "^(?=.*?[A-Z]).{8,}$" /// Error message fileprivate var message : String /** Default constructor - parameter regex: regex of the rule - parameter message: errorMessage - returns: <#return value description#> */ public init(regex: String, errorMessage: String = "Invalid Regular Expression"){ self.REGEX = regex self.message = errorMessage } /** Validates if the rule works matches - parameter value: String value to validate againts a rule - returns: if the rule is valid or not */ open func validate(_ value: String) -> Bool { let test = NSPredicate(format: "SELF MATCHES %@", self.REGEX) return test.evaluate(with: value) } /** Returns the error message - returns: <#return value description#> */ open func errorMessage() -> String { return message } }
mit
efcd0c5e18fe6f6abc6c1815354b7d2c
21.857143
84
0.592969
4.688645
false
false
false
false
kosicki123/eidolon
Kiosk/Auction Listings/ListingsViewController.swift
1
19037
import UIKit import SystemConfiguration import ARAnalytics let HorizontalMargins = 65 let VerticalMargins = 26 let MasonryCellIdentifier = "MasonryCell" let TableCellIdentifier = "TableCell" public class ListingsViewController: UIViewController { public var allowAnimations = true public var auctionID = AppSetup.sharedState.auctionID public var syncInterval = SyncInterval public var pageSize = 10 public var schedule = { (signal: RACSignal, scheduler: RACScheduler) -> RACSignal in return signal.deliverOn(scheduler) } public dynamic var saleArtworks = [SaleArtwork]() public dynamic var sortedSaleArtworks = [SaleArtwork]() public dynamic var cellIdentifier = MasonryCellIdentifier @IBOutlet public var stagingFlag: UIImageView! @IBOutlet public var loadingSpinner: Spinner! lazy var collectionView: UICollectionView = { var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: ListingsViewController.masonryLayout()) collectionView.backgroundColor = UIColor.clearColor() collectionView.dataSource = self collectionView.delegate = self collectionView.alwaysBounceVertical = true collectionView.registerClass(MasonryCollectionViewCell.self, forCellWithReuseIdentifier: MasonryCellIdentifier) collectionView.registerClass(TableCollectionViewCell.self, forCellWithReuseIdentifier: TableCellIdentifier) collectionView.allowsSelection = false return collectionView }() lazy public var switchView: SwitchView = { return SwitchView(buttonTitles: SwitchValues.allSwitchValues().map{$0.name.uppercaseString}) }() class public func instantiateFromStoryboard(storyboard: UIStoryboard) -> ListingsViewController { return storyboard.viewControllerWithID(.AuctionListings) as ListingsViewController } // Recursively calls itself with page+1 until the count of the returned array is < pageSize // Sends new response objects to the subject. func recursiveListingsRequestSignal(auctionID: String, page: Int, subject: RACSubject) -> RACSignal { let artworksEndpoint: ArtsyAPI = ArtsyAPI.AuctionListings(id: auctionID) return XAppRequest(artworksEndpoint, parameters: ["size": self.pageSize, "page": page]).filterSuccessfulStatusCodes().mapJSON().flattenMap({ (object) -> RACStream! in if let array = object as? Array<AnyObject> { let count = countElements(array) subject.sendNext(object) if count < self.pageSize { subject.sendCompleted() return nil } else { return self.recursiveListingsRequestSignal(auctionID, page: page+1, subject: subject) } } // Should never happen subject.sendCompleted() return nil }) } // Fetches all pages of the auction func allListingsRequestSignal(auctionID: String) -> RACSignal { let initialSubject = RACReplaySubject() return schedule(schedule(recursiveListingsRequestSignal(auctionID, page: 1, subject: initialSubject).ignoreValues(), RACScheduler(priority: RACSchedulerPriorityDefault)).then { initialSubject }.collect().map({ (object) -> AnyObject! in // object is an array of arrays (thanks to collect()). We need to flatten it. let array = object as? Array<Array<AnyObject>> return reduce(array ?? [], Array<AnyObject>(), +) }).mapToObjectArray(SaleArtwork.self).catch({ (error) -> RACSignal! in logger.error("Sale Artworks: Error handling thing: \(error.artsyServerError())") return RACSignal.empty() }), RACScheduler.mainThreadScheduler()) } func recurringListingsRequestSignal(auctionID: String) -> RACSignal { let recurringSignal = RACSignal.interval(syncInterval, onScheduler: RACScheduler.mainThreadScheduler()).startWith(NSDate()).takeUntil(rac_willDeallocSignal()) return recurringSignal.filter({ [weak self] (_) -> Bool in self?.shouldSync() ?? false }).doNext({ (date) -> Void in println("Syncing on \(date)") }).map ({ [weak self] (_) -> AnyObject! in return self?.allListingsRequestSignal(auctionID) ?? RACSignal.empty() }).switchToLatest().map({ [weak self] (newSaleArtworks) -> AnyObject! in if self == nil { return [] // Now safe to use self! } let currentSaleArtworks = self!.saleArtworks func update(currentSaleArtworks: [SaleArtwork], newSaleArtworks: [SaleArtwork]) -> Bool { assert(countElements(currentSaleArtworks) == countElements(newSaleArtworks), "Arrays' counts must be equal.") // Updating the currentSaleArtworks is easy. First we sort both according to the same criteria // Because we assume that their length is the same, we just do a linear scane through and // copy values from the new to the old. let sortedCurentSaleArtworks = currentSaleArtworks.sorted(sortById) let sortedNewSaleArtworks = newSaleArtworks.sorted(sortById) let count = countElements(sortedCurentSaleArtworks) for var i = 0; i < count; i++ { if currentSaleArtworks[i].id == newSaleArtworks[i].id { currentSaleArtworks[i].updateWithValues(newSaleArtworks[i]) } else { // Failure: the list was the same size but had different artworks return false } } return true } // So we want to do here is pretty simple – if the existing and new arrays are of the same length, // then update the individual values in the current array and return the existing value. // If the array's length has changed, then we pass through the new array if let newSaleArtworks = newSaleArtworks as? Array<SaleArtwork> { if countElements(newSaleArtworks) == countElements(currentSaleArtworks) { if update(currentSaleArtworks, newSaleArtworks) { return currentSaleArtworks } } } return newSaleArtworks }) } func shouldSync() -> Bool { return self.presentedViewController == nil && self.navigationController?.topViewController == self } // Adapted from https://github.com/FUKUZAWA-Tadashi/FHCCommander/blob/67c67757ee418a106e0ce0c0820459299b3d77bb/fhcc/Convenience.swift#L33-L44 func getSSID() -> String? { let interfaces: CFArray! = CNCopySupportedInterfaces()?.takeUnretainedValue() if interfaces == nil { return nil } let if0: UnsafePointer<Void>? = CFArrayGetValueAtIndex(interfaces, 0) if if0 == nil { return nil } let interfaceName: CFStringRef = unsafeBitCast(if0!, CFStringRef.self) let dictionary = CNCopyCurrentNetworkInfo(interfaceName)?.takeUnretainedValue() as NSDictionary? if dictionary == nil { return nil } return dictionary?[kCNNetworkInfoKeySSID as String] as? String } func detectDevelopment() -> Bool { var developmentEnvironment = false #if (arch(i386) || arch(x86_64)) && os(iOS) developmentEnvironment = true #else if let ssid = getSSID() { let developmentSSIDs = ["Ash's Wi-Fi Network", "Art.sy", "Artsy2"] as NSArray developmentEnvironment = developmentSSIDs.containsObject(ssid) } #endif return developmentEnvironment } override public func viewDidLoad() { super.viewDidLoad() if detectDevelopment() { let flagImageName = AppSetup.sharedState.useStaging ? "StagingFlag" : "ProductionFlag" stagingFlag.image = UIImage(named: flagImageName) stagingFlag.hidden = AppSetup.sharedState.isTesting } else { stagingFlag.hidden = AppSetup.sharedState.useStaging == false } // Add subviews view.addSubview(switchView) view.insertSubview(collectionView, belowSubview: loadingSpinner) // Set up reactive bindings RAC(self, "saleArtworks") <~ recurringListingsRequestSignal(auctionID) RAC(self, "loadingSpinner.hidden") <~ RACObserve(self, "saleArtworks").mapArrayLengthExistenceToBool() let gridSelectedSignal = switchView.selectedIndexSignal.map { (index) -> AnyObject! in switch index as Int { case SwitchValues.Grid.rawValue: return true default: return false } } RAC(self, "cellIdentifier") <~ gridSelectedSignal.map({ (gridSelected) -> AnyObject! in switch gridSelected as Bool { case true: return MasonryCellIdentifier default: return TableCellIdentifier } }) let artworkAndLayoutSignal = RACSignal.combineLatest([RACObserve(self, "saleArtworks").distinctUntilChanged(), switchView.selectedIndexSignal, gridSelectedSignal]).map({ [weak self] in let tuple = $0 as RACTuple let saleArtworks = tuple.first as [SaleArtwork] let selectedIndex = tuple.second as Int let gridSelected: AnyObject! = tuple.third let layout = { () -> UICollectionViewLayout in switch gridSelected as Bool { case true: return ListingsViewController.masonryLayout() default: return ListingsViewController.tableLayout(CGRectGetWidth(self?.switchView.frame ?? CGRectZero)) } }() if let switchValue = SwitchValues(rawValue: selectedIndex) { return RACTuple(objectsFromArray: [switchValue.sortSaleArtworks(saleArtworks), layout]) } else { // Necessary for compiler – won't execute return RACTuple(objectsFromArray: [saleArtworks, layout]) } }) RAC(self, "sortedSaleArtworks") <~ artworkAndLayoutSignal.map { ($0 as RACTuple).first }.doNext({ [weak self] in let sortedSaleArtworks = $0 as [SaleArtwork] self?.collectionView.reloadData() if countElements(sortedSaleArtworks as [SaleArtwork]) > 0 { // Need to dispatch, since the changes in the CV's model aren't imediate dispatch_async(dispatch_get_main_queue()) { self?.collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.Top, animated: false) return } } }) artworkAndLayoutSignal.map { ($0 as RACTuple).second }.subscribeNext { [weak self] (layout) -> Void in // Need to explicitly call animated: false and reload to avoid animation self?.collectionView.setCollectionViewLayout(layout as UICollectionViewLayout, animated: false) return } } override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue == .ShowSaleArtworkDetails { let saleArtwork = sender as SaleArtwork! let detailsViewController = segue.destinationViewController as SaleArtworkDetailsViewController detailsViewController.saleArtwork = saleArtwork ARAnalytics.event("Show Artwork Details", withProperties: ["id": saleArtwork.artwork.id]) } } override public func viewWillAppear(animated: Bool) { let switchHeightPredicate = "\(switchView.intrinsicContentSize().height)" switchView.constrainHeight(switchHeightPredicate) switchView.alignTop("\(64+VerticalMargins)", leading: "\(HorizontalMargins)", bottom: nil, trailing: "-\(HorizontalMargins)", toView: view) collectionView.constrainTopSpaceToView(switchView, predicate: "0") collectionView.alignTop(nil, leading: "0", bottom: "0", trailing: "0", toView: view) collectionView.contentInset = UIEdgeInsetsMake(40, 0, 80, 0) } } // MARK: - Collection View extension ListingsViewController: UICollectionViewDataSource, UICollectionViewDelegate, ARCollectionViewMasonryLayoutDelegate { public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return countElements(sortedSaleArtworks) } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as UICollectionViewCell if let listingsCell = cell as? ListingsCollectionViewCell { // TODO: Ideally we should disable when auction runs out // listingsCell.bidButton.enabled = countdownManager.auctionFinishedSignal listingsCell.saleArtwork = saleArtworkAtIndexPath(indexPath) let bidSignal: RACSignal = listingsCell.bidWasPressedSignal.takeUntil(cell.rac_prepareForReuseSignal) bidSignal.subscribeNext({ [weak self] (_) -> Void in if let saleArtwork = self?.saleArtworkAtIndexPath(indexPath) { self?.presentModalForSaleArtwork(saleArtwork) } }) let moreInfoSignal = listingsCell.moreInfoSignal.takeUntil(cell.rac_prepareForReuseSignal) moreInfoSignal.subscribeNext({ [weak self] (_) -> Void in if let saleArtwork = self?.saleArtworkAtIndexPath(indexPath) { self?.presentDetailsForSaleArtwork(saleArtwork) } }) } return cell } public func presentDetailsForSaleArtwork(saleArtwork: SaleArtwork) { performSegueWithIdentifier(SegueIdentifier.ShowSaleArtworkDetails.rawValue, sender: saleArtwork) } public func presentModalForSaleArtwork(saleArtwork: SaleArtwork) { ARAnalytics.event("Bid Button Tapped") let storyboard = UIStoryboard.fulfillment() let containerController = storyboard.instantiateInitialViewController() as FulfillmentContainerViewController containerController.allowAnimations = allowAnimations if let internalNav:FulfillmentNavigationController = containerController.internalNavigationController() { internalNav.auctionID = self.auctionID internalNav.bidDetails.saleArtwork = saleArtwork } // Present the VC, then once it's ready trigger it's own showing animations // TODO: This is messy. Clean up somehow – responder chain? navigationController?.parentViewController?.presentViewController(containerController, animated: false) { containerController.viewDidAppearAnimation(containerController.allowAnimations) } } public func collectionView(collectionView: UICollectionView!, layout collectionViewLayout: ARCollectionViewMasonryLayout!, variableDimensionForItemAtIndexPath indexPath: NSIndexPath!) -> CGFloat { return MasonryCollectionViewCell.heightForSaleArtwork(saleArtworkAtIndexPath(indexPath)) } } // MARK: Private Methods private extension ListingsViewController { // MARK: Class methods class func masonryLayout() -> ARCollectionViewMasonryLayout { var layout = ARCollectionViewMasonryLayout(direction: .Vertical) layout.itemMargins = CGSizeMake(65, 20) layout.dimensionLength = CGFloat(MasonryCollectionViewCellWidth) layout.rank = 3 layout.contentInset = UIEdgeInsetsMake(0.0, 0.0, CGFloat(VerticalMargins), 0.0) return layout } class func tableLayout(width: CGFloat) -> UICollectionViewFlowLayout { let layout = UICollectionViewFlowLayout() TableCollectionViewCell.Width = width layout.itemSize = CGSizeMake(width, TableCollectionViewCell.Height) layout.minimumLineSpacing = 0.0 return layout } // MARK: Instance methods func saleArtworkAtIndexPath(indexPath: NSIndexPath) -> SaleArtwork { return sortedSaleArtworks[indexPath.item]; } } // MARK: - Sorting Functions func leastBidsSort(lhs: SaleArtwork, rhs: SaleArtwork) -> Bool { return (lhs.bidCount ?? 0) < (rhs.bidCount ?? 0) } func mostBidsSort(lhs: SaleArtwork, rhs: SaleArtwork) -> Bool { return !leastBidsSort(lhs, rhs) } func lowestCurrentBidSort(lhs: SaleArtwork, rhs: SaleArtwork) -> Bool { return (lhs.highestBidCents ?? 0) < (rhs.highestBidCents ?? 0) } func highestCurrentBidSort(lhs: SaleArtwork, rhs: SaleArtwork) -> Bool { return !lowestCurrentBidSort(lhs, rhs) } func alphabeticalSort(lhs: SaleArtwork, rhs: SaleArtwork) -> Bool { return lhs.artwork.sortableArtistID().caseInsensitiveCompare(rhs.artwork.sortableArtistID()) == .OrderedAscending } func sortById(lhs: SaleArtwork, rhs: SaleArtwork) -> Bool { return lhs.id.caseInsensitiveCompare(rhs.id) == .OrderedAscending } // MARK: - Switch Values enum SwitchValues: Int { case Grid = 0 case LeastBids case MostBids case HighestCurrentBid case LowestCurrentBid case Alphabetical var name: String { switch self { case .Grid: return "Grid" case .LeastBids: return "Least Bids" case .MostBids: return "Most Bids" case .HighestCurrentBid: return "Highest Bid" case .LowestCurrentBid: return "Lowest Bid" case .Alphabetical: return "A–Z" } } func sortSaleArtworks(saleArtworks: [SaleArtwork]) -> [SaleArtwork] { switch self { case Grid: return saleArtworks case LeastBids: return saleArtworks.sorted(leastBidsSort) case MostBids: return saleArtworks.sorted(mostBidsSort) case HighestCurrentBid: return saleArtworks.sorted(highestCurrentBidSort) case LowestCurrentBid: return saleArtworks.sorted(lowestCurrentBidSort) case Alphabetical: return saleArtworks.sorted(alphabeticalSort) } } static func allSwitchValues() -> [SwitchValues] { return [Grid, LeastBids, MostBids, HighestCurrentBid, LowestCurrentBid, Alphabetical] } }
mit
4766c49d0546f59607df409cc760f5f1
41.761798
243
0.649587
5.590188
false
false
false
false
tehprofessor/SwiftyFORM
Example/Other/OptionsViewController.swift
1
2508
// MIT license. Copyright (c) 2015 SwiftyFORM. All rights reserved. import UIKit import SwiftyFORM class OptionsViewController: FormViewController { override func populate(builder: FormBuilder) { builder.navigationTitle = "Options" builder.toolbarMode = .None builder += SectionHeaderTitleFormItem().title("Options") builder += adoptBitcoin builder += exploreSpace builder += worldPeace builder += stopGlobalWarming builder += SectionFormItem() builder += randomizeButton } lazy var adoptBitcoin: OptionPickerFormItem = { let instance = OptionPickerFormItem() instance.title("Adopt Bitcoin?").placeholder("required") instance.append("Strongly disagree").append("Disagree").append("Neutral").append("Agree").append("Strongly agree") instance.selectOptionWithTitle("Neutral") return instance }() lazy var exploreSpace: OptionPickerFormItem = { let instance = OptionPickerFormItem() instance.title("Explore Space?").placeholder("required") instance.append("Strongly disagree").append("Disagree").append("Neutral").append("Agree").append("Strongly agree") instance.selectOptionWithTitle("Neutral") return instance }() lazy var worldPeace: OptionPickerFormItem = { let instance = OptionPickerFormItem() instance.title("World Peace?").placeholder("required") instance.append("Strongly disagree").append("Disagree").append("Neutral").append("Agree").append("Strongly agree") instance.selectOptionWithTitle("Neutral") return instance }() lazy var stopGlobalWarming: OptionPickerFormItem = { let instance = OptionPickerFormItem() instance.title("Stop Global Warming?").placeholder("required") instance.append("Strongly disagree").append("Disagree").append("Neutral").append("Agree").append("Strongly agree") instance.selectOptionWithTitle("Neutral") return instance }() lazy var randomizeButton: ButtonFormItem = { let instance = ButtonFormItem() instance.title("Randomize") instance.action = { [weak self] in self?.randomize() } return instance }() func assignRandomOption(optionField: OptionPickerFormItem) { var selected: OptionRowModel? = nil let options = optionField.options if options.count > 0 { let i = randomInt(0, options.count) if i < options.count { selected = options[i] } } optionField.selected = selected } func randomize() { assignRandomOption(adoptBitcoin) assignRandomOption(exploreSpace) assignRandomOption(worldPeace) assignRandomOption(stopGlobalWarming) } }
mit
d0df107d025754701be871e7430f999c
31.571429
116
0.744418
3.91875
false
false
false
false
grigaci/WallpapersCollectionView
WallpapersCollectionView/WallpapersCollectionView/Classes/GUI/TransylvaniaPhotos/BITransylvaniaPhotosViewController.swift
1
2734
// // BITransylvaniaPhotosViewController.swift // WallpapersCollectionView // // Created by Bogdan Iusco on 8/9/14. // Copyright (c) 2014 Grigaci. All rights reserved. // import UIKit class BITransylvaniaPhotosViewController: UICollectionViewController { let kCollectionViewCellID = NSStringFromClass(BITransylvaniaPhotosViewController.self) override init() { var layout = UICollectionViewFlowLayout() layout.estimatedItemSize = CGSizeMake(100, 100) layout.sectionInset = UIEdgeInsetsMake(10, 20, 10, 20) super.init(collectionViewLayout: layout) self.collectionView.dataSource = self self.collectionView.delegate = self self.title = BILocalizedString("Transylvania Photos") } convenience required init(coder: NSCoder) { self.init() } override func viewDidLoad() { super.viewDidLoad() self.collectionView.registerClass(BIPhotoCollectionViewCell.self, forCellWithReuseIdentifier: kCollectionViewCellID) } override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return BIModelManager.sharedInstance.locationsCount } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { var location = BIModelManager.sharedInstance.locationAtIndex(section) var countPhotos = (location != nil) ? location?.photos.count : 0 return countPhotos! } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell:BIPhotoCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(kCollectionViewCellID, forIndexPath: indexPath) as BIPhotoCollectionViewCell var location = BIModelManager.sharedInstance.locationAtIndex(indexPath.section) var photo = location?.photos.objectAtIndex(indexPath.row) as BIPhoto cell.photo = photo return cell } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { var cell:BIPhotoCollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath) as BIPhotoCollectionViewCell var photoViewController: BIPhotoViewController = BIPhotoViewController(nibName: nil, bundle: nil) // Set photo photoViewController.photo = cell.photo // Set title var location = BIModelManager.sharedInstance.locationAtIndex(indexPath.section) photoViewController.title = location?.name // Push it on nav stack self.navigationController?.pushViewController(photoViewController, animated: true) } }
mit
83ae24f3f88dc6ba86010e0fb8b4f43e
40.424242
175
0.742868
5.468
false
false
false
false
mcudich/TemplateKit
Examples/TodoMVC/Source/Todos.swift
1
1947
// // TodosModel.swift // Example // // Created by Matias Cudich on 9/20/16. // Copyright © 2016 Matias Cudich. All rights reserved. // import Foundation struct TodoItem: Hashable { var id: String = UUID().uuidString var title: String = "" var completed: Bool = false var hashValue: Int { var result = 17 result = 31 * result + id.hashValue return result } init(title: String) { self.title = title } } func ==(lhs: TodoItem, rhs: TodoItem) -> Bool { return lhs.id == rhs.id && lhs.title == rhs.title && lhs.completed == rhs.completed } typealias ChangeHandler = () -> Void class Todos: Equatable { var todos = [TodoItem]() var changes = [ChangeHandler]() init() {} func subscribe(handler: @escaping ChangeHandler) { changes.append(handler) } func inform() { for change in changes { change() } } func addTodo(title: String) { todos.append(TodoItem(title: title)) inform() } func toggleAll(checked: Bool) { for (index, _) in todos.enumerated() { todos[index].completed = checked } inform() } func toggle(id: String) { for (index, todo) in todos.enumerated() { if todo.id == id { todos[index].completed = !todo.completed break } } inform() } func move(from sourceIndex: Int, to destinationIndex: Int) { let todo = todos.remove(at: sourceIndex) todos.insert(todo, at: destinationIndex) inform() } func destroy(id: String) { todos = todos.filter { todoItem in todoItem.id != id } inform() } func save(id: String, title: String) { for (index, todo) in todos.enumerated() { if todo.id == id { todos[index].title = title break } } inform() } func clearCompleted() { todos = todos.filter { !$0.completed } inform() } } func ==(lhs: Todos, rhs: Todos) -> Bool { return lhs.todos == rhs.todos }
mit
8846d4b32fe1f653f9060a9832f8726e
17.711538
85
0.597122
3.630597
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/ThemeableTextView.swift
1
3761
import UIKit import WMF public protocol ThemeableTextViewDelegate: NSObjectProtocol { func textViewDidChange(_ textView: UITextView) func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool } @objc(WMFThemeableTextView) class ThemeableTextView: SetupView { let textView = UITextView() fileprivate let underlineView = UIView() fileprivate let underlineHeight: CGFloat = 1 fileprivate let clearButton = UIButton() public weak var delegate: ThemeableTextViewDelegate? var showsClearButton: Bool = false override open func setup() { super.setup() textView.delegate = self underlineView.translatesAutoresizingMaskIntoConstraints = false clearButton.translatesAutoresizingMaskIntoConstraints = false clearButton.setImage(UIImage(named: "clear-mini"), for: .normal) clearButton.addTarget(self, action: #selector(clearButtonPressed), for: .touchUpInside) addSubview(clearButton) clearButton.isHidden = true let clearButtonWidthConstraint = clearButton.widthAnchor.constraint(equalToConstant: 32) clearButton.addConstraints([clearButtonWidthConstraint]) wmf_addSubview(textView, withConstraintsToEdgesWithInsets: UIEdgeInsets(top: 0, left: 0, bottom: underlineHeight, right: clearButtonWidthConstraint.constant - 8)) addSubview(underlineView) let leadingConstraint = leadingAnchor.constraint(equalTo: underlineView.leadingAnchor) let trailingConstraint = trailingAnchor.constraint(equalTo: underlineView.trailingAnchor) let heightConstraint = underlineView.heightAnchor.constraint(equalToConstant: underlineHeight) let bottomConstraint = bottomAnchor.constraint(equalTo: underlineView.bottomAnchor) let centerYConstraint = clearButton.centerYAnchor.constraint(equalTo: textView.centerYAnchor) let clearButtonTrailingConstraint = clearButton.trailingAnchor.constraint(equalTo: trailingAnchor) addConstraints([leadingConstraint, trailingConstraint, bottomConstraint, clearButtonTrailingConstraint]) underlineView.addConstraint(heightConstraint) centerYConstraint.isActive = true } override open var intrinsicContentSize: CGSize { return CGSize(width: UIViewNoIntrinsicMetric, height: textView.contentSize.height + underlineHeight) } fileprivate func updateClearButton() { clearButton.isHidden = showsClearButton ? textView.text.isEmpty : true } @objc fileprivate func clearButtonPressed() { textView.text = "" textViewDidChange(textView) } } extension ThemeableTextView: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { invalidateIntrinsicContentSize() updateClearButton() delegate?.textViewDidChange(textView) } func textViewDidEndEditing(_ textView: UITextView) { clearButton.isHidden = true } func textViewDidBeginEditing(_ textView: UITextView) { updateClearButton() } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { return delegate?.textView(textView, shouldChangeTextIn: range, replacementText: text) ?? false } } extension ThemeableTextView: Themeable { func apply(theme: Theme) { underlineView.backgroundColor = theme.colors.border textView.backgroundColor = theme.colors.paperBackground textView.textColor = theme.colors.primaryText backgroundColor = theme.colors.paperBackground clearButton.tintColor = theme.colors.secondaryText } }
mit
0eb70bde9a0134122c70edd441e827a6
39.44086
170
0.729061
6.0176
false
false
false
false
adrfer/swift
test/Parse/c_function_pointers.swift
14
2964
// RUN: %target-swift-frontend -parse -verify -module-name main %s func global() -> Int { return 0 } struct S { static func staticMethod() -> Int { return 0 } } class C { static func staticMethod() -> Int { return 0 } class func classMethod() -> Int { return 0 } } if true { var x = 0 func local() -> Int { return 0 } func localWithContext() -> Int { return x } let a: @convention(c) () -> Int = global let a2: @convention(c) () -> Int = main.global let b: @convention(c) () -> Int = { 0 } let c: @convention(c) () -> Int = local // Can't convert a closure with context to a C function pointer let d: @convention(c) () -> Int = { x } // expected-error{{cannot be formed from a closure that captures context}} let d2: @convention(c) () -> Int = { [x] in x } // expected-error{{cannot be formed from a closure that captures context}} let e: @convention(c) () -> Int = localWithContext // expected-error{{cannot be formed from a local function that captures context}} // Can't convert a closure value to a C function pointer let global2 = global let f: @convention(c) () -> Int = global2 // expected-error{{can only be formed from a reference to a 'func' or a literal closure}} let globalBlock: @convention(block) () -> Int = global let g: @convention(c) () -> Int = globalBlock // expected-error{{can only be formed from a reference to a 'func' or a literal closure}} // Can convert a function pointer to a block or closure, or assign to another // C function pointer let h: @convention(c) () -> Int = a let i: @convention(block) () -> Int = a let j: () -> Int = a // Can't convert a C function pointer from a method. // TODO: Could handle static methods. let k: @convention(c) () -> Int = S.staticMethod // expected-error{{}} let m: @convention(c) () -> Int = C.staticMethod // expected-error{{}} let n: @convention(c) () -> Int = C.classMethod // expected-error{{}} // <rdar://problem/22181714> Crash when typing "signal" let iuo_global: (() -> Int)! = global let p: (@convention(c) () -> Int)! = iuo_global // expected-error{{a C function pointer can only be formed from a reference to a 'func' or a literal closure}} func handler(callback: (@convention(c) () -> Int)!) {} handler(iuo_global) // expected-error{{a C function pointer can only be formed from a reference to a 'func' or a literal closure}} } class Generic<X : C> { func f<Y : C>(y: Y) { let _: @convention(c) () -> Int = { return 0 } let _: @convention(c) () -> Int = { return X.staticMethod() } // expected-error{{cannot be formed from a closure that captures generic parameters}} let _: @convention(c) () -> Int = { return Y.staticMethod() } // expected-error{{cannot be formed from a closure that captures generic parameters}} } } func genericFunc<T>(t: T) -> T { return t } let f: @convention(c) Int -> Int = genericFunc // expected-error{{cannot be formed from a reference to a generic function}}
apache-2.0
e9f05fcfc871ba607a13ce13c1077835
45.3125
160
0.646761
3.623472
false
false
false
false
modocache/ClassDumpFormatter.swift
ClassDumpFormatter.swift
1
8148
#!/usr/bin/env xcrun swift import Foundation // MARK: Helpers extension String { /// Splits a string into substrings, delineated by newline characters. func componentsSeparatedByNewlines() -> [String] { return (self as NSString).componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) } } extension NSMutableString { /// Returns a range that encompasses the entire string. var rangeOfEntireString: NSRange { return NSRange(location: 0, length: length) } /// Removes occurrences of "(" and ")". func removeParentheses() { let options = NSStringCompareOptions.CaseInsensitiveSearch replaceOccurrencesOfString("(", withString: "", options: options, range: rangeOfEntireString) replaceOccurrencesOfString(")", withString: "", options: options, range: rangeOfEntireString) } /// Replaces all whitespace " " with the given string. func replaceOccurencesOfWhitespaceWithString(string: String) { replaceOccurrencesOfString(" ", withString: string, options: NSStringCompareOptions.CaseInsensitiveSearch, range: rangeOfEntireString) } } extension NSString { /// Returns a boolean indicating whether a line begins with "@protocol" or "@interface". /// We naively assume that this means the line contains the beginning of a protocol /// or class declaration. var hasDeclarationPrefix: Bool { return hasPrefix("@protocol") || hasPrefix("@interface") } /// Splits a string into substrings, delineated by whitespace. var componentsSeparatedByWhitespace: [NSString] { return componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } var indexOfFirstOccurrenceOfColonCharacter: Array<NSString>.Index? { return componentsSeparatedByWhitespace.indexOf { $0.isEqualToString(":") } } var isProtocolDeclaration: Bool { return indexOfFirstOccurrenceOfColonCharacter == nil } var declarationName: String { let components = componentsSeparatedByWhitespace let componentsAfterKeyword = Array(components[1..<components.count]) let stringAfterKeyword = (componentsAfterKeyword as NSArray).componentsJoinedByString(" ") if isProtocolDeclaration { let stringAfterKeywordAndBeforeAngleBracket = stringAfterKeyword.componentsSeparatedByString(" <")[0] let name = NSMutableString(string: stringAfterKeywordAndBeforeAngleBracket) name.removeParentheses() name.replaceOccurencesOfWhitespaceWithString("+") return name as String } else { let colonIndex = Int(stringAfterKeyword.indexOfFirstOccurrenceOfColonCharacter!.value) return (Array(componentsAfterKeyword[0..<colonIndex]) as NSArray).componentsJoinedByString(" ") } } /// Returns a boolean indicating whether a line ends with "@end". /// We naively assume that this means the line ends a protocol or class declaration. var hasEndPrefix: Bool { return hasPrefix("@end") } } extension Array where Element : NSString { /// Joins an array of NSString elements into a single string /// using the specified newline separator. func joinWithNewlines(newlineCharacter: String = "\n") -> String { return (self as NSArray).componentsJoinedByString(newlineCharacter) } func mapDeclarations<TransformedValue>(closure: (linesInDeclaration: [NSString]) -> (TransformedValue)) { var inDeclaration = false var linesInDeclaration: [NSString] = [] for line in self { if line.hasDeclarationPrefix { inDeclaration = true } if inDeclaration { linesInDeclaration.append(line) } if line.hasEndPrefix { closure(linesInDeclaration: linesInDeclaration) inDeclaration = false linesInDeclaration.removeAll() } } } /// A header comment prepended to each file generated with this script. /// It includes copyright for class-dump, among other things. var classDumpHeader: String { let commentLines = filter { $0.hasPrefix("//") } let headerCommentLines = commentLines.filter { !$0.hasSuffix("properties") } return headerCommentLines.joinWithNewlines() } } /// Errors emitted when running ClassDumpFormatter. enum ClassDumpFormatterError: ErrorType { /// class-dump was unable to provide any data we could convert into a string. case InvalidData /// Could not create a file at the given URL. case InvalidFileURL(url: NSURL) } /// Runs class-dump on a Mach-O file. func classDump(executablePath: String, machOFilePath: String) throws -> String { let pipe = NSPipe() let fileHandle = pipe.fileHandleForReading let task = NSTask() task.launchPath = executablePath task.arguments = [machOFilePath] task.standardOutput = pipe task.launch() let data = fileHandle.readDataToEndOfFile() fileHandle.closeFile() if let output = NSString(data: data, encoding: NSUTF8StringEncoding) { return output as String } else { throw ClassDumpFormatterError.InvalidData } } struct ClassDumpDeclaration { let name: String let header: String let declaration: String var fileName: String { return "\(name).h" } var fileBody: String { return "\(declaration)\n" } } extension NSFileManager { func createFileForHeader(header: String, inDirectoryAtPath: String) throws { let url = NSURL(fileURLWithPath: inDirectoryAtPath).URLByAppendingPathComponent("class-dump-version.h") guard let path = url.path else { throw ClassDumpFormatterError.InvalidFileURL(url: url) } try header.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding) } func createFileForDeclaration(declaration: ClassDumpDeclaration, inDirectoryAtPath: String) throws { let url = NSURL(fileURLWithPath: inDirectoryAtPath).URLByAppendingPathComponent(declaration.fileName) guard let path = url.path else { throw ClassDumpFormatterError.InvalidFileURL(url: url) } try declaration.fileBody.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding) } } /// A parsed set of arguments for this script. struct ClassDumpFormatterArguments { /// The path to a class-dump executable. let classDumpExecutablePath: String /// The path to a Mach-O file to class-dump. let machOFilePath: String /// The directory the class-dumped files should be created in. let outputDirectoryPath: String } /// Parses the arguments passed to this script. Aborts if invalid arguments are given. func parseArguments(arguments: [String]) -> ClassDumpFormatterArguments { if arguments.count != 4 { print("Usage: ./ClassDumpFormatter.swift [path to class-dump executable] [path to Mach-O file] [path to output directory]") abort() } return ClassDumpFormatterArguments( classDumpExecutablePath: arguments[1], machOFilePath: arguments[2], outputDirectoryPath: arguments[3] ) } // MARK: Main // Parse arguments. Aborts if invalid arguments are given. let arguments = parseArguments(Process.arguments) // Create output directory if it doesn't already exist. let fileManager = NSFileManager.defaultManager() try fileManager.createDirectoryAtPath(arguments.outputDirectoryPath, withIntermediateDirectories: true, attributes: nil) // class-dump and generate header for each file. let output = try classDump(arguments.classDumpExecutablePath, machOFilePath: arguments.machOFilePath) let lines: [NSString] = output.componentsSeparatedByNewlines() let header = "\(lines.classDumpHeader)\n" try fileManager.createFileForHeader(header, inDirectoryAtPath: arguments.outputDirectoryPath) // For each protocol/class declaration in the dump... lines.mapDeclarations { linesInDeclaration in // ...generate the file name... guard let firstLine = linesInDeclaration.first else { print("Error enumerating declarations.") abort() } let declarationName = firstLine.declarationName // ...create the declaration struct... let declaration = ClassDumpDeclaration( name: declarationName, header: header, declaration: linesInDeclaration.joinWithNewlines() ) // ...and write it to a file. try! fileManager.createFileForDeclaration(declaration, inDirectoryAtPath: arguments.outputDirectoryPath) }
mit
1f0cf6aaa5ee152ca019b77c3cffda94
34.12069
138
0.745582
4.669341
false
false
false
false
megabitsenmzq/PomoNow-iOS
Old-1.0/PomoNow/PomoNow/TaskTableViewCell.swift
1
742
// // TaskTableViewCell.swift // PomoNow // // Created by Megabits on 15/10/17. // Copyright © 2015年 ScrewBox. All rights reserved. // import UIKit class TaskTableViewCell: UITableViewCell { @IBOutlet weak var taskLabel: UILabel! @IBOutlet weak var colorTag: UIView! @IBOutlet weak var times: UILabel! var tagColor = 0 { didSet { switch tagColor { case 0:colorTag.backgroundColor = colorRed case 1:colorTag.backgroundColor = colorYellow case 2:colorTag.backgroundColor = colorBlue case 3:colorTag.backgroundColor = colorPink case 4:colorTag.backgroundColor = colorGray default:break } } } }
mit
74427eb19db9775affd73df3f0ea1541
24.482759
57
0.619756
4.347059
false
false
false
false
ruslanskorb/CoreStore
CoreStoreTests/ListPublisherTests.swift
1
12445
// // ListPublisherTests.swift // CoreStore iOS // // Copyright © 2018 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #if canImport(UIKit) || canImport(AppKit) import XCTest @testable import CoreStore // MARK: - ListPublisherTests @available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *) class ListPublisherTests: BaseTestDataTestCase { @objc dynamic func test_ThatListPublishers_CanReceiveInsertNotifications() { self.prepareStack { (stack) in let observer = NSObject() let listPublisher = stack.publishList( From<TestEntity1>(), SectionBy(#keyPath(TestEntity1.testBoolean)), OrderBy<TestEntity1>(.ascending(#keyPath(TestEntity1.testBoolean)), .ascending(#keyPath(TestEntity1.testEntityID))) ) XCTAssertFalse(listPublisher.snapshot.hasSections()) XCTAssertFalse(listPublisher.snapshot.hasItems()) XCTAssertTrue(listPublisher.snapshot.itemIDs.isEmpty) let didChangeExpectation = self.expectation(description: "didChange") listPublisher.addObserver(observer) { listPublisher in XCTAssertTrue(listPublisher.snapshot.hasSections()) XCTAssertTrue(listPublisher.snapshot.hasItems()) XCTAssertEqual(listPublisher.snapshot.numberOfItems(inSectionIndex: 0), 1) didChangeExpectation.fulfill() } let saveExpectation = self.expectation(description: "save") stack.perform( asynchronous: { (transaction) -> Bool in let object = transaction.create(Into<TestEntity1>()) object.testBoolean = NSNumber(value: true) object.testNumber = NSNumber(value: 1) object.testDecimal = NSDecimalNumber(string: "1") object.testString = "nil:TestEntity1:1" object.testData = ("nil:TestEntity1:1" as NSString).data(using: String.Encoding.utf8.rawValue)! object.testDate = self.dateFormatter.date(from: "2000-01-01T00:00:00Z")! return transaction.hasChanges }, success: { (hasChanges) in XCTAssertTrue(hasChanges) saveExpectation.fulfill() }, failure: { _ in XCTFail() } ) self.waitAndCheckExpectations() withExtendedLifetime(listPublisher, {}) withExtendedLifetime(observer, {}) } } @objc dynamic func test_ThatListPublishers_CanReceiveUpdateNotifications() { self.prepareStack { (stack) in self.prepareTestDataForStack(stack) let observer = NSObject() let listPublisher = stack.publishList( From<TestEntity1>(), SectionBy(#keyPath(TestEntity1.testBoolean)), OrderBy<TestEntity1>(.ascending(#keyPath(TestEntity1.testBoolean)), .ascending(#keyPath(TestEntity1.testEntityID))) ) XCTAssertTrue(listPublisher.snapshot.hasSections()) XCTAssertEqual(listPublisher.snapshot.numberOfSections, 2) XCTAssertTrue(listPublisher.snapshot.hasItems()) XCTAssertTrue(listPublisher.snapshot.hasItems(inSectionIndex: 0)) XCTAssertEqual(listPublisher.snapshot.numberOfItems(inSectionIndex: 0), 2) XCTAssertEqual(listPublisher.snapshot.numberOfItems(inSectionIndex: 1), 3) let didChangeExpectation = self.expectation(description: "didChange") listPublisher.addObserver(observer) { listPublisher in XCTAssertTrue(listPublisher.snapshot.hasSections()) XCTAssertEqual(listPublisher.snapshot.numberOfSections, 2) XCTAssertTrue(listPublisher.snapshot.hasItems()) XCTAssertTrue(listPublisher.snapshot.hasItems(inSectionIndex: 0)) XCTAssertEqual(listPublisher.snapshot.numberOfItems(inSectionIndex: 0), 2) XCTAssertEqual(listPublisher.snapshot.numberOfItems(inSectionIndex: 1), 3) didChangeExpectation.fulfill() } let saveExpectation = self.expectation(description: "save") stack.perform( asynchronous: { (transaction) -> Bool in if let object = try transaction.fetchOne( From<TestEntity1>(), Where<TestEntity1>(#keyPath(TestEntity1.testEntityID), isEqualTo: 101)) { object.testNumber = NSNumber(value: 11) object.testDecimal = NSDecimalNumber(string: "11") object.testString = "nil:TestEntity1:11" object.testData = ("nil:TestEntity1:11" as NSString).data(using: String.Encoding.utf8.rawValue)! object.testDate = self.dateFormatter.date(from: "2000-01-11T00:00:00Z")! } else { XCTFail() } if let object = try transaction.fetchOne( From<TestEntity1>(), Where<TestEntity1>(#keyPath(TestEntity1.testEntityID), isEqualTo: 102)) { object.testNumber = NSNumber(value: 22) object.testDecimal = NSDecimalNumber(string: "22") object.testString = "nil:TestEntity1:22" object.testData = ("nil:TestEntity1:22" as NSString).data(using: String.Encoding.utf8.rawValue)! object.testDate = self.dateFormatter.date(from: "2000-01-22T00:00:00Z")! } else { XCTFail() } return transaction.hasChanges }, success: { (hasChanges) in XCTAssertTrue(hasChanges) saveExpectation.fulfill() }, failure: { _ in XCTFail() } ) self.waitAndCheckExpectations() withExtendedLifetime(listPublisher, {}) withExtendedLifetime(observer, {}) } } @objc dynamic func test_ThatListPublishers_CanReceiveMoveNotifications() { self.prepareStack { (stack) in self.prepareTestDataForStack(stack) let observer = NSObject() let listPublisher = stack.publishList( From<TestEntity1>(), SectionBy(#keyPath(TestEntity1.testBoolean)), OrderBy<TestEntity1>(.ascending(#keyPath(TestEntity1.testBoolean)), .ascending(#keyPath(TestEntity1.testEntityID))) ) XCTAssertTrue(listPublisher.snapshot.hasSections()) XCTAssertEqual(listPublisher.snapshot.numberOfSections, 2) XCTAssertTrue(listPublisher.snapshot.hasItems()) XCTAssertTrue(listPublisher.snapshot.hasItems(inSectionIndex: 0)) XCTAssertEqual(listPublisher.snapshot.numberOfItems(inSectionIndex: 0), 2) XCTAssertEqual(listPublisher.snapshot.numberOfItems(inSectionIndex: 1), 3) let didChangeExpectation = self.expectation(description: "didChange") listPublisher.addObserver(observer) { listPublisher in XCTAssertTrue(listPublisher.snapshot.hasSections()) XCTAssertEqual(listPublisher.snapshot.numberOfSections, 2) XCTAssertTrue(listPublisher.snapshot.hasItems()) XCTAssertTrue(listPublisher.snapshot.hasItems(inSectionIndex: 0)) XCTAssertEqual(listPublisher.snapshot.numberOfItems(inSectionIndex: 0), 1) XCTAssertEqual(listPublisher.snapshot.numberOfItems(inSectionIndex: 1), 4) didChangeExpectation.fulfill() } let saveExpectation = self.expectation(description: "save") stack.perform( asynchronous: { (transaction) -> Bool in if let object = try transaction.fetchOne( From<TestEntity1>(), Where<TestEntity1>(#keyPath(TestEntity1.testEntityID), isEqualTo: 102)) { object.testBoolean = NSNumber(value: true) } else { XCTFail() } return transaction.hasChanges }, success: { (hasChanges) in XCTAssertTrue(hasChanges) saveExpectation.fulfill() }, failure: { _ in XCTFail() } ) self.waitAndCheckExpectations() withExtendedLifetime(listPublisher, {}) withExtendedLifetime(observer, {}) } } @objc dynamic func test_ThatListPublishers_CanReceiveDeleteNotifications() { self.prepareStack { (stack) in self.prepareTestDataForStack(stack) let observer = NSObject() let listPublisher = stack.publishList( From<TestEntity1>(), SectionBy(#keyPath(TestEntity1.testBoolean)), OrderBy<TestEntity1>(.ascending(#keyPath(TestEntity1.testBoolean)), .ascending(#keyPath(TestEntity1.testEntityID))) ) XCTAssertTrue(listPublisher.snapshot.hasSections()) XCTAssertEqual(listPublisher.snapshot.numberOfSections, 2) XCTAssertTrue(listPublisher.snapshot.hasItems()) XCTAssertTrue(listPublisher.snapshot.hasItems(inSectionIndex: 0)) XCTAssertEqual(listPublisher.snapshot.numberOfItems(inSectionIndex: 0), 2) XCTAssertEqual(listPublisher.snapshot.numberOfItems(inSectionIndex: 1), 3) let didChangeExpectation = self.expectation(description: "didChange") listPublisher.addObserver(observer) { listPublisher in XCTAssertTrue(listPublisher.snapshot.hasSections()) XCTAssertEqual(listPublisher.snapshot.numberOfSections, 1) XCTAssertTrue(listPublisher.snapshot.hasItems()) XCTAssertTrue(listPublisher.snapshot.hasItems(inSectionIndex: 0)) XCTAssertEqual(listPublisher.snapshot.numberOfItems(inSectionIndex: 0), 3) didChangeExpectation.fulfill() } let saveExpectation = self.expectation(description: "save") stack.perform( asynchronous: { (transaction) -> Bool in let count = try transaction.deleteAll( From<TestEntity1>(), Where<TestEntity1>(#keyPath(TestEntity1.testBoolean), isEqualTo: false) ) XCTAssertEqual(count, 2) return transaction.hasChanges }, success: { (hasChanges) in XCTAssertTrue(hasChanges) saveExpectation.fulfill() }, failure: { _ in XCTFail() } ) self.waitAndCheckExpectations() } } } #endif
mit
b53af65d17cd3b46c05f1d87df4070b7
39.934211
131
0.592173
5.419861
false
true
false
false
fousa/trackkit
Sources/Classes/Parser/TrackTypeVersion.swift
1
2594
// // TrackTypeVersion.swift // Pods // // Created by Jelle Vandebeeck on 30/12/2016. // // import Foundation /// Returns the version of the file type. public enum TrackTypeVersion { /// A GPX formatted track with it's version. case gpx(String) /// A LOC formatted track with it's version. case loc(String) /// A NMEA formatted track. case nmea(String) /// A TCX formatted track with it's version. case tcx(String) /// A FIT formatted track with it's version. case fit(String) /// A TRACK formatted track with it's version. case track(String) // MARK: - Init /// Initialize the TrackTypeVersion by passing the file type and the version string. /// /// - parameter: the file type /// - parameter: the version string public init(type: TrackType, version: String?) throws { guard let version = version, TrackTypeVersion.validate(type: type, version: version) else { throw TrackParseError.invalidVersion } switch type { case .gpx: self = .gpx(version) case .loc: self = .loc(version) case .nmea: self = .nmea(version) case .tcx: self = .tcx(version) case .fit: self = .fit(version) case .track: self = .track(version) } } // MARK: - Version /// Return the version string for the file type. public var versionString: String? { switch self { case .gpx(let version): return version case .loc(let version): return version case .nmea(let version): return version case .tcx(let version): return version case .fit(let version): return version case .track(let version): return version } } // MARK: - Validation private static func validate(type: TrackType, version: String) -> Bool { var supportedVersions = [String]() switch type { case .gpx: supportedVersions = ["1.0", "1.1"] case .loc: supportedVersions = ["1.0"] case .nmea: supportedVersions = ["NMEA-0183"] case .tcx: supportedVersions = ["http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"] case .fit: supportedVersions = ["2.2"] case .track: supportedVersions = ["1.0"] } return supportedVersions.firstIndex(of: version) != nil } }
mit
49c842331dcea023d5a4939fad693260
24.683168
94
0.553971
4.367003
false
false
false
false
mattjgalloway/emoncms-ios
Pods/Former/Former/RowFormers/DatePickerRowFormer.swift
1
1753
// // DatePickerRowFormer.swift // Former-Demo // // Created by Ryo Aoyama on 8/1/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public protocol DatePickerFormableRow: FormableRow { func formDatePicker() -> UIDatePicker } open class DatePickerRowFormer<T: UITableViewCell> : BaseRowFormer<T>, Formable where T: DatePickerFormableRow { // MARK: Public open var date: Date = Date() public required init(instantiateType: Former.InstantiateType = .Class, cellSetup: ((T) -> Void)? = nil) { super.init(instantiateType: instantiateType, cellSetup: cellSetup) } @discardableResult public final func onDateChanged(_ handler: @escaping ((Date) -> Void)) -> Self { onDateChanged = handler return self } open override func initialized() { super.initialized() rowHeight = 216 } open override func cellInitialized(_ cell: T) { super.cellInitialized(cell) cell.formDatePicker().addTarget(self, action: #selector(DatePickerRowFormer.dateChanged(datePicker:)), for: .valueChanged) } open override func update() { super.update() cell.selectionStyle = .none let datePicker = cell.formDatePicker() datePicker.setDate(date, animated: false) datePicker.isUserInteractionEnabled = enabled datePicker.layer.opacity = enabled ? 1 : 0.5 } // MARK: Private private final var onDateChanged: ((Date) -> Void)? private dynamic func dateChanged(datePicker: UIDatePicker) { if enabled { let date = datePicker.date self.date = date onDateChanged?(date) } } }
mit
00ce85235fcfd6eb562a08691a3027ef
26.375
130
0.631279
4.684492
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Blog/Onboarding Questions Prompt/OnboardingQuestionsCoordinator.swift
1
3005
import Foundation import UIKit enum OnboardingOption: String { case stats case writing case notifications case reader case showMeAround = "show_me_around" case skip } extension NSNotification.Name { static let onboardingPromptWasDismissed = NSNotification.Name(rawValue: "OnboardingPromptWasDismissed") } class OnboardingQuestionsCoordinator { var navigationController: UINavigationController? var onDismiss: ((_ selection: OnboardingOption) -> Void)? func dismiss(selection: OnboardingOption) { onDismiss?(selection) } func track(_ event: WPAnalyticsEvent, option: OnboardingOption? = nil) { guard let option = option else { WPAnalytics.track(event) return } let properties = ["item": option.rawValue] WPAnalytics.track(event, properties: properties) } } // MARK: - Questions View Handling extension OnboardingQuestionsCoordinator { func questionsDisplayed() { track(.onboardingQuestionsDisplayed) } func questionsSkipped(option: OnboardingOption) { dismiss(selection: option) track(.onboardingQuestionsSkipped) } func didSelect(option: OnboardingOption) { guard option != .skip else { questionsSkipped(option: option) return } track(.onboardingQuestionsItemSelected, option: option) UserPersistentStoreFactory.instance().onboardingQuestionSelected = option // Check if notification's are already enabled // If they are just dismiss, if not then prompt UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { [weak self] settings in DispatchQueue.main.async { guard settings.authorizationStatus == .notDetermined, let self = self else { self?.dismiss(selection: option) return } let controller = OnboardingEnableNotificationsViewController(with: self, option: option) self.navigationController?.pushViewController(controller, animated: true) } }) } } // MARK: - Notifications Handling extension OnboardingQuestionsCoordinator { func notificationsDisplayed(option: OnboardingOption) { track(.onboardingEnableNotificationsDisplayed, option: option) UserPersistentStoreFactory.instance().onboardingNotificationsPromptDisplayed = true } func notificationsEnabledTapped(selection: OnboardingOption) { track(.onboardingEnableNotificationsEnableTapped, option: selection) InteractiveNotificationsManager.shared.requestAuthorization { authorized in DispatchQueue.main.async { self.dismiss(selection: selection) } } } func notificationsSkipped(selection: OnboardingOption) { track(.onboardingEnableNotificationsSkipped, option: selection) dismiss(selection: selection) } }
gpl-2.0
2fc80f485f8b86f4ef94c25ea4b97cfe
31.311828
111
0.681198
5.564815
false
false
false
false
PrashantMangukiya/SwiftParseDemo
Source-Xcode6/SwiftParseDemo/SwiftParseDemo/ForgotPasswordViewController.swift
2
4495
// // ForgotPasswordViewController.swift // SwiftParseDemo // // Created by Prashant on 10/09/15. // Copyright (c) 2015 PrashantKumar Mangukiya. All rights reserved. // import UIKit import Parse class ForgotPasswordViewController: UIViewController, UITextFieldDelegate { // outlet - activity indicator (spinner) @IBOutlet var spinner: UIActivityIndicatorView! // outlet and action - email @IBOutlet var emailText: UITextField! @IBAction func emailTextEditingChanged(sender: UITextField) { // validate input while entering text self.validateInput() } // outlet and action - submit button @IBOutlet var submitButton: UIButton! @IBAction func submitButtonAction(sender: UIButton) { // end editing i.e. close keyboard if open self.view.endEditing(true) // submit password reset request to parse self.doSubmit() } // action - close button @IBAction func closeButtonAction(sender: UIButton) { // close the curren screen self.dismissViewControllerAnimated(true, completion: nil) } // MARK: - view functions override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // stop spinner at view load self.spinner.stopAnimating() // set textfield delegate self.emailText.delegate = self // disable submit button self.submitButton.enabled = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - text field delegate function func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // MARK: - Utility functions private func doSubmit() -> Void { // show spinner for task in progress self.spinner.startAnimating() // collect email from text field. var email = self.emailText.text // Send asynchronous password reset request to parse server PFUser.requestPasswordResetForEmailInBackground(email, block: { (success,error) -> Void in // stop the spinner self.spinner.stopAnimating() // if error then show message. if error != nil { self.showAlertMessage(alertTitle: "Error", alertMessage: error!.localizedDescription ) }else{ // show sucess message and close screen when Ok button presssed. let alertCtrl = UIAlertController(title: "Success", message: "Password reset instruction email has been sent to " + email , preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { (action ) -> Void in // close password resetscreen self.dismissViewControllerAnimated( true, completion: nil) }) alertCtrl.addAction(okAction) self.showViewController(alertCtrl, sender: self) } }) } // validate input data, disable sign in button if any input not valid. private func validateInput() -> Void { var isValidInput : Bool = true // if any input not valid then set status false if count(self.emailText.text) < 4 { isValidInput = false } // if valid input then enable submit button if isValidInput { self.submitButton.enabled = true }else{ self.submitButton.enabled = false } } // show alert message with given title and message private func showAlertMessage(#alertTitle: String, alertMessage: String) -> Void { let alertCtrl = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil) alertCtrl.addAction(okAction) self.showViewController(alertCtrl, sender: self) } }
mit
578884c4b4c5ec8ac79af29a8280e828
28.572368
186
0.595551
5.654088
false
false
false
false
yunzixun/V2ex-Swift
View/V2LoadingView.swift
1
2890
// // V2LoadingView.swift // V2ex-Swift // // Created by huangfeng on 1/28/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit let noticeString = [ "正在拼命加载", "前方发现楼主", "年轻人,不要着急", "让我飞一会儿", "大爷,您又来了?", "楼主正在抓皮卡丘,等他一会儿吧", "爱我,就等我一万年", "未满18禁止入内", "正在前往 花村", "正在前往 阿努比斯神殿", "正在前往 沃斯卡娅工业区", "正在前往 观测站:直布罗陀", "正在前往 好莱坞", "正在前往 66号公路", "正在前往 国王大道", "正在前往 伊利奥斯", "正在前往 漓江塔", "正在前往 尼泊尔" ] class V2LoadingView: UIView { var activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray) init (){ super.init(frame:CGRect.zero) self.addSubview(self.activityIndicatorView) self.activityIndicatorView.snp.makeConstraints{ (make) -> Void in make.centerX.equalTo(self) make.centerY.equalTo(self).offset(-32) } let noticeLabel = UILabel() //修复BUG。做个小笔记给阅读代码的兄弟们提个醒 //(Int)(arc4random()) //上面这种写法有问题,arc4random()会返回 一个Uint32的随机数值。 //在32位机器上,如果随机的数大于Int.max ,转换就会crash。 noticeLabel.text = noticeString[Int(arc4random() % UInt32(noticeString.count))] noticeLabel.font = v2Font(10) noticeLabel.textColor = V2EXColor.colors.v2_TopicListDateColor self.addSubview(noticeLabel) noticeLabel.snp.makeConstraints{ (make) -> Void in make.top.equalTo(self.activityIndicatorView.snp.bottom).offset(10) make.centerX.equalTo(self.activityIndicatorView) } self.themeChangedHandler = {[weak self] (style) -> Void in if V2EXColor.sharedInstance.style == V2EXColor.V2EXColorStyleDefault { self?.activityIndicatorView.activityIndicatorViewStyle = .gray } else{ self?.activityIndicatorView.activityIndicatorViewStyle = .white } } } override func willMove(toSuperview newSuperview: UIView?) { self.activityIndicatorView.startAnimating() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func hide(){ self.superview?.bringSubview(toFront: self) UIView.animate(withDuration: 0.2, animations: { () -> Void in self.alpha = 0 ; }, completion: { (finished) -> Void in if finished { self.removeFromSuperview(); } }) } }
mit
cc5ddb369f81742e50f485f40bba9075
27.54023
87
0.596456
3.448611
false
false
false
false
stephentyrone/swift
stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift
3
4429
//===--- SwiftPrivateLibcExtras.swift -------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftPrivate #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) || os(WASI) import Glibc #elseif os(Windows) import MSVCRT #endif public func _stdlib_mkstemps(_ template: inout String, _ suffixlen: CInt) -> CInt { #if os(Android) || os(Haiku) || os(Windows) || os(WASI) preconditionFailure("mkstemps doesn't work on your platform") #else var utf8CStr = template.utf8CString let (fd, fileName) = utf8CStr.withUnsafeMutableBufferPointer { (utf8CStr) -> (CInt, String) in let fd = mkstemps(utf8CStr.baseAddress!, suffixlen) let fileName = String(cString: utf8CStr.baseAddress!) return (fd, fileName) } template = fileName return fd #endif } #if !os(Windows) public var _stdlib_FD_SETSIZE: CInt { return 1024 } public struct _stdlib_fd_set { var _data: [UInt] static var _wordBits: Int { return MemoryLayout<UInt>.size * 8 } public init() { _data = [UInt]( repeating: 0, count: Int(_stdlib_FD_SETSIZE) / _stdlib_fd_set._wordBits) } public func isset(_ fd: CInt) -> Bool { let fdInt = Int(fd) return ( _data[fdInt / _stdlib_fd_set._wordBits] & UInt(1 << (fdInt % _stdlib_fd_set._wordBits)) ) != 0 } public mutating func set(_ fd: CInt) { let fdInt = Int(fd) _data[fdInt / _stdlib_fd_set._wordBits] |= UInt(1 << (fdInt % _stdlib_fd_set._wordBits)) } public mutating func clear(_ fd: CInt) { let fdInt = Int(fd) _data[fdInt / _stdlib_fd_set._wordBits] &= ~UInt(1 << (fdInt % _stdlib_fd_set._wordBits)) } public mutating func zero() { let count = _data.count return _data.withUnsafeMutableBufferPointer { (_data) in for i in 0..<count { _data[i] = 0 } return } } } public func _stdlib_select( _ readfds: inout _stdlib_fd_set, _ writefds: inout _stdlib_fd_set, _ errorfds: inout _stdlib_fd_set, _ timeout: UnsafeMutablePointer<timeval>? ) -> CInt { return readfds._data.withUnsafeMutableBufferPointer { (readfds) in writefds._data.withUnsafeMutableBufferPointer { (writefds) in errorfds._data.withUnsafeMutableBufferPointer { (errorfds) in let readAddr = readfds.baseAddress let writeAddr = writefds.baseAddress let errorAddr = errorfds.baseAddress #if os(Cygwin) typealias fd_set = _types_fd_set #endif func asFdSetPtr( _ p: UnsafeMutablePointer<UInt>? ) -> UnsafeMutablePointer<fd_set>? { return UnsafeMutableRawPointer(p)? .assumingMemoryBound(to: fd_set.self) } return select( _stdlib_FD_SETSIZE, asFdSetPtr(readAddr), asFdSetPtr(writeAddr), asFdSetPtr(errorAddr), timeout) } } } } #endif /// Swift-y wrapper around pipe(2) public func _stdlib_pipe() -> (readEnd: CInt, writeEnd: CInt, error: CInt) { var fds: [CInt] = [0, 0] let ret = fds.withUnsafeMutableBufferPointer { unsafeFds -> CInt in #if os(Windows) return _pipe(unsafeFds.baseAddress, 0, 0) #elseif os(WASI) preconditionFailure("No pipes available on WebAssembly/WASI") #else return pipe(unsafeFds.baseAddress) #endif } return (readEnd: fds[0], writeEnd: fds[1], error: ret) } #if !os(Windows) // // Functions missing in `Darwin` module. // public func _WSTATUS(_ status: CInt) -> CInt { return status & 0x7f } public var _WSTOPPED: CInt { return 0x7f } public func WIFEXITED(_ status: CInt) -> Bool { return _WSTATUS(status) == 0 } public func WIFSIGNALED(_ status: CInt) -> Bool { return _WSTATUS(status) != _WSTOPPED && _WSTATUS(status) != 0 } public func WEXITSTATUS(_ status: CInt) -> CInt { return (status >> 8) & 0xff } public func WTERMSIG(_ status: CInt) -> CInt { return _WSTATUS(status) } #endif
apache-2.0
0c2907675d1bbe5a030e0517d43bef88
25.680723
112
0.624746
3.515079
false
false
false
false
1000copy/fin
View/BaseDetailTableViewCell.swift
1
4352
// // BaseDetailTableViewCell.swift // V2ex-Swift // // Created by huangfeng on 1/21/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit class BaseDetailTableViewCell: TJCell { var titleLabel:UILabel = { let label = UILabel() label.font = v2Font(16) return label }() var detailLabel:UILabel = { let label = UILabel() label.font = v2Font(13) return label }() var detailMarkImageView:UIImageView = { let imageview = UIImageView(image: UIImage.imageUsedTemplateMode("ic_keyboard_arrow_right")) imageview.contentMode = .center return imageview }() var separator:UIImageView = UIImageView() var detailMarkHidden:Bool { get{ return self.detailMarkImageView.isHidden } set{ if self.detailMarkImageView.isHidden == newValue{ return ; } self.detailMarkImageView.isHidden = newValue if newValue { self.detailMarkImageView.snp.remakeConstraints{ (make) -> Void in make.width.height.equalTo(0) make.centerY.equalTo(self.contentView) make.right.equalTo(self.contentView).offset(-12) } } else{ self.detailMarkImageView.snp.remakeConstraints{ (make) -> Void in make.width.height.equalTo(20) make.centerY.equalTo(self.contentView) make.right.equalTo(self.contentView).offset(-12) } } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier); // self.setup(); } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func setup()->Void{ let selectedBackgroundView = UIView() self.selectedBackgroundView = selectedBackgroundView self.contentView.addSubview(self.titleLabel) self.contentView.addSubview(self.detailMarkImageView); self.contentView.addSubview(self.detailLabel) self.contentView.addSubview(self.separator) self.titleLabel.snp.makeConstraints{ (make) -> Void in make.left.equalTo(self.contentView).offset(12) make.centerY.equalTo(self.contentView) } self.detailMarkImageView.snp.remakeConstraints{ (make) -> Void in make.height.equalTo(24) make.width.equalTo(14) make.centerY.equalTo(self.contentView) make.right.equalTo(self.contentView).offset(-12) } self.detailLabel.snp.makeConstraints{ (make) -> Void in make.right.equalTo(self.detailMarkImageView.snp.left).offset(-5) make.centerY.equalTo(self.contentView) } self.separator.snp.makeConstraints{ (make) -> Void in make.left.right.bottom.equalTo(self.contentView) make.height.equalTo(SEPARATOR_HEIGHT) } self.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor self.selectedBackgroundView!.backgroundColor = V2EXColor.colors.v2_backgroundColor self.titleLabel.textColor = V2EXColor.colors.v2_TopicListTitleColor self.detailMarkImageView.tintColor = self.titleLabel.textColor self.detailLabel.textColor = V2EXColor.colors.v2_TopicListUserNameColor self.separator.image = createImageWithColor( V2EXColor.colors.v2_SeparatorColor ) // self.thmemChangedHandler = {[weak self] (style) -> Void in // self?.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor // self?.selectedBackgroundView!.backgroundColor = V2EXColor.colors.v2_backgroundColor // self?.titleLabel.textColor = V2EXColor.colors.v2_TopicListTitleColor // self?.detailMarkImageView.tintColor = self?.titleLabel.textColor // self?.detailLabel.textColor = V2EXColor.colors.v2_TopicListUserNameColor // self?.separator.image = createImageWithColor( V2EXColor.colors.v2_SeparatorColor ) // } } }
mit
fd3072773f8623a3a70b5857f55ae577
37.504425
105
0.612963
4.729348
false
false
false
false
vulcancreative/chinwag-swift
Source/Chinwag.swift
1
7460
// // Chinwag.swift // Chinwag // // Created by Chris Calo on 2/26/15. // Copyright (c) 2015 Chris Calo. All rights reserved. // import Foundation public let version = String.fromCString(CW_VERSION)! // public typealias CWDict = cwdict_t public class CWDict: NSObject, NSCopying { public var name: String { get { return String.fromCString(self.dict.name)! } set(name) { var nameC = UnsafeMutablePointer<Int8>.alloc(12) strcpy(nameC, (name as NSString).UTF8String) free(self.dict.name) self.dict.name = nameC } } public var length: UInt { return UInt(cwdict_length(self.dict)) } public var isValid: Bool { return self.validate() == nil ? true : false } public var isSorted: Bool { get { return self.dict.sorted } set(sorted) { self.dict.sorted = sorted } } internal var dict: cwdict_t = cwdict_open() override init() { super.init() self.name = "" } convenience init(dict: cwdict_t) { self.init() self.dict = dict } convenience init(name: String) { self.init() self.name = name } } public enum CWError: String { case InvalidOutputType = "CWError.InvalidOutputType" case MinLessThanOne = "CWError.MinLessThanOne" case MaxLessThanMin = "CWError.MaxLessThanMin" case MaxTooHigh = "CWError.MaxTooHigh" case DictTooSmall = "CWError.DictTooSmall" case DictUnsortable = "CWError.DictUnsortable" case DictUnknown = "CWError.DictUnknown" } public enum CWType: cw_t { case Letters = 0 case Words = 1 case Sentences = 2 case Paragraphs = 3 } public enum CWEmbedded { case Seuss case Seussian case Latin } public var defaultDict: CWDict = open(embedded: .Seuss)! public var defaultType = CWType.Words public var defaultMinOutput: UInt = 1 public var defaultMaxOutput: UInt = 5 public func generate(dict: CWDict, kind: CWType, min: UInt, max: UInt) -> (result: String, err: CWError?) { var err = dict.validate() if err != nil { return ("", err) } // TODO : not currently a primary feature in core library if max > 10000 { return ("", CWError.MaxTooHigh) } var errC = cwerror_t() var resultC = chinwag(kind.rawValue, min, max, dict.dict, &errC) if resultC == nil { switch errC { case cwerror_t(0): return ("", CWError.InvalidOutputType) case cwerror_t(1): return ("", CWError.MinLessThanOne) case cwerror_t(2): return ("", CWError.MaxLessThanMin) case cwerror_t(3): return ("", CWError.MaxTooHigh) default: return ("", CWError.DictUnknown) } } var result = String.fromCString(resultC)! free(resultC) return ("", nil) } public func generate() -> (result: String, err: CWError?) { return generate(defaultDict, defaultType, defaultMinOutput, defaultMaxOutput) } public func open() -> CWDict { return CWDict() } public func open(#name: String) -> CWDict! { return CWDict(name: name) } // TODO : implement public func open(#tokens: NSData) -> CWDict? { return nil } // TODO : implement public func open(#name: String, #tokens: NSData) -> CWDict? { return nil } public func open(#embedded: CWEmbedded) -> CWDict? { switch embedded { case .Seuss, .Seussian: return CWDict(dict: cwdict_open_with_name_and_tokens("Seussian", dict_seuss, CW_DELIMITERS)) case .Latin: return CWDict(dict: cwdict_open_with_name_and_tokens("Latin", dict_latin, CW_DELIMITERS)) default: return nil } } /* // TODO : implement infix operator + { associativity left precedence 140 } public func +(left: CWDict, right: String) -> CWDict { return open() } // TODO : implement public func +(left: CWDict, right: [String]) -> CWDict { return open() } // TODO : implement infix operator += { associativity left precedence 90 } public func +=(inout left: CWDict, right: String) { left = left + right } // TODO : implement public func +=(inout left: CWDict, right: [String]) { left = left + right } // TODO : implement infix operator << { associativity left precedence 140 } public func <<(inout left: CWDict, right: String) { return } // TODO : implement public func <<(inout left: CWDict, right: [String]) { return } infix operator == { associativity left precedence 130 } public func ==(left: CWDict, right: CWDict) -> Bool { return cwdict_equal(left.dict, right.dict) } infix operator != { associativity left precedence 130 } public func !=(left: CWDict, right: CWDict) -> Bool { return cwdict_inequal(left.dict, right.dict) } */ // separate extension for the sake of organization public extension CWDict { public func copyWithZone(zone: NSZone) -> AnyObject { var copy = open() copy.dict = self.dict return copy } public func sort() { self.dict = cwdict_sort(self.dict) } public func prune() { self.dict = cwdict_prune(self.dict, false, false) } public func clean() { self.dict = cwdict_prune(self.dict, true, false) } public func exclude(word: String) -> Bool { var wordC = UnsafeMutablePointer<Int8>.alloc(12) strcpy(wordC, (word as NSString).UTF8String) let result = cwdict_exclude(self.dict, wordC) free(wordC) return result } public func include(word: String) -> Bool { var wordC = UnsafeMutablePointer<Int8>.alloc(12) strcpy(wordC, (word as NSString).UTF8String) let result = cwdict_include(self.dict, wordC) free(wordC) return result } public func validate() -> CWError? { var err = cwerror_t() if !cwdict_valid(self.dict, &err) { switch err { case cwerror_t(4): return CWError.DictTooSmall case cwerror_t(5): return CWError.DictUnsortable default: return CWError.DictUnknown } } return nil } public var size: UInt { return self.length } public var count: UInt { return self.length } public var largest: UInt { return UInt(cwdict_largest(self.dict)) } public var sample: String? { if self.length == 0 { return nil } return String.fromCString(cwdict_sample(self.dict))! } // TODO : implement public func join(joiner: String) -> String { return "" } // TODO : implement public func string() -> String { var result = ""; var index: UInt = 0; let length = self.length let rowCount = self.dict.count result += "[" for var i: UInt = 0; i != rowCount; ++i { // if index >= length { break } result += "[" let current = self.dict.drows[Int(i)] let wordCount = current.count if current.words != nil { for var j: UInt = 0; j != wordCount; ++j { // println("\(index) of \(length)") let word = String.fromCString(current.words[Int(j)]) if word == nil { result += "]]" return result } // println("[\(index):\(length)] \(word)") result += word! ++index; // println("index : \(index)") if index >= length { result += "]]" return result } if j < wordCount - 1 { result += ", " } } } result += "]" if i < rowCount - 1 { result += ", " } } result += "]" return result } public func close() { cwdict_close(self.dict) } }
mit
9f46f2079585a89f7b18c3f5fe140349
19.722222
98
0.611394
3.565966
false
false
false
false
hollarab/LearningSwiftWorkshop
DaVinciWeekendWorkshop.playground/Pages/8) Excercise!.xcplaygroundpage/Contents.swift
1
2003
/*: [Previous](@previous) # "Real" playground Our last activity today will be to complete an iOS app, [Rocket App](https://github.com/hollarab/LearningSwiftRocketApp). But first, lets look at the logic and method we will need. Press `CMD + OPT + Enter` to show the Assitant Editor Read the code below, and uncomment the last line to make it run. */ import XCPlayground import UIKit import Foundation import Foundation import UIKit class RocketHelper:NSObject { var timer:NSTimer? // creates our run loop var distance:Float = 0.0 // distance travelled let distancePerTick:Float = 2 // how far it moves each tick var parent:UIView? var child:UIView? override init() { /** TODO: start blue square at bottom of screen */ parent = UIView(frame: CGRectMake(0, 0, 100, 200)) parent?.backgroundColor = UIColor.redColor() child = UIView(frame: CGRectMake(0, 0, 50, 50)) child?.backgroundColor = UIColor.blueColor() parent?.addSubview(child!) } /*: The rest of the class can be used to play with and move to the Rocket App */ func startTimer() { timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "timerFired", userInfo: nil, repeats: true) } func stopTimer() { timer?.invalidate() distance = 0 } func timerFired() { distance += distancePerTick print(distance) var frame = child!.frame frame.origin.x += CGFloat(distancePerTick) frame.origin.y += CGFloat(distancePerTick) child!.frame = frame /** Can you make the square reset when it goes off the screen? */ } } // call constructor, make new object let helper = RocketHelper() // Show the parent view so we can see things move XCPlaygroundPage.currentPage.liveView = helper.parent! /** Uncomment NEXT line to let the playground run */ helper.startTimer()
mit
a86c99f78237e4f8175621a50e3e8f1f
25.012987
127
0.645032
4.344902
false
false
false
false
GitTennis/SuccessFramework
Templates/_BusinessAppSwift_/_BusinessAppSwift_Tests/SettingsManagerTests.swift
2
2440
// // SettingsManagerTests.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 26/10/2016. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import XCTest @testable import _BusinessAppSwift_ class SettingsManagerTests: _BusinessAppSwift_Tests { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() let manager = SettingsManager.init(localizationManager: LocalizationManager()) manager.clearAll() } func test_isFirstTimeAppLaunch() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let manager = SettingsManager.init(localizationManager: LocalizationManager()) XCTAssert((manager.isFirstTimeAppLaunch == true), "Should be empty now") manager.isFirstTimeAppLaunch = false NLAssertEqualOptional(expression1: manager.isFirstTimeAppLaunch, true, "Should be set") } }
mit
956d44bfe31a206532ff05395aa13a21
41.034483
111
0.71452
4.706564
false
true
false
false
wibosco/WhiteBoardCodingChallenges
WhiteBoardCodingChallenges/Challenges/Other/HeapSort/HeapSort.swift
1
1653
// // HeapSort.swift // WhiteBoardCodingChallenges // // Created by William Boles on 27/06/2016. // Copyright © 2016 Boles. All rights reserved. // import Foundation class HeapSort: NSObject { // MARK: Max class func maxHeapSort(input: [Int]) -> [Int] { if input.count < 2 { return input } var maxHeap = MaxHeap.buildMaxHeap(input: input) var heapSorted = [Int]() while maxHeap.count > 1 { heapSorted.insert(maxHeap[0], at: 0) exchange(heap: &maxHeap, i: 0, j: (maxHeap.count - 1)) maxHeap.removeLast() MaxHeap.maxHeapify(heap: &maxHeap, indexRoot: 0) } heapSorted.insert(maxHeap[0], at: 0) return heapSorted } // MARK: Min class func minHeapSort(input: [Int]) -> [Int] { if input.count < 2 { return input } var minHeap = MinHeap.buildMinHeap(input: input) var heapSorted = [Int]() while minHeap.count > 1 { heapSorted.insert(minHeap[0], at: 0) exchange(heap: &minHeap, i: 0, j: (minHeap.count - 1)) minHeap.removeLast() MinHeap.minHeapify(heap: &minHeap, indexRoot: 0) } heapSorted.insert(minHeap[0], at: 0) return heapSorted } // MARK: Exchange class func exchange<T>(heap: inout [T], i:Int, j:Int) { let temp:T = heap[i] heap[i] = heap[j] heap[j] = temp } }
mit
69e03b66d69e2dd5e4a7905055bb11f0
22.267606
66
0.491525
3.942721
false
false
false
false
devxoul/URLNavigator
Sources/URLNavigator/Navigator.swift
1
6549
#if os(iOS) || os(tvOS) import UIKit #if !COCOAPODS import URLMatcher #endif public typealias URLPattern = String public typealias ViewControllerFactory = (_ url: URLConvertible, _ values: [String: Any], _ context: Any?) -> UIViewController? public typealias URLOpenHandlerFactory = (_ url: URLConvertible, _ values: [String: Any], _ context: Any?) -> Bool public typealias URLOpenHandler = () -> Bool open class Navigator: NavigatorProtocol { // MARK: Properties public let matcher = URLMatcher() open weak var delegate: NavigatorDelegate? private var viewControllerFactories = [URLPattern: ViewControllerFactory]() private var handlerFactories = [URLPattern: URLOpenHandlerFactory]() // MARK: Initializing public init() { // ⛵ I'm a Navigator! } // MARK: Registering URLs /// Registers a view controller factory to the URL pattern. open func register(_ pattern: URLPattern, _ factory: @escaping ViewControllerFactory) { self.viewControllerFactories[pattern] = factory } /// Registers an URL open handler to the URL pattern. open func handle(_ pattern: URLPattern, _ factory: @escaping URLOpenHandlerFactory) { self.handlerFactories[pattern] = factory } /// Returns a matching view controller from the specified URL. /// /// - parameter url: An URL to find view controllers. /// /// - returns: A match view controller or `nil` if not matched. open func viewController(for url: URLConvertible, context: Any? = nil) -> UIViewController? { let urlPatterns = Array(self.viewControllerFactories.keys) guard let match = self.matcher.match(url, from: urlPatterns) else { return nil } guard let factory = self.viewControllerFactories[match.pattern] else { return nil } return factory(url, match.values, context) } /// Returns a matching URL handler from the specified URL. /// /// - parameter url: An URL to find url handlers. /// /// - returns: A matching handler factory or `nil` if not matched. open func handler(for url: URLConvertible, context: Any? = nil) -> URLOpenHandler? { let urlPatterns = Array(self.handlerFactories.keys) guard let match = self.matcher.match(url, from: urlPatterns) else { return nil } guard let handler = self.handlerFactories[match.pattern] else { return nil } return { handler(url, match.values, context) } } // MARK: Push /// Pushes a matching view controller to the navigation controller stack. /// /// - note: It is not a good idea to use this method directly because this method requires all /// parameters. This method eventually gets called when pushing a view controller with /// an URL, so it's recommended to implement this method only for mocking. @discardableResult open func push(_ url: URLConvertible, context: Any? = nil, from: UINavigationControllerType? = nil, animated: Bool = true) -> UIViewController? { guard let viewController = self.viewController(for: url, context: context) else { return nil } return self.push(viewController, from: from, animated: animated) } /// Pushes the view controller to the navigation controller stack. /// /// - note: It is not a good idea to use this method directly because this method requires all /// parameters. This method eventually gets called when pushing a view controller, so /// it's recommended to implement this method only for mocking. @discardableResult open func push(_ viewController: UIViewController, from: UINavigationControllerType? = nil, animated: Bool = true) -> UIViewController? { guard (viewController is UINavigationController) == false else { return nil } guard let navigationController = from ?? UIViewController.topMost?.navigationController else { return nil } guard self.delegate?.shouldPush(viewController: viewController, from: navigationController) != false else { return nil } navigationController.pushViewController(viewController, animated: animated) return viewController } // MARK: Present /// Presents a matching view controller. /// /// - note: It is not a good idea to use this method directly because this method requires all /// parameters. This method eventually gets called when presenting a view controller with /// an URL, so it's recommended to implement this method only for mocking. @discardableResult open func present(_ url: URLConvertible, context: Any? = nil, wrap: UINavigationController.Type? = nil, from: UIViewControllerType? = nil, animated: Bool = true, completion: (() -> Void)? = nil) -> UIViewController? { guard let viewController = self.viewController(for: url, context: context) else { return nil } return self.present(viewController, wrap: wrap, from: from, animated: animated, completion: completion) } /// Presents the view controller. /// /// - note: It is not a good idea to use this method directly because this method requires all /// parameters. This method eventually gets called when presenting a view controller, so /// it's recommended to implement this method only for mocking. @discardableResult open func present(_ viewController: UIViewController, wrap: UINavigationController.Type? = nil, from: UIViewControllerType? = nil, animated: Bool = true, completion: (() -> Void)? = nil) -> UIViewController? { guard let fromViewController = from ?? UIViewController.topMost else { return nil } let viewControllerToPresent: UIViewController if let navigationControllerClass = wrap, (viewController is UINavigationController) == false { viewControllerToPresent = navigationControllerClass.init(rootViewController: viewController) } else { viewControllerToPresent = viewController } guard self.delegate?.shouldPresent(viewController: viewController, from: fromViewController) != false else { return nil } fromViewController.present(viewControllerToPresent, animated: animated, completion: completion) return viewController } // MARK: Open /// Executes an URL open handler. /// /// - note: It is not a good idea to use this method directly because this method requires all /// parameters. This method eventually gets called when opening an url, so it's /// recommended to implement this method only for mocking. @discardableResult open func open(_ url: URLConvertible, context: Any? = nil) -> Bool { guard let handler = self.handler(for: url, context: context) else { return false } return handler() } } #endif
mit
d1862bbacc6d94fe3e4d2983c0c60596
44.465278
219
0.719719
4.744203
false
false
false
false
RoRoche/iOSSwiftStarter
iOSSwiftStarter/Pods/ReactKit/ReactKit/UIKit/UIBarButtonItem+Stream.swift
4
1478
// // UIBarButtonItem+Stream.swift // ReactKit // // Created by Yasuhiro Inami on 2014/10/08. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // import UIKit public extension UIBarButtonItem { public func stream<T>(map: UIBarButtonItem? -> T) -> Stream<T> { return Stream<T> { [weak self] progress, fulfill, reject, configure in let target = _TargetActionProxy { (self_: AnyObject?) in progress(map(self_ as? UIBarButtonItem)) } let addTargetAction: Void -> Void = { if let self_ = self { self_.target = target self_.action = _targetActionSelector } } let removeTargetAction: Void -> Void = { if let self_ = self { self_.target = nil self_.action = nil } } configure.pause = { removeTargetAction() } configure.resume = { addTargetAction() } configure.cancel = { removeTargetAction() } configure.resume?() }.name("\(_summary(self))") |> takeUntil(self.deinitStream) } public func stream<T>(mappedValue: T) -> Stream<T> { return self.stream { _ in mappedValue } } }
apache-2.0
50877a716f0422a7b6a0abe820a3a7b0
26.351852
78
0.466802
5.072165
false
true
false
false
tatey/Lighting
Widget/TodayViewController.swift
1
3278
// // Created by Tate Johnson on 26/03/2015. // Copyright (c) 2015 Tate Johnson. All rights reserved. // import Cocoa import NotificationCenter import LIFXHTTPKit class TodayViewController: NSViewController, NCWidgetProviding { static let DefaultMargin: CGFloat = 5.0 // Derived from margin between collection view and label in TodayViewController.xib static let EmptyString: String = "" @IBOutlet weak var lightsCollectionView: LightTargetCollectionView? @IBOutlet weak var errorLabel: NSTextField? var accessToken: AccessToken! var accessTokenObserver: DarwinNotification? var client: Client! var allLightTarget: LightTarget! override var nibName: String? { return "TodayViewController" } override func viewDidLoad() { super.viewDidLoad() accessToken = AccessToken() client = Client(accessToken: accessToken.token ?? TodayViewController.EmptyString) allLightTarget = client.allLightTarget() accessTokenObserver = accessToken.addObserver { self.client = Client(accessToken: self.accessToken.token ?? TodayViewController.EmptyString) self.lightsCollectionView?.content = self.lightTargetsBySortingAlphabetically(self.allLightTarget) self.setNeedsUpdate() } if #available(OSX 10.11, *) { fetch() } lightsCollectionView?.backgroundColors = [NSColor.clear] } deinit { if let observer = accessTokenObserver { accessToken.removeObserver(observer) } } fileprivate func lightTargetsBySortingAlphabetically(_ lightTarget: LightTarget) -> [LightTarget] { return [lightTarget] + lightTarget.toLightTargets().sorted { (lhs, rhs) in return lhs.label < rhs.label } } fileprivate func setNeedsUpdate() { if let lightsCollectionView = self.lightsCollectionView, let errorLabel = self.errorLabel { var newSize = lightsCollectionView.sizeThatFits(NSSize(width: view.frame.width, height: CGFloat.greatestFiniteMagnitude)) if errorLabel.stringValue == TodayViewController.EmptyString { errorLabel.frame = CGRect.zero } else { errorLabel.sizeToFit() } newSize.height += errorLabel.frame.height preferredContentSize = NSSize(width: view.frame.width, height: newSize.height + TodayViewController.DefaultMargin) } } fileprivate func fetch(_ completionHandler: (([NSError]) -> Void)? = nil) { client.fetch { (errors) in DispatchQueue.main.async { if errors.count > 0 { self.errorLabel?.stringValue = "An error occured fetching lights." completionHandler?(errors as [NSError]) } else { self.errorLabel?.stringValue = TodayViewController.EmptyString self.lightsCollectionView?.content = self.lightTargetsBySortingAlphabetically(self.allLightTarget) completionHandler?([]) } self.setNeedsUpdate() } } } // MARK: NCWidgetProviding func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) { fetch { (errors) in if errors.count > 0 { completionHandler(.failed) } else { completionHandler(.newData) } } } func widgetMarginInsets(forProposedMarginInsets defaultMarginInset: NSEdgeInsets) -> NSEdgeInsets { return NSEdgeInsets(top: defaultMarginInset.top + TodayViewController.DefaultMargin, left: defaultMarginInset.left, bottom: defaultMarginInset.bottom, right: 0.0) } }
gpl-3.0
63342e9a68c80d5bbd6f6a3b7941f1dd
30.219048
164
0.748322
4.21879
false
false
false
false
BMWB/RRArt-Swift-Test
RRArt-Swift/RRArt-Swift/Classes/Drawer/MMViewController.swift
1
1263
// // MMViewController.swift // RRArt-Swift // // Created by wtj on 16/5/5. // Copyright © 2016年 com.yibei.renrenmeishu. All rights reserved. // import UIKit import MMDrawerController let MMLeftVc_width = kScreen_Width - 200 class MMViewController: MMDrawerController { override func viewDidLoad() { super.viewDidLoad() let leftVC = GET_SB("LeftVc").instantiateViewControllerWithIdentifier("MyZone_RootViewController") as! MyZone_RootViewController leftVC.mainVC = self centerViewController = centerVc leftDrawerViewController = leftVC maximumLeftDrawerWidth = MMLeftVc_width shouldStretchDrawer = false openDrawerGestureModeMask = MMOpenDrawerGestureMode.All closeDrawerGestureModeMask = MMCloseDrawerGestureMode.All } lazy var centerVc :BaseNavigationViewController = { let orgModel = COrgListModels() orgModel.Id = 1 orgModel.Name = "每日推荐" let centerVc = Lesson_RootViewController() centerVc.orglist = orgModel let centerNav = BaseNavigationViewController(rootViewController: centerVc) return centerNav }() }
apache-2.0
28e46624fe25bb00ab745fa928dd6810
26.217391
138
0.658147
4.968254
false
false
false
false
wordpress-mobile/AztecEditor-iOS
Aztec/Classes/Formatters/Implementations/HeaderFormatter.swift
1
4408
import Foundation import UIKit // MARK: - Header Formatter // open class HeaderFormatter: ParagraphAttributeFormatter { /// Heading Level of this formatter /// let headerLevel: Header.HeaderType /// Designated Initializer /// public init(headerLevel: Header.HeaderType = .h1) { self.headerLevel = headerLevel } // MARK: - Overwriten Methods public func apply(to attributes: [NSAttributedString.Key: Any], andStore representation: HTMLRepresentation?) -> [NSAttributedString.Key: Any] { guard let font = attributes[.font] as? UIFont else { return attributes } let newParagraphStyle = ParagraphStyle() if let paragraphStyle = attributes[.paragraphStyle] as? NSParagraphStyle { newParagraphStyle.setParagraphStyle(paragraphStyle) } let defaultSize = defaultFontSize(from: attributes) let header = Header(level: headerLevel, with: representation, defaultFontSize: defaultSize) if newParagraphStyle.headers.isEmpty { newParagraphStyle.appendProperty(header) } else { newParagraphStyle.replaceProperty(ofType: Header.self, with: header) } let targetFontSize = CGFloat(headerFontSize(for: headerLevel, defaultSize: defaultSize)) var resultingAttributes = attributes let newDescriptor = font.fontDescriptor.addingAttributes([.size: targetFontSize]) var newFont = UIFont(descriptor: newDescriptor, size: targetFontSize) if Configuration.headersWithBoldTrait { newFont = newFont.modifyTraits(.traitBold, enable: true) } resultingAttributes[.paragraphStyle] = newParagraphStyle resultingAttributes[.font] = newFont resultingAttributes[.headingRepresentation] = headerLevel.rawValue return resultingAttributes } func remove(from attributes: [NSAttributedString.Key: Any]) -> [NSAttributedString.Key: Any] { guard let paragraphStyle = attributes[.paragraphStyle] as? ParagraphStyle, let header = paragraphStyle.headers.last, header.level != .none else { return attributes } let newParagraphStyle = ParagraphStyle() newParagraphStyle.setParagraphStyle(paragraphStyle) newParagraphStyle.removeProperty(ofType: Header.self) var resultingAttributes = attributes resultingAttributes[.paragraphStyle] = newParagraphStyle if let font = attributes[.font] as? UIFont { var newFont = font.withSize(CGFloat(header.defaultFontSize)) if Configuration.headersWithBoldTrait { newFont = newFont.modifyTraits(.traitBold, enable: false) if attributes[.shadow] != nil { resultingAttributes.removeValue(forKey: .shadow) resultingAttributes.removeValue(forKey: .kern) newFont = newFont.modifyTraits(.traitBold, enable: true) } } resultingAttributes[.font] = newFont } resultingAttributes[.headingRepresentation] = nil return resultingAttributes } func present(in attributes: [NSAttributedString.Key: Any]) -> Bool { guard let paragraphStyle = attributes[.paragraphStyle] as? ParagraphStyle else { return false } if headerLevel == .none { return paragraphStyle.headerLevel != 0 } return paragraphStyle.headerLevel != 0 && paragraphStyle.headerLevel == headerLevel.rawValue } } // MARK: - Private Helpers // private extension HeaderFormatter { func defaultFontSize(from attributes: [NSAttributedString.Key: Any]) -> Float? { if let paragraphStyle = attributes[.paragraphStyle] as? ParagraphStyle, let lastHeader = paragraphStyle.headers.last { return lastHeader.defaultFontSize } if let font = attributes[.font] as? UIFont { return Float(font.pointSize) } return nil } func headerFontSize(for type: Header.HeaderType, defaultSize: Float?) -> Float { if Configuration.useDefaultFont { return defaultSize! } guard type == .none, let defaultSize = defaultSize else { return type.fontSize } return defaultSize } }
mpl-2.0
aebe9c9f0b7b8819fd39136e8de5277c
33.708661
148
0.649047
5.537688
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/KPUserManager.swift
1
10560
// // KPUserManager.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/5/25. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit import Firebase import FirebaseAuth import FacebookLogin import FacebookCore import ObjectMapper import PromiseKit import Crashlytics import Amplitude_iOS extension NSNotification.Name { public static let KPCurrentUserDidChange: NSNotification.Name = NSNotification.Name(rawValue: "KPCurrentUserDidChange") } public class KPUserManager { // MARK: Singleton static let sharedManager = KPUserManager() // MARK: Initialization private init() { // 讀取資料 KPUserDefaults.loadUserInformation() // 介面 loadingView = KPLoadingView() loadingView.loadingContents = ("登入中...", "登入成功", "登入失敗") loadingView.state = .loading // 屬性 loginManager = LoginManager() // 建立Current User if KPUserDefaults.accessToken != nil { var currentUserInfo: [String: Any] = ["access_token": KPUserDefaults.accessToken!] if let userInformation = KPUserDefaults.userInformation { currentUserInfo.merge(dict: userInformation) self.currentUser = Mapper<KPUser>().map(JSONObject: currentUserInfo) } } } // MARK: Properties var currentUser: KPUser? { didSet { NotificationCenter.default.post(name: NSNotification.Name.KPCurrentUserDidChange, object: nil) } } var loginManager: LoginManager! var loadingView: KPLoadingView! // MARK: API func logIn(_ viewController: UIViewController, completion: ((Bool) -> Swift.Void)? = nil) { self.loadingView.state = .loading loginManager.loginBehavior = LoginBehavior.native; loginManager.logIn([.publicProfile], viewController: viewController) { (loginResult) in viewController.view.addSubview(self.loadingView) self.loadingView.addConstraints(fromStringArray: ["V:|[$self]|", "H:|[$self]|"]) switch loginResult { case .failed(_): self.loadingView.state = .failed completion?(false) case .cancelled: self.loadingView.state = .failed completion?(false) case .success( _, _, let accessToken): let credential = FacebookAuthProvider.credential(withAccessToken: accessToken.authenticationToken) Auth.auth().signIn(with: credential, completion: { (user, error) in if let error = error { CLSLogv("Login Error %@", getVaList(["\(error.localizedDescription)"])) self.showAlert(viewController, error) self.loadingView.state = .failed completion?(false) return } let loginRequest = KPLoginRequest() loginRequest.perform(user?.uid, user?.displayName, user?.photoURL?.absoluteString, user?.email ?? "unknown").then { result -> Void in KPUserDefaults.accessToken = result["token"].string // 建立 Current User self.currentUser = Mapper<KPUser>().map(JSONObject: result["data"].dictionaryObject) self.currentUser?.accessToken = result["token"].string self.storeUserInformation() self.loadingView.state = .successed Crashlytics.sharedInstance().setUserIdentifier(self.currentUser?.identifier) Crashlytics.sharedInstance().setUserEmail(self.currentUser?.email) Crashlytics.sharedInstance().setUserName(self.currentUser?.displayName) Amplitude.instance().setUserId(self.currentUser?.identifier) Amplitude.instance().setUserProperties(["name": self.currentUser?.displayName ?? "No Name", "email": self.currentUser?.email ?? "No Email"]) completion?(true) DispatchQueue.main.asyncAfter(deadline: .now()+1.0) { viewController.dismiss(animated: true, completion: { print("Successfully Logged In") }) } }.catch { error in CLSLogv("Login Error %@", getVaList(["\(error.localizedDescription)"])) self.showAlert(viewController, error) self.loadingView.state = .failed completion?(false) return } }) } } } func logOut() { loginManager.logOut() KPUserDefaults.clearUserInformation() currentUser = nil } func updateUserInformation() { let userRequest = KPUserInformationRequest() userRequest.perform(nil, nil, nil, nil, nil, .get).then { result -> Void in print("取得更新後的使用者資料") let token = self.currentUser?.accessToken self.currentUser = Mapper<KPUser>().map(JSONObject: result["data"].dictionaryObject) self.currentUser?.accessToken = result["token"].string ?? token KPUserDefaults.accessToken = token self.storeUserInformation() }.catch { error in } } func storeUserInformation() { synchronized(lock: self) { let userInformationString = currentUser?.toJSONString() if let jsonData = userInformationString?.data(using: .utf8) { do { let userInformation = try? JSONSerialization.jsonObject(with: jsonData, options: []) if userInformation != nil { KPUserDefaults.userInformation = userInformation as? Dictionary<String, Any> } } } } } // UI Event func showAlert(_ viewController: UIViewController, _ error: Error) { let alertController = UIAlertController(title: "登入失敗", message: error.localizedDescription, preferredStyle: .alert) let okayAction = UIAlertAction(title: "瞭解", style: .cancel, handler: nil) alertController.addAction(okayAction) viewController.present(alertController, animated: true, completion: nil) } // MARK: Thread Issue func synchronized(lock: AnyObject, closure: () -> ()) { objc_sync_enter(lock) closure() objc_sync_exit(lock) } }
mit
7bbb7090d9b5a4f1aa59126d4f6fd179
48.419811
171
0.367472
8.204385
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/EthereumKit/Services/Activity/EthereumActivityItemEventDetails.swift
1
1459
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import MoneyKit import PlatformKit public struct EthereumActivityItemEventDetails: Equatable { public struct Confirmation: Equatable { public let needConfirmation: Bool public let confirmations: Int public let requiredConfirmations: Int public let factor: Float public let status: EthereumTransactionState } public let amount: CryptoValue public let confirmation: Confirmation public let createdAt: Date public let data: String? public let fee: CryptoValue public let from: EthereumAddress public let identifier: String public let to: EthereumAddress init(transaction: EthereumHistoricalTransaction) { amount = transaction.amount createdAt = transaction.createdAt data = transaction.data fee = transaction.fee ?? .zero(currency: .ethereum) from = transaction.fromAddress identifier = transaction.transactionHash to = transaction.toAddress confirmation = Confirmation( needConfirmation: transaction.state == .pending, confirmations: transaction.confirmations, requiredConfirmations: EthereumHistoricalTransaction.requiredConfirmations, factor: Float(transaction.confirmations) / Float(EthereumHistoricalTransaction.requiredConfirmations), status: transaction.state ) } }
lgpl-3.0
08044ca8e99fb187c463d3ce2b29e2fe
34.560976
114
0.707819
5.808765
false
false
false
false
qingcai518/MyReader_ios
MyReader/LocalBookInfo.swift
1
598
// // LocalBookInfo.swift // MyReader // // Created by RN-079 on 2017/02/21. // Copyright © 2017年 RN-079. All rights reserved. // import Foundation class LocalBookInfo { var bookId: String var bookName : String var authorName : String var localPath : String var bookImgUrl: String init(bookId: String, bookName: String, authorName: String, localPath: String, bookImgUrl: String) { self.bookId = bookId self.bookName = bookName self.authorName = authorName self.localPath = localPath self.bookImgUrl = bookImgUrl } }
mit
9b02f4da6473ab57a3f9e8d8457a3227
22.8
103
0.657143
3.966667
false
false
false
false
fjcaetano/RxWebSocket
Classes/RxWebSocket.swift
1
5039
// // RxWebSocket.swift // RxWebSocket // // Created by Flávio Caetano on 2016-01-10. // Copyright © 2016 RxWebSocket. All rights reserved. // import Foundation import RxCocoa import RxSwift import Starscream /// This is the abstraction over Starscream to make it reactive. open class RxWebSocket: WebSocket { /// Every message received by the websocket is converted to an `StreamEvent`. public enum StreamEvent { /// The "connect" message, flagging that the websocket did connect to the server. case connect /// A disconnect message that may contain an `Error` containing the reason for the disconection. case disconnect(Error?) /// The "pong" message the server may respond to a "ping". case pong(Data?) /// Any string messages received by the client. case text(String) /// Any data messages received by the client, excluding strings. case data(Data) } fileprivate let connectSubject: ReplaySubject<StreamEvent> fileprivate let eventSubject: PublishSubject<StreamEvent> /** - parameters: - request: A URL Request to be started. - protocols: The protocols that should be used in the comms. May be nil. - stream: A stream to which the client should connect. - returns: An instance of `RxWebSocket` The creation of a `RxWebSocket` object. The client is automatically connected to the server uppon initialization. */ override public init(request: URLRequest, protocols: [String]? = nil, stream: WSStream = FoundationStream()) { let publish = PublishSubject<StreamEvent>() eventSubject = publish let replay = ReplaySubject<StreamEvent>.create(bufferSize: 1) connectSubject = replay super.init(request: request, protocols: protocols, stream: stream) super.onConnect = { replay.onNext(.connect) } super.onText = { publish.onNext(.text($0)) } super.onData = { publish.onNext(.data($0)) } super.onPong = { publish.onNext(.pong($0)) } super.onDisconnect = { replay.onNext(.disconnect($0)) } connect() } /** - parameters: - url: The server url. - protocols: The protocols that should be used in the comms. May be nil. - returns: An instance of `RxWebSocket` The creation of a `RxWebSocket` object. The client is automatically connected to the server uppon initialization. */ public convenience init(url: URL, protocols: [String]? = nil) { self.init( request: URLRequest(url: url), protocols: protocols ) } } /// Makes RxWebSocket Reactive. public extension Reactive where Base: RxWebSocket { /// Receives and sends text messages from the websocket. var text: ControlProperty<String> { let values = stream.flatMap { event -> Observable<String> in guard case .text(let text) = event else { return Observable.empty() } return Observable.just(text) } return ControlProperty(values: values, valueSink: AnyObserver { [weak base] event in guard case .next(let text) = event else { return } base?.write(string: text) }) } /// Receives and sends data messages from the websocket. var data: ControlProperty<Data> { let values = stream.flatMap { event -> Observable<Data> in guard case .data(let data) = event else { return Observable.empty() } return Observable.just(data) } return ControlProperty(values: values, valueSink: AnyObserver { [weak base] event in guard case .next(let data) = event else { return } base?.write(data: data) }) } /// Receives connection events from the websocket. var connect: Observable<Void> { return stream.flatMap { event -> Observable<Void> in guard case .connect = event else { return Observable.empty() } return Observable.just(()) } } /// Receives disconnect events from the websocket. var disconnect: Observable<Error?> { return stream.flatMap { event -> Observable<Error?> in guard case .disconnect(let error) = event else { return Observable.empty() } return Observable.just(error) } } /// Receives "pong" messages from the websocket var pong: Observable<Data?> { return stream.flatMap { event -> Observable<Data?> in guard case .pong(let data) = event else { return Observable.empty() } return Observable.just(data) } } /// The stream of messages received by the websocket. var stream: Observable<Base.StreamEvent> { return Observable.merge(base.connectSubject, base.eventSubject) } }
mit
83cdf7cb3fbe75db00c30a0147dd9cb5
30.092593
118
0.612865
4.747408
false
false
false
false
GianniCarlo/Audiobook-Player
BookPlayerWatch Extension/Controllers/ComplicationController.swift
1
1139
// // ComplicationController.swift // BookPlayerWatch Extension // // Created by Gianni Carlo on 4/25/19. // Copyright © 2019 Tortuga Power. All rights reserved. // import ClockKit class ComplicationController: NSObject, CLKComplicationDataSource { // MARK: - Timeline Configuration func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) { handler([]) } // MARK: - Timeline Population func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) { // Call the handler with the current timeline entry if complication.family == .modularSmall { let template = CLKComplicationTemplateModularSmallSimpleImage() template.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "Complication/Modular")!) let entry = CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template) handler(entry) return } handler(nil) } }
gpl-3.0
064e9ccd5269e186e812732fd7bf502f
33.484848
156
0.707381
5.747475
false
false
false
false
devnikor/mpvx
mpvxTests/Core/CoreRepresentableTests.swift
1
2590
// // CoreRepresentableTests.swift // mpvx // // Created by Игорь Никитин on 21.02.16. // Copyright © 2016 Coder's Cake. All rights reserved. // @testable import mpvx import XCTest import mpv class CoreRepresentableTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testMPVNodeFromString() { var stringNode = "test".mpvNode XCTAssertEqual(stringNode.format, MPV_FORMAT_STRING) let stringPointer = stringNode.u.string let string = String(UTF8String: stringPointer) XCTAssertEqual(string, "test") } func testMPVNodeFromFlag() { let flagTrueNode = true.mpvNode XCTAssertEqual(flagTrueNode.format, MPV_FORMAT_FLAG) XCTAssertEqual(flagTrueNode.u.flag, 1) let flagFalseNode = false.mpvNode XCTAssertEqual(flagFalseNode.format, MPV_FORMAT_FLAG) XCTAssertEqual(flagFalseNode.u.flag, 0) } func testMPVNodeFromInt() { let intNode = 10.mpvNode XCTAssertEqual(intNode.format, MPV_FORMAT_INT64) XCTAssertEqual(intNode.u.int64, 10) let int64Node = Int64(11).mpvNode XCTAssertEqual(int64Node.format, MPV_FORMAT_INT64) XCTAssertEqual(int64Node.u.int64, 11) } func testMPVNodeFromDouble() { let node = 3.0.mpvNode XCTAssertEqual(node.format, MPV_FORMAT_DOUBLE) XCTAssertEqual(node.u.double_, 3.0) } func testStringFromNode() { let testString = "Hello" let stringNode = testString.mpvNode let stringFromNode = String(node: stringNode) XCTAssertEqual(testString, stringFromNode) } func testFlagFromNode() { let flag = true let node = flag.mpvNode let flagFromNode = Bool(node: node) XCTAssertEqual(flag, flagFromNode) } func testIntFromNode() { let int = 64 let node = int.mpvNode let intFromNode = Int(node: node) XCTAssertEqual(int, intFromNode) } func testDoubleFromNode() { let double = 4.0 let node = double.mpvNode let doubleFromNode = Double(node: node) XCTAssertEqual(double, doubleFromNode) } }
gpl-2.0
3c3503af05de835b4d69a5b7d67f1f66
26.414894
111
0.621653
4.190244
false
true
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/MiddleLeftHeight.Individual.swift
1
1225
// // MiddleLeftHeight.Individual.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/20. // Copyright © 2017年 史翔新. All rights reserved. // import Foundation extension IndividualProperty { public struct MiddleLeftHeight { let middleLeft: LayoutElement.Point let height: LayoutElement.Length } } // MARK: - Make Frame extension IndividualProperty.MiddleLeftHeight { private func makeFrame(middleLeft: Point, height: Float, width: Float) -> Rect { let x = middleLeft.x let y = middleLeft.y - height.half let frame = Rect(x: x, y: y, width: width, height: height) return frame } } // MARK: - Set A Length - // MARK: Width extension IndividualProperty.MiddleLeftHeight: LayoutPropertyCanStoreWidthToEvaluateFrameType { public func evaluateFrame(width: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect { let middleLeft = self.middleLeft.evaluated(from: parameters) let height = self.height.evaluated(from: parameters, withTheOtherAxis: .width(0)) let width = width.evaluated(from: parameters, withTheOtherAxis: .height(height)) return self.makeFrame(middleLeft: middleLeft, height: height, width: width) } }
apache-2.0
75e9b8cedffc824ba1e06af941115974
22.269231
115
0.729752
3.817035
false
false
false
false
stripe/stripe-ios
StripeIdentity/StripeIdentity/Source/NativeComponents/ML/Helpers/NonMaxSuppression.swift
1
7060
// // Taken from https://github.com/hollance/CoreMLHelpers/blob/master/CoreMLHelpers/NonMaxSuppression.swift // // Copyright (c) 2017-2019 M.I. Hollemans // // 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 Accelerate import Foundation protocol MLBoundingBox { /// Index of the predicted class. var classIndex: Int { get } /// Confidence score. var score: Float { get } /// Normalized coordinates between 0 and 1. var rect: CGRect { get } } // Computes intersection-over-union overlap between two bounding boxes. func IOU(_ a: CGRect, _ b: CGRect) -> Float { let areaA = a.width * a.height if areaA <= 0 { return 0 } let areaB = b.width * b.height if areaB <= 0 { return 0 } let intersectionMinX = max(a.minX, b.minX) let intersectionMinY = max(a.minY, b.minY) let intersectionMaxX = min(a.maxX, b.maxX) let intersectionMaxY = min(a.maxY, b.maxY) let intersectionArea = max(intersectionMaxY - intersectionMinY, 0) * max(intersectionMaxX - intersectionMinX, 0) return Float(intersectionArea / (areaA + areaB - intersectionArea)) } // Removes bounding boxes that overlap too much with other boxes that have // a higher score. func nonMaxSuppression( boundingBoxes: [MLBoundingBox], iouThreshold: Float, maxBoxes: Int ) -> [Int] { return nonMaxSuppression( boundingBoxes: boundingBoxes, indices: Array(boundingBoxes.indices), iouThreshold: iouThreshold, maxBoxes: maxBoxes ) } // Removes bounding boxes that overlap too much with other boxes that have // a higher score. // // Based on code from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/non_max_suppression_op.cc // // - Note: This version of NMS ignores the class of the bounding boxes. Since it // selects the bounding boxes in a greedy fashion, if a certain class has many // boxes that are selected, then it is possible none of the boxes of the other // classes get selected. // // - Parameters: // - boundingBoxes: an array of bounding boxes and their scores // - indices: which predictions to look at // - iouThreshold: used to decide whether boxes overlap too much // - maxBoxes: the maximum number of boxes that will be selected // // - Returns: the array indices of the selected bounding boxes func nonMaxSuppression( boundingBoxes: [MLBoundingBox], indices: [Int], iouThreshold: Float, maxBoxes: Int ) -> [Int] { // Sort the boxes based on their confidence scores, from high to low. let sortedIndices = indices.sorted { boundingBoxes[$0].score > boundingBoxes[$1].score } var selected: [Int] = [] // Loop through the bounding boxes, from highest score to lowest score, // and determine whether or not to keep each box. for i in 0..<sortedIndices.count { if selected.count >= maxBoxes { break } var shouldSelect = true let boxA = boundingBoxes[sortedIndices[i]] // Does the current box overlap one of the selected boxes more than the // given threshold amount? Then it's too similar, so don't keep it. for j in 0..<selected.count { let boxB = boundingBoxes[selected[j]] if IOU(boxA.rect, boxB.rect) > iouThreshold { shouldSelect = false break } } // This bounding box did not overlap too much with any previously selected // bounding box, so we'll keep it. if shouldSelect { selected.append(sortedIndices[i]) } } return selected } // Multi-class version of non maximum suppression. // // Where `nonMaxSuppression()` does not look at the class of the predictions at // all, the multi-class version first selects the best bounding boxes for each // class, and then keeps the best ones of those. // // With this method you can usually expect to see at least one bounding box for // each class (unless all the scores for a given class are really low). // // Based on code from: https://github.com/tensorflow/models/blob/master/object_detection/core/post_processing.py // // - Parameters: // - numClasses: the number of classes // - boundingBoxes: an array of bounding boxes and their scores // - scoreThreshold: used to only keep bounding boxes with a high enough score // - iouThreshold: used to decide whether boxes overlap too much // - maxPerClass: the maximum number of boxes that will be selected per class // - maxTotal: maximum number of boxes that will be selected over all classes // // - Returns: the array indices of the selected bounding boxes func nonMaxSuppressionMultiClass( numClasses: Int, boundingBoxes: [MLBoundingBox], scoreThreshold: Float, iouThreshold: Float, maxPerClass: Int, maxTotal: Int ) -> [Int] { var selectedBoxes: [Int] = [] // Look at all the classes one-by-one. for c in 0..<numClasses { var filteredBoxes = [Int]() // Look at every bounding box for this class. for p in 0..<boundingBoxes.count { let prediction = boundingBoxes[p] if prediction.classIndex == c { // Only keep the box if its score is over the threshold. if prediction.score > scoreThreshold { filteredBoxes.append(p) } } } // Only keep the best bounding boxes for this class. let nmsBoxes = nonMaxSuppression( boundingBoxes: boundingBoxes, indices: filteredBoxes, iouThreshold: iouThreshold, maxBoxes: maxPerClass ) // Add the indices of the surviving boxes to the big list. selectedBoxes.append(contentsOf: nmsBoxes) } // Sort all the surviving boxes by score and only keep the best ones. let sortedBoxes = selectedBoxes.sorted { boundingBoxes[$0].score > boundingBoxes[$1].score } return Array(sortedBoxes.prefix(maxTotal)) }
mit
b20b11125699d1bf5cc40e849f547ebc
36.553191
125
0.677479
4.162736
false
false
false
false
ello/ello-ios
Sources/Networking/ElloRequest.swift
1
328
//// /// ElloRequest.swift // import Moya struct ElloRequest { let url: URL let method: Moya.Method let parameters: [String: Any]? init(url: URL, method: Moya.Method = .get, parameters: [String: Any]? = nil) { self.url = url self.method = method self.parameters = parameters } }
mit
74eab17c668db0e032e6dddd9a28c83b
17.222222
82
0.591463
3.604396
false
false
false
false
wibosco/ApproachingParsers
ApproachingParsers/Networking/Questions/QuestionsAPIManager.swift
1
1215
// // QuestionsAPIManager.swift // ApproachingParsers // // Created by Home on 28/02/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit class QuestionsAPIManager: NSObject { class func retrieveQuestions(feed: Feed, refresh: Bool, completion:((successful: Bool) -> Void)?){ var url: NSURL if (feed.pages!.count > 0) { let page = feed.orderedPages().last! url = NSURL(string: page.nextHref!)! } else { url = NSURL(string: kStackOverflowQuestionsBaseURL as String)! } let feedManagedObjectID = feed.objectID let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in let operation = QuestionsRetrievalOperationValidator.init(feedID: feedManagedObjectID, data: data!, refresh: refresh, completion: completion) QueueManager.sharedInstance.queue.addOperation(operation) }) } task.resume() } }
mit
de572bc79050e0b8c35ad7d92facbef4
30.947368
157
0.595552
4.742188
false
false
false
false
lioonline/Swift
NSBlockOperation/NSBlockOperation/ViewController.swift
1
2464
// // ViewController.swift // NSBlockOperation // // Created by Carlos Butron on 02/12/14. // Copyright (c) 2014 Carlos Butron. // // This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License along with this program. If not, see // http:/www.gnu.org/licenses/. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { var queue = NSOperationQueue() let operation1 : NSBlockOperation = NSBlockOperation ( { self.getWebs() let operation2 : NSBlockOperation = NSBlockOperation({ self.loadWebs() }) queue.addOperation(operation2) }) queue.addOperation(operation1) super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadWebs(){ let urls : NSMutableArray = NSMutableArray (objects:NSURL(string:"http://www.google.es")!, NSURL(string: "http://www.apple.com")!,NSURL(string: "http://carlosbutron.es")!, NSURL(string: "http://www.bing.com")!,NSURL(string: "http://www.yahoo.com")!) urls.addObjectsFromArray(googlewebs) for iterator:AnyObject in urls{ NSData(contentsOfURL:iterator as NSURL) println("Downloaded \(iterator)") } } var googlewebs:NSArray = [] func getWebs(){ let languages:NSArray = ["com","ad","ae","com.af","com.ag","com.ai","am","co.ao","com.ar","as","at"] var languageWebs = NSMutableArray() for(var i=0;i < languages.count; i++){ var webString: NSString = "http://www.google.\(languages[i])" languageWebs.addObject(NSURL(fileURLWithPath: webString)!) } googlewebs = languageWebs } }
gpl-3.0
f9d9935a132a187d4dbd93051bb73704
31.421053
257
0.614042
4.597015
false
false
false
false
mozilla-mobile/focus-ios
BlockzillaPackage/Sources/UIComponents/AsyncImageView.swift
1
2278
/* 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 UIHelpers public class AsyncImageView: UIView { private lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() private lazy var activityIndicator = UIActivityIndicatorView(style: .large) private lazy var loader = ImageLoader.shared public var defaultImage: UIImage? { didSet { imageView.image = defaultImage } } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } func commonInit() { addSubview(imageView) addSubview(activityIndicator) activityIndicator.hidesWhenStopped = true activityIndicator.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ imageView.topAnchor.constraint(equalTo: topAnchor), imageView.bottomAnchor.constraint(equalTo: bottomAnchor), imageView.leadingAnchor.constraint(equalTo: leadingAnchor), imageView.trailingAnchor.constraint(equalTo: trailingAnchor), activityIndicator.centerXAnchor.constraint(equalTo: centerXAnchor), activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor) ]) } public func load(imageURL: URL, defaultImage: UIImage) { activityIndicator.startAnimating() loader.loadImage(imageURL) { [weak self] result in DispatchQueue.main.async { switch result { case .success(let image): self?.activityIndicator.stopAnimating() self?.imageView.image = image case .failure: self?.activityIndicator.stopAnimating() self?.imageView.image = defaultImage } } } } }
mpl-2.0
7d330c370f8fa0f1ab27c55f7f321baf
32.014493
79
0.629939
5.752525
false
false
false
false
SwifterSwift/SwifterSwift
Sources/SwifterSwift/UIKit/UIScrollViewExtensions.swift
1
6210
// UIScrollViewExtensions.swift - Copyright 2020 SwifterSwift #if canImport(UIKit) && !os(watchOS) import UIKit // MARK: - Methods public extension UIScrollView { /// SwifterSwift: Takes a snapshot of an entire ScrollView. /// /// AnySubclassOfUIScrollView().snapshot /// UITableView().snapshot /// /// - Returns: Snapshot as UIImage for rendered ScrollView. var snapshot: UIImage? { // Original Source: https://gist.github.com/thestoics/1204051 UIGraphicsBeginImageContextWithOptions(contentSize, false, 0) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext() else { return nil } let previousFrame = frame frame = CGRect(origin: frame.origin, size: contentSize) layer.render(in: context) frame = previousFrame return UIGraphicsGetImageFromCurrentImageContext() } /// SwifterSwift: The currently visible region of the scroll view. var visibleRect: CGRect { let contentWidth = contentSize.width - contentOffset.x let contentHeight = contentSize.height - contentOffset.y return CGRect(origin: contentOffset, size: CGSize(width: min(min(bounds.size.width, contentSize.width), contentWidth), height: min(min(bounds.size.height, contentSize.height), contentHeight))) } } public extension UIScrollView { /// SwifterSwift: Scroll to the top-most content offset. /// - Parameter animated: `true` to animate the transition at a constant velocity to the new offset, `false` to make the transition immediate. func scrollToTop(animated: Bool = true) { setContentOffset(CGPoint(x: contentOffset.x, y: -contentInset.top), animated: animated) } /// SwifterSwift: Scroll to the left-most content offset. /// - Parameter animated: `true` to animate the transition at a constant velocity to the new offset, `false` to make the transition immediate. func scrollToLeft(animated: Bool = true) { setContentOffset(CGPoint(x: -contentInset.left, y: contentOffset.y), animated: animated) } /// SwifterSwift: Scroll to the bottom-most content offset. /// - Parameter animated: `true` to animate the transition at a constant velocity to the new offset, `false` to make the transition immediate. func scrollToBottom(animated: Bool = true) { setContentOffset( CGPoint(x: contentOffset.x, y: max(0, contentSize.height - bounds.height) + contentInset.bottom), animated: animated) } /// SwifterSwift: Scroll to the right-most content offset. /// - Parameter animated: `true` to animate the transition at a constant velocity to the new offset, `false` to make the transition immediate. func scrollToRight(animated: Bool = true) { setContentOffset( CGPoint(x: max(0, contentSize.width - bounds.width) + contentInset.right, y: contentOffset.y), animated: animated) } /// SwifterSwift: Scroll up one page of the scroll view. /// If `isPagingEnabled` is `true`, the previous page location is used. /// - Parameter animated: `true` to animate the transition at a constant velocity to the new offset, `false` to make the transition immediate. func scrollUp(animated: Bool = true) { let minY = -contentInset.top var y = max(minY, contentOffset.y - bounds.height) #if !os(tvOS) if isPagingEnabled, bounds.height != 0 { let page = max(0, ((y + contentInset.top) / bounds.height).rounded(.down)) y = max(minY, page * bounds.height - contentInset.top) } #endif setContentOffset(CGPoint(x: contentOffset.x, y: y), animated: animated) } /// SwifterSwift: Scroll left one page of the scroll view. /// If `isPagingEnabled` is `true`, the previous page location is used. /// - Parameter animated: `true` to animate the transition at a constant velocity to the new offset, `false` to make the transition immediate. func scrollLeft(animated: Bool = true) { let minX = -contentInset.left var x = max(minX, contentOffset.x - bounds.width) #if !os(tvOS) if isPagingEnabled, bounds.width != 0 { let page = ((x + contentInset.left) / bounds.width).rounded(.down) x = max(minX, page * bounds.width - contentInset.left) } #endif setContentOffset(CGPoint(x: x, y: contentOffset.y), animated: animated) } /// SwifterSwift: Scroll down one page of the scroll view. /// If `isPagingEnabled` is `true`, the next page location is used. /// - Parameter animated: `true` to animate the transition at a constant velocity to the new offset, `false` to make the transition immediate. func scrollDown(animated: Bool = true) { let maxY = max(0, contentSize.height - bounds.height) + contentInset.bottom var y = min(maxY, contentOffset.y + bounds.height) #if !os(tvOS) if isPagingEnabled, bounds.height != 0 { let page = ((y + contentInset.top) / bounds.height).rounded(.down) y = min(maxY, page * bounds.height - contentInset.top) } #endif setContentOffset(CGPoint(x: contentOffset.x, y: y), animated: animated) } /// SwifterSwift: Scroll right one page of the scroll view. /// If `isPagingEnabled` is `true`, the next page location is used. /// - Parameter animated: `true` to animate the transition at a constant velocity to the new offset, `false` to make the transition immediate. func scrollRight(animated: Bool = true) { let maxX = max(0, contentSize.width - bounds.width) + contentInset.right var x = min(maxX, contentOffset.x + bounds.width) #if !os(tvOS) if isPagingEnabled, bounds.width != 0 { let page = ((x + contentInset.left) / bounds.width).rounded(.down) x = min(maxX, page * bounds.width - contentInset.left) } #endif setContentOffset(CGPoint(x: x, y: contentOffset.y), animated: animated) } } #endif
mit
863a702fa675fc40d24b9a682575147f
45.691729
146
0.650403
4.513081
false
false
false
false
universonic/shadowsocks-macos
Shadowsocks/LaunchAgentUtils.swift
1
14036
// // BGUtils.swift // Shadowsocks // // Created by 邱宇舟 on 16/6/6. // Copyright 2019 Shadowsocks Community. All rights reserved. // import Foundation let SS_LOCAL_VERSION = "3.1.3" let KCPTUN_CLIENT_VERSION = "v20170718" let V2RAY_PLUGIN_VERSION = "master" let PRIVOXY_VERSION = "3.0.26.static" let SIMPLE_OBFS_VERSION = "0.0.5_1" let APP_SUPPORT_DIR = "/Library/Application Support/Shadowsocks/" let LAUNCH_AGENT_DIR = "/Library/LaunchAgents/" let LAUNCH_AGENT_CONF_SSLOCAL_NAME = "com.qiuyuzhou.Shadowsocks.local.plist" let LAUNCH_AGENT_CONF_PRIVOXY_NAME = "com.qiuyuzhou.Shadowsocks.http.plist" let LAUNCH_AGENT_CONF_KCPTUN_NAME = "com.qiuyuzhou.Shadowsocks.kcptun.plist" func getFileSHA1Sum(_ filepath: String) -> String { if let data = try? Data(contentsOf: URL(fileURLWithPath: filepath)) { return data.sha1() } return "" } // Ref: https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html // Genarate the mac launch agent service plist // MARK: sslocal func generateSSLocalLauchAgentPlist() -> Bool { let sslocalPath = NSHomeDirectory() + APP_SUPPORT_DIR + "ss-local-latest/ss-local" let logFilePath = NSHomeDirectory() + "/Library/Logs/ss-local.log" let launchAgentDirPath = NSHomeDirectory() + LAUNCH_AGENT_DIR let plistFilepath = launchAgentDirPath + LAUNCH_AGENT_CONF_SSLOCAL_NAME // Ensure launch agent directory is existed. let fileMgr = FileManager.default if !fileMgr.fileExists(atPath: launchAgentDirPath) { try! fileMgr.createDirectory(atPath: launchAgentDirPath, withIntermediateDirectories: true, attributes: nil) } let oldSha1Sum = getFileSHA1Sum(plistFilepath) let defaults = UserDefaults.standard let enableUdpRelay = defaults.bool(forKey: "LocalSocks5.EnableUDPRelay") let enableVerboseMode = defaults.bool(forKey: "LocalSocks5.EnableVerboseMode") var arguments = [sslocalPath, "-c", "ss-local-config.json", "--fast-open"] if enableUdpRelay { arguments.append("-u") } if enableVerboseMode { arguments.append("-v") } arguments.append("--reuse-port") // For a complete listing of the keys, see the launchd.plist manual page. let dyld_library_paths = [ NSHomeDirectory() + APP_SUPPORT_DIR + "ss-local-latest/", NSHomeDirectory() + APP_SUPPORT_DIR + "plugins/", ] let dict: NSMutableDictionary = [ "Label": "com.qiuyuzhou.Shadowsocks.local", "WorkingDirectory": NSHomeDirectory() + APP_SUPPORT_DIR, "StandardOutPath": logFilePath, "StandardErrorPath": logFilePath, "ProgramArguments": arguments, "EnvironmentVariables": ["DYLD_LIBRARY_PATH": dyld_library_paths.joined(separator: ":")] ] dict.write(toFile: plistFilepath, atomically: true) let Sha1Sum = getFileSHA1Sum(plistFilepath) if oldSha1Sum != Sha1Sum { NSLog("generateSSLocalLauchAgentPlist - File has been changed.") return true } else { NSLog("generateSSLocalLauchAgentPlist - File has not been changed.") return false } } func StartSSLocal() { let bundle = Bundle.main let installerPath = bundle.path(forResource: "start_ss_local.sh", ofType: nil) let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Start ss-local succeeded.") } else { NSLog("Start ss-local failed.") } } func StopSSLocal() { let bundle = Bundle.main let installerPath = bundle.path(forResource: "stop_ss_local.sh", ofType: nil) let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Stop ss-local succeeded.") } else { NSLog("Stop ss-local failed.") } } func InstallSSLocal() { let fileMgr = FileManager.default let homeDir = NSHomeDirectory() let appSupportDir = homeDir+APP_SUPPORT_DIR if !fileMgr.fileExists(atPath: appSupportDir + "ss-local-\(SS_LOCAL_VERSION)/ss-local") || !fileMgr.fileExists(atPath: appSupportDir + "ss-local-\(SS_LOCAL_VERSION)/libmbedcrypto.0.dylib") { let bundle = Bundle.main let installerPath = bundle.path(forResource: "install_ss_local.sh", ofType: nil) let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Install ss-local succeeded.") } else { NSLog("Install ss-local failed.") } } } func writeSSLocalConfFile(_ conf:[String:AnyObject]) -> Bool { do { let filepath = NSHomeDirectory() + APP_SUPPORT_DIR + "ss-local-config.json" let data: Data = try JSONSerialization.data(withJSONObject: conf, options: .prettyPrinted) let oldSum = getFileSHA1Sum(filepath) try data.write(to: URL(fileURLWithPath: filepath), options: .atomic) let newSum = data.sha1() if oldSum == newSum { NSLog("writeSSLocalConfFile - File has not been changed.") return false } NSLog("writeSSLocalConfFile - File has been changed.") return true } catch { NSLog("Write ss-local file failed.") } return false } func removeSSLocalConfFile() { do { let filepath = NSHomeDirectory() + APP_SUPPORT_DIR + "ss-local-config.json" try FileManager.default.removeItem(atPath: filepath) } catch { } } func SyncSSLocal() { var changed: Bool = false changed = changed || generateSSLocalLauchAgentPlist() let mgr = ServerProfileManager.instance if mgr.activeProfileId != nil { if let profile = mgr.getActiveProfile() { changed = changed || writeSSLocalConfFile((profile.toJsonConfig())) } let on = UserDefaults.standard.bool(forKey: "ShadowsocksOn") if on { if changed { StopSSLocal() DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + DispatchTimeInterval.seconds(1), execute: { () in StartSSLocal() }) } else { StartSSLocal() } } else { StopSSLocal() } } else { removeSSLocalConfFile() StopSSLocal() } SyncPac() SyncPrivoxy() } // -------------------------------------------------------------------------------- // MARK: simple-obfs func InstallSimpleObfs() { let fileMgr = FileManager.default let homeDir = NSHomeDirectory() let appSupportDir = homeDir + APP_SUPPORT_DIR if !fileMgr.fileExists(atPath: appSupportDir + "simple-obfs-\(SIMPLE_OBFS_VERSION)/obfs-local") || !fileMgr.fileExists(atPath: appSupportDir + "plugins/obfs-local") { let bundle = Bundle.main let installerPath = bundle.path(forResource: "install_simple_obfs.sh", ofType: nil) let task = Process.launchedProcess(launchPath: "/bin/sh", arguments: [installerPath!]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Install simple-obfs succeeded.") } else { NSLog("Install simple-obfs failed.") } } } // -------------------------------------------------------------------------------- // MARK: kcptun func InstallKcptun() { let fileMgr = FileManager.default let homeDir = NSHomeDirectory() let appSupportDir = homeDir+APP_SUPPORT_DIR if !fileMgr.fileExists(atPath: appSupportDir + "kcptun_\(KCPTUN_CLIENT_VERSION)/kcptun_client") { let bundle = Bundle.main let installerPath = bundle.path(forResource: "install_kcptun", ofType: "sh") let task = Process.launchedProcess(launchPath: "/bin/sh", arguments: [installerPath!]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Install kcptun succeeded.") } else { NSLog("Install kcptun failed.") } } } // -------------------------------------------------------------------------------- // MARK: v2ray-plugin func InstallV2rayPlugin() { let fileMgr = FileManager.default let homeDir = NSHomeDirectory() let appSupportDir = homeDir+APP_SUPPORT_DIR if !fileMgr.fileExists(atPath: appSupportDir + "v2ray-plugin_\(V2RAY_PLUGIN_VERSION)/v2ray-plugin") { let bundle = Bundle.main let installerPath = bundle.path(forResource: "install_v2ray_plugin", ofType: "sh") let task = Process.launchedProcess(launchPath: "/bin/sh", arguments: [installerPath!]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Install v2ray-plugin succeeded.") } else { NSLog("Install v2ray-plugin failed.") } } } // -------------------------------------------------------------------------------- // MARK: privoxy func generatePrivoxyLauchAgentPlist() -> Bool { let privoxyPath = NSHomeDirectory() + APP_SUPPORT_DIR + "privoxy" let logFilePath = NSHomeDirectory() + "/Library/Logs/privoxy.log" let launchAgentDirPath = NSHomeDirectory() + LAUNCH_AGENT_DIR let plistFilepath = launchAgentDirPath + LAUNCH_AGENT_CONF_PRIVOXY_NAME // Ensure launch agent directory is existed. let fileMgr = FileManager.default if !fileMgr.fileExists(atPath: launchAgentDirPath) { try! fileMgr.createDirectory(atPath: launchAgentDirPath, withIntermediateDirectories: true, attributes: nil) } let oldSha1Sum = getFileSHA1Sum(plistFilepath) let arguments = [privoxyPath, "--no-daemon", "privoxy.config"] // For a complete listing of the keys, see the launchd.plist manual page. let dict: NSMutableDictionary = [ "Label": "com.qiuyuzhou.Shadowsocks.http", "WorkingDirectory": NSHomeDirectory() + APP_SUPPORT_DIR, "StandardOutPath": logFilePath, "StandardErrorPath": logFilePath, "ProgramArguments": arguments ] dict.write(toFile: plistFilepath, atomically: true) let Sha1Sum = getFileSHA1Sum(plistFilepath) if oldSha1Sum != Sha1Sum { return true } else { return false } } func StartPrivoxy() { let bundle = Bundle.main let installerPath = bundle.path(forResource: "start_privoxy.sh", ofType: nil) let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Start privoxy succeeded.") } else { NSLog("Start privoxy failed.") } } func StopPrivoxy() { let bundle = Bundle.main let installerPath = bundle.path(forResource: "stop_privoxy.sh", ofType: nil) let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Stop privoxy succeeded.") } else { NSLog("Stop privoxy failed.") } } func InstallPrivoxy() { let fileMgr = FileManager.default let homeDir = NSHomeDirectory() let appSupportDir = homeDir+APP_SUPPORT_DIR if !fileMgr.fileExists(atPath: appSupportDir + "privoxy-\(PRIVOXY_VERSION)/privoxy") { let bundle = Bundle.main let installerPath = bundle.path(forResource: "install_privoxy.sh", ofType: nil) let task = Process.launchedProcess(launchPath: installerPath!, arguments: [""]) task.waitUntilExit() if task.terminationStatus == 0 { NSLog("Install privoxy succeeded.") } else { NSLog("Install privoxy failed.") } } } func writePrivoxyConfFile() -> Bool { do { let defaults = UserDefaults.standard let bundle = Bundle.main let examplePath = bundle.path(forResource: "privoxy.config.example", ofType: nil) var example = try String(contentsOfFile: examplePath!, encoding: .utf8) example = example.replacingOccurrences(of: "{http}", with: defaults.string(forKey: "LocalHTTP.ListenAddress")! + ":" + String(defaults.integer(forKey: "LocalHTTP.ListenPort"))) example = example.replacingOccurrences(of: "{socks5}", with: defaults.string(forKey: "LocalSocks5.ListenAddress")! + ":" + String(defaults.integer(forKey: "LocalSocks5.ListenPort"))) let data = example.data(using: .utf8) let filepath = NSHomeDirectory() + APP_SUPPORT_DIR + "privoxy.config" let oldSum = getFileSHA1Sum(filepath) try data?.write(to: URL(fileURLWithPath: filepath), options: .atomic) let newSum = getFileSHA1Sum(filepath) if oldSum == newSum { return false } return true } catch { NSLog("Write privoxy file failed.") } return false } func removePrivoxyConfFile() { do { let filepath = NSHomeDirectory() + APP_SUPPORT_DIR + "privoxy.config" try FileManager.default.removeItem(atPath: filepath) } catch { } } func SyncPrivoxy() { var changed: Bool = false changed = changed || generatePrivoxyLauchAgentPlist() let mgr = ServerProfileManager.instance if mgr.activeProfileId != nil { changed = changed || writePrivoxyConfFile() let on = UserDefaults.standard.bool(forKey: "LocalHTTPOn") if on { if changed { StopPrivoxy() DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + DispatchTimeInterval.seconds(1), execute: { () in StartPrivoxy() }) } else { StartPrivoxy() } } else { StopPrivoxy() } } else { removePrivoxyConfFile() StopPrivoxy() } }
gpl-3.0
77d0fd31650c4198a492f76414f40dc5
34.609137
190
0.621597
4.122833
false
false
false
false
maeikei/SM.RC.4WD
RC/ble.rc.4wd.ios/ble.rc.4wd.ios/AppDelegate.swift
2
6116
// // AppDelegate.swift // ble.rc.4wd.ios // // Created by 馬 英奎 on 2016/08/07. // Copyright © 2016年 馬 英奎. 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 "org.RobotTeam2.ble_rc_4wd_ios" 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("ble_rc_4wd_ios", 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() } } } }
mit
34e2e951ad751eb97aacb489ab0a8ffa
53.963964
291
0.718407
5.750236
false
false
false
false
Arbalest313/THImageBrowser
THImageBrowser/ViewController.swift
1
2844
// // ViewController.swift // THImageBrowser // // Created by Apple on 16/10/25. // Copyright © 2016年 Tsao. All rights reserved. // import UIKit import SDWebImage class ViewController: UIViewController { @IBOutlet weak var showImage: UIButton! @IBOutlet weak var v1: UIImageView! @IBOutlet weak var v2: UIImageView! @IBOutlet weak var v4: UIImageView! @IBOutlet weak var v3: UIImageView! //thumb300,or360 var compressedURL = [ "http://ww3.sinaimg.cn/or480/7828dd47jw1f94xrskwvhj20u00u0god.jpg", "http://ww2.sinaimg.cn/or480/6ba7ecc9gw1f93x9rc2zwj21kw11xdq6.jpg", "http://ww2.sinaimg.cn/or480/6ba7ecc9gw1f93x6lhk6lj21kw11xgvz.jpg", "http://ww4.sinaimg.cn/or480/6ba7ecc9gw1f93x708zbij21kw11xdt7.jpg", ] //mw1024,woriginal var originalURL = [ "http://ww3.sinaimg.cn/woriginal/7828dd47jw1f94xrskwvhj20u00u0god.jpg", "http://ww2.sinaimg.cn/woriginal/6ba7ecc9gw1f93x9rc2zwj21kw11xdq6.jpg", "http://ww2.sinaimg.cn/woriginal/6ba7ecc9gw1f93x6lhk6lj21kw11xgvz.jpg", "http://ww4.sinaimg.cn/woriginal/6ba7ecc9gw1f93x708zbij21kw11xdt7.jpg", ] func url(string:String) -> URL! { return URL(string: string); } override func viewDidLoad() { super.viewDidLoad() for view in view.subviews { view.contentMode = .scaleAspectFill view.clipsToBounds = true } // SDImageCache.shared().clearDisk() // SDImageCache.shared().clearMemory() // Do any additional setup after loading the view, typically from a nib. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // SDImageCache.shared().cleanDisk() v1.sd_setImage(with:url(string:compressedURL[0])) v2.sd_setImage(with:url(string:compressedURL[1])) v3.sd_setImage(with:url(string:compressedURL[2])) v4.sd_setImage(with:url(string:compressedURL[3])) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func showImage(_ sender: UIGestureRecognizer) { let numberOfViews = 3 BrowserPageViewController.show(startAt:(sender.view?.tag)!-1, sourceAt:{ (index) -> BrowserViewable? in if index > numberOfViews || index<0{return nil} let viewable = BrowserViewable() viewable.index = index viewable.imageUrl = self.originalURL[index] let imageV = self.view.viewWithTag(index + 1) as! UIImageView viewable.placeholder = imageV.image return viewable }).configurableFade(inView:sender.view!, outView: { (index) -> UIView? in return self.view.viewWithTag(index+1) }) } }
mit
4bed2c343e837092c60395fc1a840b02
34.074074
111
0.654699
3.56015
false
false
false
false
debugsquad/nubecero
nubecero/Model/OnboardForm/MOnboardFormItemPassGenerator.swift
1
2871
import UIKit class MOnboardFormItemPassGenerator:MOnboardFormItem { typealias Password = String private let kCellHeight:CGFloat = 42 private let kPasswordMinLength:Int = 6 private let kPasswordExtensionLength:UInt32 = 7 private let kMinLowerCaseUnicode:Int = 65 private let kLowerCaseUnicodeRange:UInt32 = 26 private let kMinUpperCaseUnicode:Int = 97 private let kUpperCaseUnicodeRange:UInt32 = 26 private let kMinNumericUnicode:Int = 48 private let kNumericUnicodeRange:UInt32 = 10 override init() { let reusableIdentifier:String = VOnboardFormCellPassGenerator.reusableIdentifier super.init( reusableIdentifier:reusableIdentifier, cellHeight:kCellHeight) } override init(reusableIdentifier:String, cellHeight:CGFloat) { fatalError() } //MARK: private private func lowerCaseUnicode() -> Int { let unicodeValue:Int = kMinLowerCaseUnicode + Int(arc4random_uniform(kLowerCaseUnicodeRange)) return unicodeValue } private func upperCaseUnicode() -> Int { let unicodeValue:Int = kMinUpperCaseUnicode + Int(arc4random_uniform(kUpperCaseUnicodeRange)) return unicodeValue } private func numericUnicode() -> Int { let unicodeValue:Int = kMinNumericUnicode + Int(arc4random_uniform(kNumericUnicodeRange)) return unicodeValue } private func passwordItem() -> String { let unicodeValue:Int let unicode:UnicodeScalar let character:Character let string:String let selectUnicode:UInt32 = arc4random_uniform(3) switch selectUnicode { case 0: unicodeValue = lowerCaseUnicode() break case 1: unicodeValue = upperCaseUnicode() break case 2: unicodeValue = numericUnicode() break default: unicodeValue = kMinNumericUnicode break } unicode = UnicodeScalar(unicodeValue)! character = Character(unicode) string = String(character) return string } //MARK: public func generatePassword() -> Password { let extendPassword:Int = Int(arc4random_uniform(kPasswordExtensionLength)) let passwordLength:Int = kPasswordMinLength + extendPassword var password:Password = "" for _:Int in 0 ..< passwordLength { password += passwordItem() } return password } }
mit
192f422f535db1641fc4b2153ef65fc8
25.33945
101
0.575061
5.618395
false
false
false
false
wleofeng/UpChallenge
UpChallenge/UpChallenge/VoicesTableViewController.swift
1
1617
// // VoicesTableViewController.swift // UpChallenge // // Created by Wo Jun Feng on 3/30/17. // Copyright © 2017 wojunfeng. All rights reserved. // import UIKit import AVFoundation protocol VoicesTableViewControllerDelegate: class { func didSelectVoice(voicesTableViewController: VoicesTableViewController) } class VoicesTableViewController: UITableViewController { var voices: [AVSpeechSynthesisVoice] = [] var selectedVoice: AVSpeechSynthesisVoice? weak var delegate: VoicesTableViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() self.navigationController?.setNavigationBarHidden(false, animated: true) self.clearsSelectionOnViewWillAppear = false } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return voices.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "VoicesTableViewCell", for: indexPath) let voice = voices[indexPath.row] cell.textLabel?.text = voice.name return cell } // MARK: Table view delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedVoice = voices[indexPath.row] self.delegate?.didSelectVoice(voicesTableViewController: self) self.navigationController?.popViewController(animated: true) } }
mit
99b4a4c59479436c061dec5e2ddd8114
28.381818
109
0.701733
5.386667
false
false
false
false
kello711/HackingWithSwift
project33/Project33/ResultsViewController.swift
1
6408
// // ResultsViewController.swift // Project33 // // Created by Hudzilla on 19/09/2015. // Copyright © 2015 Paul Hudson. All rights reserved. // import AVFoundation import CloudKit import UIKit class ResultsViewController: UITableViewController { var whistle: Whistle! var suggestions = [String]() var whistlePlayer: AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() title = "Genre: \(whistle.genre)" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Download", style: .Plain, target: self, action: #selector(downloadTapped)) tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") let reference = CKReference(recordID: whistle.recordID, action: CKReferenceAction.DeleteSelf) let pred = NSPredicate(format: "owningWhistle == %@", reference) let sort = NSSortDescriptor(key: "creationDate", ascending: true) let query = CKQuery(recordType: "Suggestions", predicate: pred) query.sortDescriptors = [sort] CKContainer.defaultContainer().publicCloudDatabase.performQuery(query, inZoneWithID: nil) { [unowned self] (results, error) -> Void in if error == nil { if let results = results { self.parseResults(results) } } else { print(error!.localizedDescription) } } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 1 { return "Suggested songs" } return nil } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } else { return max(1, suggestions.count + 1) } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) cell.selectionStyle = .None cell.textLabel?.numberOfLines = 0 if indexPath.section == 0 { // the user's comments about this whistle cell.textLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleTitle1) if whistle.comments.characters.count == 0 { cell.textLabel?.text = "Comments: None" } else { cell.textLabel?.text = whistle.comments } } else { cell.textLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) if indexPath.row == suggestions.count { // this is our extra row cell.textLabel?.text = "Add suggestion" cell.selectionStyle = .Gray } else { cell.textLabel?.text = suggestions[indexPath.row] } } return cell } override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { guard indexPath.section == 1 && indexPath.row == suggestions.count else { return } tableView.deselectRowAtIndexPath(indexPath, animated: true) let ac = UIAlertController(title: "Suggest a song…", message: nil, preferredStyle: .Alert) var suggestion: UITextField! ac.addTextFieldWithConfigurationHandler { (textField) -> Void in suggestion = textField textField.autocorrectionType = .Yes } ac.addAction(UIAlertAction(title: "Submit", style: .Default) { (action) -> Void in if suggestion.text?.characters.count > 0 { self.addSuggestion(suggestion.text!) } }) ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) presentViewController(ac, animated: true, completion: nil) } func addSuggestion(suggest: String) { let whistleRecord = CKRecord(recordType: "Suggestions") let reference = CKReference(recordID: whistle.recordID, action: .DeleteSelf) whistleRecord["text"] = suggest whistleRecord["owningWhistle"] = reference CKContainer.defaultContainer().publicCloudDatabase.saveRecord(whistleRecord) { [unowned self] (record, error) -> Void in dispatch_async(dispatch_get_main_queue()) { if error == nil { self.suggestions.append(suggest) self.tableView.reloadData() } else { let ac = UIAlertController(title: "Error", message: "There was a problem submitting your suggestion: \(error!.localizedDescription)", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(ac, animated: true, completion: nil) } } } } func parseResults(records: [CKRecord]) { var newSuggestions = [String]() for record in records { newSuggestions.append(record["text"] as! String) } dispatch_async(dispatch_get_main_queue()) { self.suggestions = newSuggestions self.tableView.reloadData() } } func downloadTapped() { let spinner = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) spinner.tintColor = UIColor.blackColor() spinner.startAnimating() navigationItem.rightBarButtonItem = UIBarButtonItem(customView: spinner) CKContainer.defaultContainer().publicCloudDatabase.fetchRecordWithID(whistle.recordID) { [unowned self] (record, error) -> Void in if error == nil { if let record = record { if let asset = record["audio"] as? CKAsset { self.whistle.audio = asset.fileURL dispatch_async(dispatch_get_main_queue()) { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Listen", style: .Plain, target: self, action: #selector(self.listenTapped)) } } } } else { dispatch_async(dispatch_get_main_queue()) { // meaningful error message here! self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Download", style: .Plain, target: self, action: #selector(self.downloadTapped)) } } } } func listenTapped() { do { whistlePlayer = try AVAudioPlayer(contentsOfURL: whistle.audio) whistlePlayer.play() } catch { let ac = UIAlertController(title: "Playback failed", message: "There was a problem playing your whistle; please try re-recording.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) } } }
unlicense
e49dd49471f69306d8b17f2ea4cd9c35
32.186528
162
0.72662
4.079618
false
false
false
false
airbnb/lottie-ios
Sources/Private/MainThread/LayerContainers/CompLayers/ShapeCompositionLayer.swift
3
1556
// // ShapeLayerContainer.swift // lottie-swift // // Created by Brandon Withrow on 1/22/19. // import CoreGraphics import Foundation /// A CompositionLayer responsible for initializing and rendering shapes final class ShapeCompositionLayer: CompositionLayer { // MARK: Lifecycle init(shapeLayer: ShapeLayerModel) { let results = shapeLayer.items.initializeNodeTree() let renderContainer = ShapeContainerLayer() self.renderContainer = renderContainer rootNode = results.rootNode super.init(layer: shapeLayer, size: .zero) contentsLayer.addSublayer(renderContainer) for container in results.renderContainers { renderContainer.insertRenderLayer(container) } rootNode?.updateTree(0, forceUpdates: true) childKeypaths.append(contentsOf: results.childrenNodes) } override init(layer: Any) { guard let layer = layer as? ShapeCompositionLayer else { fatalError("init(layer:) wrong class.") } rootNode = nil renderContainer = nil super.init(layer: layer) } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Internal let rootNode: AnimatorNode? let renderContainer: ShapeContainerLayer? override func displayContentsWithFrame(frame: CGFloat, forceUpdates: Bool) { rootNode?.updateTree(frame, forceUpdates: forceUpdates) renderContainer?.markRenderUpdates(forFrame: frame) } override func updateRenderScale() { super.updateRenderScale() renderContainer?.renderScale = renderScale } }
apache-2.0
e75b1ab2798965dcbb093d7703ff2781
25.827586
78
0.73329
4.471264
false
false
false
false
ibari/StationToStation
StationToStation/Utils.swift
1
1064
// // Utils.swift // StationToStation // // Created by Benjamin Tsai on 6/6/15. // Copyright (c) 2015 Ian Bari. All rights reserved. // import UIKit import Foundation class Utils { let secrets: NSDictionary init() { self.secrets = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("secrets", ofType: "plist")!)! } func getSecret(property: String) -> String { return secrets[property] as! String } func secondsToMinutes(interval: Double) -> String { let minutes = floor(interval / 60.0) let seconds = round(interval - minutes * 60.0) return NSString(format: "%d:%02d", Int(minutes), Int(seconds)) as String } func foo() { var dict = [String: String]() let data = NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.allZeros, error: nil) } class var sharedInstance: Utils { struct Static { static let instance = Utils() } return Static.instance } }
gpl-2.0
5f99704e4dc82d82f7420d78d2b12136
24.333333
120
0.613722
4.360656
false
false
false
false
galv/reddift
reddift/Model/Oembed.swift
1
2406
// // Oembed.swift // reddift // // Created by sonson on 2015/04/20. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation /** Media represents the content which is embeded a link. */ public struct Oembed { /** example, "http://i.imgur.com", */ public let providerUrl:String /** example, "The Internet's visual storytelling community. Explore, share, and discuss the best visual stories the Internet has to offer.", */ public let description:String /** example, "Imgur GIF", */ public let title:String /** example, 245, */ public let thumbnailWidth:Int /** example, 333, */ public let height:Int /** example, 245, */ public let width:Int /** example, "&lt;iframe class=\"embedly-embed\" src=\"//cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fi.imgur.com%2FkhgfcrQ.mp4&amp;src_secure=1&amp;url=http%3A%2F%2Fi.imgur.com%2FkhgfcrQ.gifv&amp;image=http%3A%2F%2Fi.imgur.com%2FkhgfcrQ.gif&amp;key=2aa3c4d5f3de4f5b9120b660ad850dc9&amp;type=video%2Fmp4&amp;schema=imgur\" width=\"245\" height=\"333\" scrolling=\"no\" frameborder=\"0\" allowfullscreen&gt;&lt;/iframe&gt;", */ public let html:String /** example, "1.0", */ public let version:String /** example, "Imgur", */ public let providerName:String /** example, "http://i.imgur.com/khgfcrQ.gif", */ public let thumbnailUrl:String /** example, "video", */ public let type:String /** example, 333 */ public let thumbnailHeight:Int /** Update each property with JSON object. - parameter json: JSON object which is included "t2" JSON. */ public init (json:JSONDictionary) { self.providerUrl = json["provider_url"] as? String ?? "" self.description = json["description"] as? String ?? "" self.title = json["title"] as? String ?? "" self.thumbnailWidth = json["thumbnail_width"] as? Int ?? 0 self.height = json["height"] as? Int ?? 0 self.width = json["width"] as? Int ?? 0 self.html = json["html"] as? String ?? "" self.version = json["version"] as? String ?? "" self.providerName = json["provider_name"] as? String ?? "" self.thumbnailUrl = json["thumbnail_url"] as? String ?? "" self.type = json["type"] as? String ?? "" self.thumbnailHeight = json["thumbnail_height"] as? Int ?? 0 } }
mit
95e402153a35567a369f0a09b96cd3cb
28.329268
431
0.62604
3.302198
false
false
false
false
zhou9734/Warm
Warm/Classes/Experience/View/EFindDataView.swift
1
1197
// // EFindDataView.swift // Warm // // Created by zhoucj on 16/9/22. // Copyright © 2016年 zhoucj. All rights reserved. // import UIKit class EFindDataView: UIView { override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(){ backgroundColor = Color_GlobalBackground addSubview(imageView) addSubview(msgLbl) } private lazy var imageView: UIImageView = { let iv = UIImageView() iv.image = UIImage(named: "nocontent_133x76_") iv.frame = CGRect(x: (ScreenWidth - 133.0)/2, y: (ScreenHeight - 76.0)/2, width: 133.0, height: 76.0) return iv }() private lazy var msgLbl: UILabel = { let lbl = UILabel() lbl.text = "没有消息" lbl.textAlignment = .Center lbl.textColor = UIColor.grayColor() lbl.font = UIFont.systemFontOfSize(16) lbl.numberOfLines = 0 lbl.frame = CGRect(x: (ScreenWidth - 100.0)/2, y: (ScreenHeight - 76.0)/2 + 86, width: 100.0, height: 45.0) return lbl }() }
mit
617b252a20704e903abb66a4bcc8cfc1
26.581395
115
0.597808
3.765079
false
false
false
false
joaoSakai/torpedo-saude
GrupoFlecha/GrupoFlecha/MapViewController.swift
1
5347
// // MapViewController.swift // GrupoFlecha // // Created by Davi Rodrigues on 05/03/16. // Copyright © 2016 Davi Rodrigues. All rights reserved. // // Crédito logos da tabbar: Melissa Holterman, Oliviu Stolan, Pencil import UIKit import MapKit import CoreLocation let kSavedItemsKey = "savedItems" class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet weak var map: MKMapView! var locationManager = CLLocationManager() var zoom = false override func viewDidLoad() { super.viewDidLoad() self.map.showsUserLocation = true self.map.zoomEnabled = true locationManager.desiredAccuracy = kCLLocationAccuracyBest//kCLLocationAccuracyNearestTenMeters locationManager.delegate = self locationManager.startUpdatingLocation() locationManager.requestAlwaysAuthorization() } override func viewWillAppear(animated: Bool) { AlertSource.getData(){ () in } } override func viewWillDisappear(animated: Bool) { AlertSource.pinCoordinates.removeAll() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { } func locationManager(manager: CLLocationManager, didFinishDeferredUpdatesWithError error: NSError?) { } func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) { if(self.zoom == false) { let coor = self.map.userLocation.location?.coordinate let region = MKCoordinateRegionMakeWithDistance(coor!, 1000, 1000) self.map.setRegion(region, animated: true) self.zoom = true } self.updateAnnotations() self.insideRadius() //print(AlertSource.casosDeDengue) } func updateAnnotations() { self.map.removeAnnotations(map.annotations) self.map.removeOverlays(map.overlays) let annotation = MKCircle(centerCoordinate: map.userLocation.coordinate, radius: 300) annotation.title = "Sua localização" annotation.subtitle = "" map.addOverlay(annotation) self.addPinCoordinates() } func addPinCoordinates() { //for coord in AlertSource.pinCoordinates { /* let annotation = MKPointAnnotation() annotation.coordinate = coord annotation.title = "Caso de dengue nas proximidades" annotation.subtitle = "Localização aproximada de um caso confirmado" map.addAnnotation(annotation) let annotation = DengueOverlay(centerCoordinate: coord, radius: 100) annotation.title = "Caso de dengue nas proximidades" map.addOverlay(annotation) } */ let annotation = MKPointAnnotation() annotation.coordinate = map.userLocation.coordinate annotation.title = String(AlertSource.casosDeDengue) + " casos próximos a você" map.addAnnotation(annotation) } func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { if overlay is DengueOverlay { let circleRenderer = MKCircleRenderer(overlay: overlay) circleRenderer.lineWidth = 1 circleRenderer.strokeColor = UIColor.purpleColor() circleRenderer.fillColor = UIColor.purpleColor().colorWithAlphaComponent(0.4) return circleRenderer } if overlay is MKCircle { let circleRenderer = MKCircleRenderer(overlay: overlay) circleRenderer.lineWidth = 1.0 //Cor do circulo if(AlertSource.casosDeDengue == 0) { circleRenderer.strokeColor = UIColor.greenColor() circleRenderer.fillColor = UIColor.greenColor().colorWithAlphaComponent(0.4) } else if(AlertSource.casosDeDengue == 1) { circleRenderer.strokeColor = UIColor.yellowColor() circleRenderer.fillColor = UIColor.yellowColor().colorWithAlphaComponent(0.4) } else { circleRenderer.strokeColor = UIColor.redColor() circleRenderer.fillColor = UIColor.redColor().colorWithAlphaComponent(0.4) } return circleRenderer } return MKOverlayRenderer() } func insideRadius() { let radius: Double = 0.0029 for coord in AlertSource.pinCoordinates { let distance: Double = (map.userLocation.coordinate.latitude - coord.latitude)*(map.userLocation.coordinate.latitude - coord.latitude) + (map.userLocation.coordinate.longitude - coord.longitude)*(map.userLocation.coordinate.longitude - coord.longitude) //print(sqrt(distance)) //print(radius) if(sqrt(distance) <= radius) { AlertSource.casosDeDengue++ } } } }
gpl-2.0
125dbe89a661dba6c8928c0701304e1d
31.357576
264
0.621277
5.403846
false
false
false
false
corywilhite/SceneBuilder
SceneBuilder/LightDetailViewController.swift
1
3554
// // LightDetailViewController.swift // SceneBuilder // // Created by Cory Wilhite on 1/14/17. // Copyright © 2017 Cory Wilhite. All rights reserved. // import UIKit protocol LightDetailViewControllerDelegate: class { func didUpdate(light: Light, from detailController: LightDetailViewController) } class LightDetailViewController: UIViewController { var light: Light let api: HueAPI @IBOutlet weak var colorContainer: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var brightnessSlider: UISlider! @IBOutlet weak var onOffSwitch: UISwitch! weak var delegate: LightDetailViewControllerDelegate? init(light: Light, api: HueAPI) { self.light = light self.api = api super.init(nibName: nil, bundle: nil) _ = view } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() onOffSwitch.addTarget(self, action: #selector(onOffSwitchToggled(sender:)), for: .valueChanged) brightnessSlider.addTarget(self, action: #selector(brightnessSliderDidBeginValueChange(sender:)), for: .touchDown) brightnessSlider.addTarget(self, action: #selector(brightnessSliderValueChanged(sender:)), for: .valueChanged) brightnessSlider.addTarget(self, action: #selector(brightnessSliderDidEndValueChanged(sender:)), for: [.touchUpInside, .touchUpOutside, .touchCancel]) brightnessSlider.minimumValue = 0 brightnessSlider.maximumValue = 254 let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(dismissController)) swipeGesture.numberOfTouchesRequired = 3 swipeGesture.direction = .down view.addGestureRecognizer(swipeGesture) } override var prefersStatusBarHidden: Bool { return true } func onOffSwitchToggled(sender: UISwitch) { let animateTo: UIColor if sender.isOn { animateTo = light.currentColor } else { animateTo = .lightGray } UIView.animate(withDuration: 1) { self.colorContainer.backgroundColor = animateTo } let task = sender.isOn ? api.turnOn(light: light) : api.turnOff(light: light) task.continueOnSuccessWithTask { _ in return self.api.getState(light: self.light) }.continueOnSuccessWith { light in self.light = light self.delegate?.didUpdate(light: light, from: self) } } func brightnessSliderDidBeginValueChange(sender: UISlider) { } func brightnessSliderValueChanged(sender: UISlider) { api.changeBrightness(for: light, to: Int(sender.value)) } func brightnessSliderDidEndValueChanged(sender: UISlider) { api.getState(light: light).continueOnSuccessWith { light in self.light = light self.delegate?.didUpdate(light: light, from: self) } } func configure(light: Light) { titleLabel.text = light.name colorContainer.backgroundColor = light.state.isOn ? light.currentColor : .lightGray brightnessSlider.value = Float(light.state.brightness) onOffSwitch.onTintColor = .green onOffSwitch.isOn = light.state.isOn } func dismissController() { dismiss(animated: true, completion: nil) } }
mit
3fae4091ada15f97b75f87aba57d811d
31.3
158
0.649873
4.997187
false
false
false
false
sleifer/SKLBits
bits/UIImage-SKLBits.swift
1
2129
// // UIImage-SKLBits.swift // SKLBits // // Created by Simeon Leifer on 7/29/16. // Copyright © 2016 droolingcat.com. All rights reserved. // #if os(iOS) import UIKit public extension UIImage { public class func drawSimpleButton(_ frame: CGRect, radius: CGFloat = -1, strokeWidth: CGFloat = 1, strokeColor: UIColor? = UIColor.black, fillColor: UIColor? = nil) { let inset = strokeWidth let rectanglePath = UIBezierPath(roundedRect: CGRect(x: (frame.origin.x + inset), y: (frame.origin.y + inset), width: (frame.size.width - (inset * 2)), height: (frame.size.height - (inset * 2))), cornerRadius: radius) if let fillColor = fillColor { fillColor.setFill() rectanglePath.fill() } if let strokeColor = strokeColor { strokeColor.setStroke() rectanglePath.lineWidth = strokeWidth rectanglePath.stroke() } } public class func imageOfSimpleButton(_ frame: CGRect, radius: CGFloat = -1, strokeWidth: CGFloat = 1, strokeColor: UIColor? = UIColor.black, fillColor: UIColor? = nil) -> UIImage { var r = radius if r == -1 { r = floor(frame.height / 2.0) } let width = ((r + 2) * 2) + 1 let height = frame.height UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, 0) drawSimpleButton(CGRect(x: 0, y: 0, width: width, height: height), radius: r, strokeWidth: strokeWidth, strokeColor: strokeColor, fillColor: fillColor) let imageOfSimpleButton = UIGraphicsGetImageFromCurrentImageContext()?.resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: r+2, bottom: 0, right: r+2), resizingMode: .stretch) UIGraphicsEndImageContext() return imageOfSimpleButton! } public func tinted(_ color: UIColor) -> UIImage? { let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, self.scale) if let ctx = UIGraphicsGetCurrentContext() { self.draw(in: rect) ctx.setFillColor(color.cgColor) ctx.setBlendMode(.sourceAtop) ctx.fill(rect) } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } #endif
mit
28b2075f644f93e6393641b0797909a9
33.322581
219
0.715226
3.600677
false
false
false
false
sschiau/swift
test/Sema/call_as_function_generic.swift
2
1071
// RUN: %target-typecheck-verify-swift protocol P0 { func callAsFunction(x: Self) } struct ConcreteType { func callAsFunction<T, U>(_ x: T, _ y: U) -> (T, U) { return (x, y) } func callAsFunction<T, U>(_ fn: @escaping (T) -> U) -> (T) -> U { return fn } } let concrete = ConcreteType() _ = concrete(1, 3.0) _ = concrete(concrete, concrete.callAsFunction as ([Int], Float) -> ([Int], Float)) func generic<T, U>(_ x: T, _ y: U) { _ = concrete(x, x) _ = concrete(x, y) } struct GenericType<T : Collection> { let collection: T func callAsFunction<U>(_ x: U) -> Bool where U == T.Element, U : Equatable { return collection.contains(x) } } // Test conditional conformance. extension GenericType where T.Element : Numeric { func callAsFunction(initialValue: T.Element) -> T.Element { return collection.reduce(initialValue, +) } } let genericString = GenericType<[String]>(collection: ["Hello", "world", "!"]) _ = genericString("Hello") let genericInt = GenericType<Set<Int>>(collection: [1, 2, 3]) _ = genericInt(initialValue: 1)
apache-2.0
5832853cfeb46d302ad5ef005297ab40
23.906977
83
0.636788
3.225904
false
false
false
false
Ben21hao/edx-app-ios-new
Source/CourseDashboardViewController.swift
1
15260
// // CourseDashboardViewController.swift // edX // // Created by Ehmad Zubair Chughtai on 11/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit protocol CourseDashboardItem { var identifier: String { get } var action:(() -> Void) { get } var height: CGFloat { get } func decorateCell(cell: UITableViewCell) } struct StandardCourseDashboardItem : CourseDashboardItem { let identifier = CourseDashboardCell.identifier let height:CGFloat = 85.0 let title: String let detail: String let icon : Icon let action:(() -> Void) typealias CellType = CourseDashboardCell func decorateCell(cell: UITableViewCell) { guard let dashboardCell = cell as? CourseDashboardCell else { return } dashboardCell.useItem(self) } } struct CertificateDashboardItem: CourseDashboardItem { let identifier = CourseCertificateCell.identifier let height: CGFloat = 116.0 let certificateImage: UIImage let certificateUrl: String let action:(() -> Void) func decorateCell(cell: UITableViewCell) { guard let certificateCell = cell as? CourseCertificateCell else { return } certificateCell.useItem(self) } } public class CourseDashboardViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,UIGestureRecognizerDelegate { public typealias Environment = protocol<OEXAnalyticsProvider, OEXConfigProvider, DataManagerProvider, NetworkManagerProvider, OEXRouterProvider, OEXInterfaceProvider, OEXRouterProvider> private let spacerHeight: CGFloat = OEXStyles.dividerSize() private let environment: Environment private let courseID: String private let courseCard = CourseCardView(frame: CGRectZero) private let tableView: UITableView = UITableView() private let stackView: TZStackView = TZStackView() private let containerView: UIScrollView = UIScrollView() private let shareButton = UIButton(type: .System) private var cellItems: [CourseDashboardItem] = [] private let loadController = LoadStateViewController() private let courseStream = BackedStream<UserCourseEnrollment>() //自定义标题 private var titleL : UILabel? private lazy var progressController : ProgressController = { ProgressController(owner: self, router: self.environment.router, dataInterface: self.environment.interface) }() public init(environment: Environment, courseID: String) { self.environment = environment self.courseID = courseID super.init(nibName: nil, bundle: nil) } public required init?(coder aDecoder: NSCoder) { // required by the compiler because UIViewController implements NSCoding, // but we don't actually want to serialize these things fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = OEXStyles.sharedStyles().neutralWhite() let leftButton = UIButton.init(frame: CGRectMake(0, 0, 48, 48)) leftButton.setImage(UIImage.init(named: "backImagee"), forState: .Normal) leftButton.imageEdgeInsets = UIEdgeInsetsMake(0, -23, 0, 23) self.navigationController?.interactivePopGestureRecognizer?.enabled = true self.navigationController?.interactivePopGestureRecognizer?.delegate = self leftButton.addTarget(self, action: #selector(leftBarItemAction), forControlEvents: .TouchUpInside) let leftBarItem = UIBarButtonItem.init(customView: leftButton) self.navigationItem.leftBarButtonItem = leftBarItem self.navigationItem.rightBarButtonItem = self.progressController.navigationItem() self.view.addSubview(containerView) self.containerView.addSubview(stackView) tableView.scrollEnabled = false // Set up tableView tableView.dataSource = self tableView.delegate = self tableView.backgroundColor = UIColor.clearColor() self.view.addSubview(tableView) stackView.snp_makeConstraints { make -> Void in make.top.equalTo(containerView) make.trailing.equalTo(containerView) make.leading.equalTo(containerView) } stackView.alignment = .Fill containerView.snp_makeConstraints {make in make.edges.equalTo(view) } addShareButton(courseCard) // Register tableViewCell tableView.registerClass(CourseDashboardCell.self, forCellReuseIdentifier: CourseDashboardCell.identifier) tableView.registerClass(CourseCertificateCell.self, forCellReuseIdentifier: CourseCertificateCell.identifier) stackView.axis = .Vertical let spacer = UIView() stackView.addArrangedSubview(courseCard) stackView.addArrangedSubview(spacer) stackView.addArrangedSubview(tableView) spacer.snp_makeConstraints {make in make.height.equalTo(spacerHeight) make.width.equalTo(self.containerView) } loadController.setupInController(self, contentView: containerView) self.progressController.hideProgessView() courseStream.backWithStream(environment.dataManager.enrollmentManager.streamForCourseWithID(courseID)) courseStream.listen(self) {[weak self] in self?.resultLoaded($0) } NSNotificationCenter.defaultCenter().oex_addObserver(self, name: EnrollmentShared.successNotification) { (notification, observer, _) -> Void in if let message = notification.object as? String { observer.showOverlayMessage(message) } } } func leftBarItemAction() { self.navigationController?.popViewControllerAnimated(true) } private func resultLoaded(result : Result<UserCourseEnrollment>) { switch result { case let .Success(enrollment): self.loadedCourseWithEnrollment(enrollment) case let .Failure(error): if !courseStream.active { // enrollment list is cached locally, so if the stream is still active we may yet load the course // don't show failure until the stream is done self.loadController.state = LoadState.failed(error) } } } private func loadedCourseWithEnrollment(enrollment: UserCourseEnrollment) { //添加标题文本 self.titleL = UILabel(frame:CGRect(x:0, y:0, width:40, height:40)) self.titleL?.text = enrollment.course.name self.navigationItem.titleView = self.titleL self.titleL?.font = UIFont(name:"OpenSans",size:18.0) self.titleL?.textColor = UIColor.whiteColor() CourseCardViewModel.onDashboard(enrollment.course).apply(courseCard, networkManager: self.environment.networkManager,type:4) verifyAccessForCourse(enrollment.course) prepareTableViewData(enrollment) self.tableView.reloadData() //分享按钮 shareButton.hidden = enrollment.course.course_about == nil || !environment.config.courseSharingEnabled shareButton.oex_removeAllActions() shareButton.oex_addAction({[weak self] _ in self?.shareCourse(enrollment.course) }, forEvents: .TouchUpInside) } //share sheet private func shareCourse(course: OEXCourse) { //分享课程 if let urlString = course.course_about, url = NSURL(string: urlString) { let analytics = environment.analytics let courseID = self.courseID let controller = shareHashtaggedTextAndALink({ hashtagOrPlatform in Strings.shareACourse(platformName: hashtagOrPlatform) }, url: url, analyticsCallback: { analyticsType in analytics.trackCourseShared(courseID, url: urlString, socialTarget: analyticsType) }) self.presentViewController(controller, animated: true, completion: nil) } } private func addShareButton(courseView: CourseCardView) { if environment.config.courseSharingEnabled { shareButton.setImage(UIImage(named: "share"), forState: .Normal) shareButton.tintColor = OEXStyles.sharedStyles().neutralDark() courseView.titleAccessoryView = shareButton shareButton.snp_makeConstraints(closure: { (make) -> Void in make.height.equalTo(26) make.width.equalTo(20) }) } } private func verifyAccessForCourse(course: OEXCourse) { if let access = course.courseware_access where !access.has_access { loadController.state = LoadState.failed(OEXCoursewareAccessError(coursewareAccess: access, displayInfo: course.start_display_info), icon: Icon.UnknownError) } else { loadController.state = .Loaded } } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) environment.analytics.trackScreenWithName(OEXAnalyticsScreenCourseDashboard, courseID: courseID, value: nil) } public override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRowAtIndexPath(indexPath, animated: false) } self.navigationController?.setNavigationBarHidden(false, animated: animated) } public func prepareTableViewData(enrollment: UserCourseEnrollment) { cellItems = [] if let certificateUrl = getCertificateUrl(enrollment) { let item = CertificateDashboardItem(certificateImage: UIImage(named: "courseCertificate")!, certificateUrl: certificateUrl, action: { let url = NSURL(string: certificateUrl)! self.environment.router?.showCertificate(url, title: enrollment.course.name, fromController: self) }) cellItems.append(item) } var item = StandardCourseDashboardItem(title: Strings.courseDashboardCourseware, detail: Strings.courseDashboardCourseDetail, icon : .Courseware) {[weak self] () -> Void in self?.showCourseware() } cellItems.append(item) if shouldShowDiscussions(enrollment.course) { let courseID = self.courseID item = StandardCourseDashboardItem(title: Strings.courseDashboardDiscussion, detail: Strings.courseDashboardDiscussionDetail, icon: .Discussions) {[weak self] () -> Void in self?.showDiscussionsForCourseID(courseID) } cellItems.append(item) } item = StandardCourseDashboardItem(title: Strings.courseDashboardHandouts, detail: Strings.courseDashboardHandoutsDetail, icon: .Handouts) {[weak self] () -> Void in self?.showHandouts() } cellItems.append(item) item = StandardCourseDashboardItem(title: Strings.courseDashboardAnnouncements, detail: Strings.courseDashboardAnnouncementsDetail, icon: .Announcements) {[weak self] () -> Void in self?.showAnnouncements() } cellItems.append(item) item = StandardCourseDashboardItem(title: Strings.classTitle, detail: Strings.entetClass, icon: .Group) {[weak self] () -> Void in self?.showQRViewController() } cellItems.append(item) } private func shouldShowDiscussions(course: OEXCourse) -> Bool { let canShowDiscussions = self.environment.config.discussionsEnabled ?? false let courseHasDiscussions = course.hasDiscussionsEnabled ?? false return canShowDiscussions && courseHasDiscussions } private func getCertificateUrl(enrollment: UserCourseEnrollment) -> String? { guard environment.config.discussionsEnabled else { return nil } return enrollment.certificateUrl } // MARK: - TableView Data and Delegate public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellItems.count } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let dashboardItem = cellItems[indexPath.row] return dashboardItem.height } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let dashboardItem = cellItems[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(dashboardItem.identifier, forIndexPath: indexPath) dashboardItem.decorateCell(cell) return cell } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let dashboardItem = cellItems[indexPath.row] dashboardItem.action() } private func showCourseware() { //课件 self.environment.router?.showCoursewareForCourseWithID(courseID, fromController: self) } private func showDiscussionsForCourseID(courseID: String) { //讨论 self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil) self.environment.router?.showDiscussionTopicsFromController(self, courseID: courseID) } private func showHandouts() { //资料 self.environment.router?.showHandoutsFromController(self, courseID: courseID) } private func showAnnouncements() { //公告 self.environment.router?.showAnnouncementsForCourseWithID(courseID) } private func showQRViewController() { //班级 let vc = QRViewController(); self.navigationController?.pushViewController(vc, animated: true) } override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.tableView.snp_updateConstraints{ make in make.height.equalTo(tableView.contentSize.height) } containerView.contentSize = stackView.bounds.size } override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait } } // MARK: Testing extension CourseDashboardViewController { func t_canVisitDiscussions() -> Bool { return self.cellItems.firstIndexMatching({ (item: CourseDashboardItem) in return (item is StandardCourseDashboardItem) && (item as! StandardCourseDashboardItem).icon == .Discussions }) != nil } func t_canVisitCertificate() -> Bool { return self.cellItems.firstIndexMatching({ (item: CourseDashboardItem) in return (item is CertificateDashboardItem)}) != nil } var t_state : LoadState { return self.loadController.state } var t_loaded : Stream<()> { return self.courseStream.map {_ in () } } }
apache-2.0
7dfe2fbd09020daaa553765edda20b32
37.780612
199
0.671819
5.238456
false
false
false
false
kristopherjohnson/KJNotepad
KJNotepad/NoteUtility.swift
1
2276
// // Note+Utility.swift // KJNotepad // // Created by Kristopher Johnson on 4/24/15. // Copyright (c) 2015 Kristopher Johnson. All rights reserved. // import Foundation import CoreData // Extension methods for Note // // We keep this separate from the auto-generated code in Note.swift, so // that we can re-generate that as needed without losing this code. extension Note { class var entityName: String { return "Note" } class func entityDescriptionInManagedObjectContext(context: NSManagedObjectContext) -> NSEntityDescription { return NSEntityDescription.entityForName(entityName, inManagedObjectContext: context)! } class func insertInContext(context: NSManagedObjectContext) -> Note { let note = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: context) as! Note note.setInitialValues() return note } private func setInitialValues() { uuid = NSUUID().UUIDString createdDate = NSDate() lastEditedDate = createdDate title = "New note" text = "" } class var sortByLastEditedDateDescending: NSSortDescriptor { return NSSortDescriptor(key: "lastEditedDate", ascending: false) } var uniqueKey: String { return uuid } class var keyPropertyName: String { return "uuid" } class func findByUniqueKey(uuid: String, inContext context: NSManagedObjectContext) -> Note? { let request = fetchRequest() request.predicate = NSPredicate(format: "uuid = %@", uuid) var error: NSError? = nil if let objects = context.executeFetchRequest(request, error: &error) { if objects.count == 1 { if let object = objects[0] as? Note { return object } } else if objects.count > 1 { assert(false, "Should not find multiple instances with same key") } } else { assert(false, "Unexpected error on attempt to find object: \(error?.localizedDescription)") } return nil } class func fetchRequest() -> NSFetchRequest { return NSFetchRequest(entityName: entityName) } }
mit
d8b67eda456b12f0d3da4f387c746645
27.45
124
0.636643
5.069042
false
false
false
false
PoshDev/PoshExtensions
PoshExtensions.swift
1
16885
// PoshExtensions.swift // The MIT License (MIT) // Copyright (c) 2016 Posh Development, LLC // // 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 CoreLocation // MARK: - Hex Representation of Color - extension UIColor { convenience init(hexValue: Int){ self.init( red: CGFloat((hexValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((hexValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(hexValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } // slightly darkened colors func colorByDarkeningWithValue(value: CGFloat) -> UIColor { let numberOfComponenets = CGColorGetNumberOfComponents(self.CGColor) let isGreyscale = numberOfComponenets == 2 let oldComponents = CGColorGetComponents(self.CGColor) var newComponents: [CGFloat] = [0.0, 0.0, 0.0, 0.0] if isGreyscale { newComponents[0] = oldComponents[0] - value < 0.0 ? 0.0 : oldComponents[0] - value newComponents[1] = oldComponents[0] - value < 0.0 ? 0.0 : oldComponents[0] - value newComponents[2] = oldComponents[0] - value < 0.0 ? 0.0 : oldComponents[0] - value newComponents[3] = oldComponents[1]; } else { newComponents[0] = oldComponents[0] - value < 0.0 ? 0.0 : oldComponents[0] - value newComponents[1] = oldComponents[1] - value < 0.0 ? 0.0 : oldComponents[1] - value newComponents[2] = oldComponents[2] - value < 0.0 ? 0.0 : oldComponents[2] - value newComponents[3] = oldComponents[3] } let colorSpace = CGColorSpaceCreateDeviceRGB() let newColor = CGColorCreate(colorSpace, newComponents) return UIColor(CGColor: newColor!) } } // MARK: - Autolayout Shortcuts - extension UIView { func applyShadowWithColor(color: UIColor) { self.layer.shadowColor = color.CGColor self.layer.masksToBounds = false; self.layer.shadowOffset = CGSizeMake(1, 2); self.layer.shadowRadius = 2; self.layer.shadowOpacity = 0.25; } // CenterX and CenterY func addCenterXConstraintsToView(view: UIView) { self.addConstraint(NSLayoutConstraint(item: self, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1.0, constant: 0.0)) } func addCenterYConstraintsToView(view: UIView) { self.addConstraint(NSLayoutConstraint(item: self, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) } func addCenterXConstraintsToView(view: UIView, offset: CGFloat) { self.addConstraint(NSLayoutConstraint(item: self, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1.0, constant: -offset)) } func addCenterYConstraintsToView(view: UIView, offset: CGFloat) { self.addConstraint(NSLayoutConstraint(item: self, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1.0, constant: -offset)) } // sides func addTopConstraintToView(view: UIView) { let top = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 0.0) self.addConstraint(top) } func addBottomConstraintToView(view: UIView) { let bottom = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1.0, constant: 0.0) self.addConstraint(bottom) } func addLeftConstraintToView(view: UIView) { let left = NSLayoutConstraint(item: self, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1.0, constant: 0.0) self.addConstraint(left) } func addRightConstraintToView(view: UIView) { let right = NSLayoutConstraint(item: self, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1.0, constant: 0.0) self.addConstraint(right) } // pin to all subviews func pinSubviewToAllEdges(subview: UIView) { subview.translatesAutoresizingMaskIntoConstraints = false let left = NSLayoutConstraint(item: self, attribute: .Left, relatedBy: .Equal, toItem: subview, attribute: .Left, multiplier: 1.0, constant: 0.0) let right = NSLayoutConstraint(item: self, attribute: .Right, relatedBy: .Equal, toItem: subview, attribute: .Right, multiplier: 1.0, constant: 0.0) let top = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: subview, attribute: .Top, multiplier: 1.0, constant: 0.0) let bottom = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: subview, attribute: .Bottom, multiplier: 1.0, constant: 0.0) self.addConstraints([left, right, top, bottom]) } // Height and Width func addHeightConstraintToView(view: UIView, value: CGFloat) { self.addConstraint(NSLayoutConstraint(item: view, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: value)) } func addWidthConstraintToView(view: UIView, value: CGFloat) { self.addConstraint(NSLayoutConstraint(item: view, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: value)) } // Equal Width and Height func addEqualHeightsConstraintsToViews(views: [UIView]) { for (i, view) in views.enumerate() { if i < views.count - 1 { self.addConstraint(NSLayoutConstraint(item: view, attribute: .Height, relatedBy: .Equal, toItem: views[i + 1], attribute: .Height, multiplier: 1.0, constant: 0.0)) } } } func addEqualWidthConstraintsToViews(views: [UIView]) { for (i, view) in views.enumerate() { if i < views.count - 1 { self.addConstraint(NSLayoutConstraint(item: view, attribute: .Width, relatedBy: .Equal, toItem: views[i + 1], attribute: .Width, multiplier: 1.0, constant: 0.0)) } } } // Visual Format func addConstraintsWithFormatStrings(strings: [String], views: [String : UIView]) { for string in strings { self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(string, options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) } } } extension UIImage { // image Stetching class func stretchableImageFromImage(image: UIImage, capInsets: UIEdgeInsets) -> UIImage { return image.resizableImageWithCapInsets(capInsets, resizingMode: .Stretch) } // recoloring class func recoloredImageFromImage(image: UIImage, newColor: UIColor) -> UIImage { let imageRect = CGRect(origin: CGPointZero, size: image.size) //////// Begin //////// UIGraphicsBeginImageContextWithOptions(imageRect.size, false, image.scale) let context = UIGraphicsGetCurrentContext() CGContextScaleCTM(context, 1.0, -1.0) CGContextTranslateCTM(context, 0, -(imageRect.size.height)) CGContextClipToMask(context, imageRect, image.CGImage) CGContextSetFillColorWithColor(context, newColor.CGColor) CGContextFillRect(context, imageRect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() ///////// End ///////// return newImage } } extension NSDate { // returns date in form: Ex: Nov 27, 3:32 PM func currentTimeStampString() -> String { let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US") formatter.dateStyle = .MediumStyle formatter.timeStyle = .ShortStyle return formatter.stringFromDate(self) } // TODO: test this? // returns the time if within the last day, 'Yesterday' if made yesterday, a MM/DD/YY is before that or future func readableLocalTimestamp() -> String { let dateFormatter = NSDateFormatter() dateFormatter.timeStyle = .ShortStyle dateFormatter.dateStyle = .ShortStyle dateFormatter.doesRelativeDateFormatting = true var dateString = dateFormatter.stringFromDate(self) print(dateString) if dateString.localizedCaseInsensitiveContainsString("yesterday") { dateString = "Yesterday" } else if dateString.localizedCaseInsensitiveContainsString("today") { //dateString.removeRange(dateString.rangeOfString("Today, ")!) let newFormatter = NSDateFormatter() newFormatter.timeStyle = .ShortStyle dateString = newFormatter.stringFromDate(self) } else { // remove the time let newFormatter = NSDateFormatter() newFormatter.timeStyle = .NoStyle newFormatter.dateStyle = .ShortStyle dateString = newFormatter.stringFromDate(self) print("new dateString: \(dateString)") } return dateString } func roundedUpDay() -> NSDate { let calendar = NSCalendar.currentCalendar() let units: NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day] let components = calendar.components(units, fromDate: self) components.day += 1 return calendar.dateFromComponents(components)! } func roundedDownDay() -> NSDate { let calendar = NSCalendar.currentCalendar() let units: NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day] let components = calendar.components(units, fromDate: self) return calendar.dateFromComponents(components)! } } extension String { var nullIfEmpty: String? { let trimmed = self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) return trimmed.characters.count == 0 ? nil : trimmed } static func commaSeparatedList(list: [String], conjunction: String = "and", oxfordComma: Bool = true) -> String { print(list.count) return list.enumerate().reduce("", combine: { (lhs: String, rhs: (Int, String)) -> String in let (rhsIndex, rhsString) = rhs if lhs.characters.count == 0 { return rhsString } if rhsString.characters.count == 0 { return lhs } if rhsIndex == list.count - 1 { if !oxfordComma || list.count == 2 { return lhs + " \(conjunction) " + rhsString } else { return lhs + ", \(conjunction) " + rhsString } } else { return lhs + ", " + rhsString } }) } // Extracts the first capture group from the string so long as the entire string matches the regex // i.e. NSRegularExpression(pattern: "^(\\d*\\.?\\d*)%?$", options: [.CaseInsensitive]) // would extract "5.43" from "$5.43" func extractMatch(regex: NSRegularExpression) -> String? { let result = regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: self.characters.count)) let capturedRange = result!.rangeAtIndex(1) if !NSEqualRanges(capturedRange, NSMakeRange(NSNotFound, 0)) { let theResult = (self as NSString).substringWithRange(result!.rangeAtIndex(1)) return theResult } else { return nil } } } extension Array { mutating func appendAsQueueWithLength(newElement: Element, length: Int) { if self.count < length { self.append(newElement) } else { self.removeFirst() self.append(newElement) } assert(self.count <= length) } } // Calculates the average value of all elements in array extension _ArrayType where Generator.Element == Double { func getAverage() -> Double { var average: Double = 0.0 self.forEach({average += $0}) return average / Double(self.count) } } extension _ArrayType where Generator.Element == Int { func getAverage() -> Int { var average: Double = 0.0 self.forEach({average += Double($0)}) return Int(round(average / Double(self.count))) } } extension CLLocationManager { func enableBackgroundLocation() { if #available(iOS 9.0, *) { self.allowsBackgroundLocationUpdates = true } else { // background location enabled by default } } } extension UITextField { func applyAttributedPlaceHolderForTextField() { let attributedPlaceholder = NSMutableAttributedString() let attributedText = NSMutableAttributedString(string: self.placeholder ?? "", attributes: [NSForegroundColorAttributeName : UIColor.lightGrayColor(), NSFontAttributeName : self.font ?? UIFont.systemFontOfSize(17.0)]) attributedPlaceholder.appendAttributedString(attributedText) self.attributedPlaceholder = attributedPlaceholder } } // Extension to get last n elements of array extension CollectionType { func last(count:Int) -> [Self.Generator.Element] { let selfCount = self.count as! Int if selfCount == 0 { return [] } if count == 0 { return [] } if selfCount <= count - 1 { return Array(self) } else { if count == 1 { Array(self).last } return Array(self.reverse()[0...count - 1].reverse()) } } } extension UInt { // http://stackoverflow.com/questions/3312935/nsnumberformatter-and-th-st-nd-rd-ordinal-number-endings var shortOrdinal: String { let ones = self % 10; let tens = (self / 10) % 10; let suffix: String if tens == 1 { suffix = "th"; } else if ones == 1 { suffix = "st"; } else if ones == 2 { suffix = "nd"; } else if ones == 3 { suffix = "rd"; } else { suffix = "th"; } return String(format: "%d%@", self, suffix) } } extension UITableViewCell { // regulatory static var nib: UINib { let className = self.className return UINib(nibName: className, bundle: NSBundle.mainBundle()) } static var cellReuseIdentifier: String { return self.className } static var className: String { return self.classForCoder().description().componentsSeparatedByString(".")[1] } } extension UICollectionViewCell { // regulatory static var nib: UINib { let className = self.className return UINib(nibName: className, bundle: NSBundle.mainBundle()) } static var cellReuseIdentifier: String { return self.className } static var className: String { return self.classForCoder().description().componentsSeparatedByString(".")[1] } } extension UITableViewHeaderFooterView { // regulatory static var nib: UINib { let className = self.className return UINib(nibName: className, bundle: NSBundle.mainBundle()) } static var cellReuseIdentifier: String { return self.className } static var className: String { return self.classForCoder().description().componentsSeparatedByString(".")[1] } } extension UIViewController { func replaceRootViewController(withViewController viewController: UIViewController) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.window?.rootViewController = viewController appDelegate.window?.makeKeyAndVisible() } }
mit
021f5133b87e2a36a68dfd605189cac8
35.002132
225
0.64584
4.612128
false
false
false
false
Hypercoin/Hypercoin-mac
Hypercoin/Models/MarketCap.swift
1
1916
// // MarketCapService.swift // Hypercoin // // Created by Axel Etcheverry on 18/10/2017. // Copyright © 2017 Hypercoin. All rights reserved. // import Foundation import Marshal struct MarketCap: Unmarshaling { public var id: String public var name: String public var symbol: String public var rank: Int public var price: [CurrencyType: Double] public var volume24h: [CurrencyType: Double] public var marketCap: [CurrencyType: Double] public var availableSupply: Double public var totalSupply: Double public var percentChange: [ChangePeriodType: Double] public var lastUpdated: Int64 init(object: MarshaledObject) throws { self.price = [:] self.percentChange = [:] self.volume24h = [:] self.marketCap = [:] self.id = try object.value(for: "id") self.name = try object.value(for: "name") self.symbol = try object.value(for: "symbol") self.rank = try object.value(for: "rank", defaultValue: 0) self.availableSupply = try object.double(for: "available_supply", defaultValue: 0) self.totalSupply = try object.double(for: "total_supply", defaultValue: 0) self.lastUpdated = try object.value(for: "last_updated", defaultValue: 0) for currency in CurrencyType.allValues { if let price = try? object.double(for: "price_\(currency)", defaultValue: 0), price > 0 { self.price[currency] = price } if let price = try? object.double(for: "24h_volume_\(currency)", defaultValue: 0), price > 0 { self.volume24h[currency] = price } if let price = try? object.double(for: "market_cap_\(currency)", defaultValue: 0), price > 0 { self.marketCap[currency] = price } } self.percentChange[.hourly] = try object.double(for: "percent_change_1h", defaultValue: 0) self.percentChange[.daily] = try object.double(for: "percent_change_24h", defaultValue: 0) self.percentChange[.weekly] = try object.double(for: "percent_change_7d", defaultValue: 0) } }
mit
66bf0175916f444321f85eddbd27a210
30.916667
97
0.706527
3.307427
false
false
false
false
frootloops/swift
test/SILGen/opaque_values_silgen.swift
1
75115
// RUN: %target-swift-frontend -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime // UNSUPPORTED: resilient_stdlib struct TrivialStruct { var x: Int } protocol Foo { func foo() } protocol P { var x : Int { get } } protocol P2 : P {} extension TrivialStruct : P2 {} struct Box<T> { let t: T } protocol EmptyP {} struct AddressOnlyStruct : EmptyP {} struct AnyStruct { let a: Any } protocol Clonable { func maybeClone() -> Self? } indirect enum IndirectEnum<T> { case Nil case Node(T) } protocol SubscriptableGet { subscript(a : Int) -> Int { get } } protocol SubscriptableGetSet { subscript(a : Int) -> Int { get set } } var subscriptableGet : SubscriptableGet var subscriptableGetSet : SubscriptableGetSet class OpaqueClass<T> { typealias ObnoxiousTuple = (T, (T.Type, (T) -> T)) func inAndOut(x: T) -> T { return x } func variantOptionalityTuples(x: ObnoxiousTuple) -> ObnoxiousTuple? { return x } } class StillOpaqueClass<T>: OpaqueClass<T> { override func variantOptionalityTuples(x: ObnoxiousTuple?) -> ObnoxiousTuple { return x! } } class OpaqueTupleClass<U>: OpaqueClass<(U, U)> { override func inAndOut(x: (U, U)) -> (U, U) { return x } } func unreachableF<T>() -> (Int, T)? { } func s010_hasVarArg(_ args: Any...) {} // Tests Address only enums's construction // CHECK-LABEL: sil shared [transparent] @_T020opaque_values_silgen15AddressOnlyEnumO4mereAcA6EmptyP_pcACmF : $@convention(method) (@in EmptyP, @thin AddressOnlyEnum.Type) -> @out AddressOnlyEnum { // CHECK: bb0([[ARG0:%.*]] : $EmptyP, [[ARG1:%.*]] : $@thin AddressOnlyEnum.Type): // CHECK: [[RETVAL:%.*]] = enum $AddressOnlyEnum, #AddressOnlyEnum.mere!enumelt.1, [[ARG0]] : $EmptyP // CHECK: return [[RETVAL]] : $AddressOnlyEnum // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen15AddressOnlyEnumO4mereAcA6EmptyP_pcACmF' // CHECK-LABEL: sil shared [transparent] [thunk] @_T020opaque_values_silgen15AddressOnlyEnumO4mereAcA6EmptyP_pcACmFTc : $@convention(thin) (@thin AddressOnlyEnum.Type) -> @owned @callee_guaranteed (@in EmptyP) -> @out AddressOnlyEnum { // CHECK: bb0([[ARG:%.*]] : $@thin AddressOnlyEnum.Type): // CHECK: [[RETVAL:%.*]] = partial_apply {{.*}}([[ARG]]) : $@convention(method) (@in EmptyP, @thin AddressOnlyEnum.Type) -> @out AddressOnlyEnum // CHECK: return [[RETVAL]] : $@callee_guaranteed (@in EmptyP) -> @out AddressOnlyEnum // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen15AddressOnlyEnumO4mereAcA6EmptyP_pcACmFTc' enum AddressOnlyEnum { case nought case mere(EmptyP) case phantom(AddressOnlyStruct) } // Test vtables - OpaqueTupleClass // --- // CHECK-LABEL: sil private @_T020opaque_values_silgen16OpaqueTupleClassC8inAndOutx_xtx_xt1x_tFAA0dF0CADxxAE_tFTV : $@convention(method) <U> (@in (U, U), @guaranteed OpaqueTupleClass<U>) -> @out (U, U) { // CHECK: bb0([[ARG0:%.*]] : $(U, U), [[ARG1:%.*]] : $OpaqueTupleClass<U>): // CHECK: ([[TELEM0:%.*]], [[TELEM1:%.*]]) = destructure_tuple [[ARG0]] : $(U, U) // CHECK: [[APPLY:%.*]] = apply {{.*}}<U>([[TELEM0]], [[TELEM1]], [[ARG1]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @in τ_0_0, @guaranteed OpaqueTupleClass<τ_0_0>) -> (@out τ_0_0, @out τ_0_0) // CHECK: [[BORROWED_CALL:%.*]] = begin_borrow [[APPLY]] // CHECK: [[BORROWED_CALL_EXT0:%.*]] = tuple_extract [[BORROWED_CALL]] : $(U, U), 0 // CHECK: [[RETVAL0:%.*]] = copy_value [[BORROWED_CALL_EXT0]] : $U // CHECK: [[BORROWED_CALL_EXT1:%.*]] = tuple_extract [[BORROWED_CALL]] : $(U, U), 1 // CHECK: [[RETVAL1:%.*]] = copy_value [[BORROWED_CALL_EXT1]] : $U // CHECK: end_borrow [[BORROWED_CALL]] // CHECK: [[RETVAL:%.*]] = tuple ([[RETVAL0]] : $U, [[RETVAL1]] : $U) // CHECK: return [[RETVAL]] // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen16OpaqueTupleClassC8inAndOutx_xtx_xt1x_tFAA0dF0CADxxAE_tFTV' // Test vtables - StillOpaqueClass // --- // CHECK-LABEL: sil private @_T020opaque_values_silgen16StillOpaqueClassC24variantOptionalityTuplesx_xm_xxcttx_xm_xxcttSg1x_tFAA0eF0CAdEx_xm_xxcttAF_tFTV : $@convention(method) <T> (@in T, @thick T.Type, @owned @callee_guaranteed (@in T) -> @out T, @guaranteed StillOpaqueClass<T>) -> @out Optional<(T, (@thick T.Type, @callee_guaranteed (@in T) -> @out T))> { // CHECK: bb0([[ARG0:%.*]] : $T, [[ARG1:%.*]] : $@thick T.Type, [[ARG2:%.*]] : $@callee_guaranteed (@in T) -> @out T, [[ARG3:%.*]] : $StillOpaqueClass<T>): // CHECK: [[TELEM0:%.*]] = tuple ([[ARG1]] : $@thick T.Type, [[ARG2]] : $@callee_guaranteed (@in T) -> @out T) // CHECK: [[TELEM1:%.*]] = tuple ([[ARG0]] : $T, [[TELEM0]] : $(@thick T.Type, @callee_guaranteed (@in T) -> @out T)) // CHECK: [[ENUMOPT0:%.*]] = enum $Optional<(T, (@thick T.Type, @callee_guaranteed (@in T) -> @out T))>, #Optional.some!enumelt.1, [[TELEM1]] : $(T, (@thick T.Type, @callee_guaranteed (@in T) -> @out T)) // CHECK: [[APPLY:%.*]] = apply {{.*}}<T>([[ENUMOPT0]], [[ARG3]]) : $@convention(method) <τ_0_0> (@in Optional<(τ_0_0, (@thick τ_0_0.Type, @callee_guaranteed (@in τ_0_0) -> @out τ_0_0))>, @guaranteed StillOpaqueClass<τ_0_0>) -> (@out τ_0_0, @thick τ_0_0.Type, @owned @callee_guaranteed (@in τ_0_0) -> @out τ_0_0) // CHECK: [[BORROWED_T:%.*]] = begin_borrow [[APPLY]] // CHECK: [[BORROWED_T_EXT0:%.*]] = tuple_extract [[BORROWED_T]] : $(T, @thick T.Type, @callee_guaranteed (@in T) -> @out T), 0 // CHECK: [[RETVAL0:%.*]] = copy_value [[BORROWED_T_EXT0]] // CHECK: [[BORROWED_T_EXT1:%.*]] = tuple_extract [[BORROWED_T]] : $(T, @thick T.Type, @callee_guaranteed (@in T) -> @out T), 1 // CHECK: [[BORROWED_T_EXT2:%.*]] = tuple_extract [[BORROWED_T]] : $(T, @thick T.Type, @callee_guaranteed (@in T) -> @out T), 2 // CHECK: [[RETVAL1:%.*]] = copy_value [[BORROWED_T_EXT2]] // CHECK: end_borrow [[BORROWED_T]] // CHECK: [[RETTUPLE0:%.*]] = tuple ([[BORROWED_T_EXT1]] : $@thick T.Type, [[RETVAL1]] : $@callee_guaranteed (@in T) -> @out T) // CHECK: [[RETTUPLE1:%.*]] = tuple ([[RETVAL0]] : $T, [[RETTUPLE0]] : $(@thick T.Type, @callee_guaranteed (@in T) -> @out T)) // CHECK: [[RETVAL:%.*]] = enum $Optional<(T, (@thick T.Type, @callee_guaranteed (@in T) -> @out T))>, #Optional.some!enumelt.1, [[RETTUPLE1]] : $(T, (@thick T.Type, @callee_guaranteed (@in T) -> @out T)) // CHECK: return [[RETVAL]] // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen16StillOpaqueClassC24variantOptionalityTuplesx_xm_xxcttx_xm_xxcttSg1x_tFAA0eF0CAdEx_xm_xxcttAF_tFTV' // part of s280_convExistTrivial: conversion between existential types - reabstraction thunk // --- // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T020opaque_values_silgen1P_pAA13TrivialStructVIegid_AA2P2_pAaE_pIegir_TR : $@convention(thin) (@in P2, @guaranteed @callee_guaranteed (@in P) -> TrivialStruct) -> @out P2 { // CHECK: bb0([[ARG0:%.*]] : $P2, [[ARG1:%.*]] : $@callee_guaranteed (@in P) -> TrivialStruct): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG0]] : $P2 // CHECK: [[OPENED_ARG:%.*]] = open_existential_value [[BORROWED_ARG]] : $P2 to $@opened({{.*}}) P2 // CHECK: [[COPIED_VAL:%.*]] = copy_value [[OPENED_ARG]] // CHECK: [[INIT_P:%.*]] = init_existential_value [[COPIED_VAL]] : $@opened({{.*}}) P2, $@opened({{.*}}) P2, $P // CHECK: [[APPLY_P:%.*]] = apply [[ARG1]]([[INIT_P]]) : $@callee_guaranteed (@in P) -> TrivialStruct // CHECK: [[RETVAL:%.*]] = init_existential_value [[APPLY_P]] : $TrivialStruct, $TrivialStruct, $P2 // CHECK: destroy_value [[ARG0]] // CHECK: return [[RETVAL]] : $P2 // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen1P_pAA13TrivialStructVIegid_AA2P2_pAaE_pIegir_TR' // part of s290_convOptExistTriv: conversion between existential types - reabstraction thunk - optionals case // --- // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T020opaque_values_silgen1P_pSgAA13TrivialStructVIegid_AESgAA2P2_pIegyr_TR : $@convention(thin) (Optional<TrivialStruct>, @guaranteed @callee_guaranteed (@in Optional<P>) -> TrivialStruct) -> @out P2 { // CHECK: bb0([[ARG0:%.*]] : $Optional<TrivialStruct>, [[ARG1:%.*]] : $@callee_guaranteed (@in Optional<P>) -> TrivialStruct): // CHECK: switch_enum [[ARG0]] : $Optional<TrivialStruct>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1 // CHECK: bb1: // CHECK: [[ONONE:%.*]] = enum $Optional<P>, #Optional.none!enumelt // CHECK: br bb3([[ONONE]] : $Optional<P>) // CHECK: bb2([[OSOME:%.*]] : $TrivialStruct): // CHECK: [[INIT_S:%.*]] = init_existential_value [[OSOME]] : $TrivialStruct, $TrivialStruct, $P // CHECK: [[ENUM_S:%.*]] = enum $Optional<P>, #Optional.some!enumelt.1, [[INIT_S]] : $P // CHECK: br bb3([[ENUM_S]] : $Optional<P>) // CHECK: bb3([[OPT_S:%.*]] : $Optional<P>): // CHECK: [[APPLY_P:%.*]] = apply [[ARG1]]([[OPT_S]]) : $@callee_guaranteed (@in Optional<P>) -> TrivialStruct // CHECK: [[RETVAL:%.*]] = init_existential_value [[APPLY_P]] : $TrivialStruct, $TrivialStruct, $P2 // CHECK: return [[RETVAL]] : $P2 // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen1P_pSgAA13TrivialStructVIegid_AESgAA2P2_pIegyr_TR' // Test array initialization - we are still (somewhat) using addresses // --- // CHECK-LABEL: sil @_T020opaque_values_silgen21s020_______callVarArgyyF : $@convention(thin) () -> () { // CHECK: %[[APY:.*]] = apply %{{.*}}<Any>(%{{.*}}) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: %[[BRW:.*]] = begin_borrow %[[APY]] // CHECK: %[[TPL:.*]] = tuple_extract %[[BRW]] : $(Array<Any>, Builtin.RawPointer), 1 // CHECK: end_borrow %[[BRW]] from %[[APY]] : $(Array<Any>, Builtin.RawPointer), $(Array<Any>, Builtin.RawPointer) // CHECK: destroy_value %[[APY]] // CHECK: %[[PTR:.*]] = pointer_to_address %[[TPL]] : $Builtin.RawPointer to [strict] $*Any // CHECK: [[IOPAQUE:%.*]] = init_existential_value %{{.*}} : $Int, $Int, $Any // CHECK: store [[IOPAQUE]] to [init] %[[PTR]] : $*Any // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s020_______callVarArgyyF' public func s020_______callVarArg() { s010_hasVarArg(3) } // Test emitSemanticStore. // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s030______assigninoutyxz_xtlF : $@convention(thin) <T> (@inout T, @in T) -> () { // CHECK: bb0([[ARG0:%.*]] : $*T, [[ARG1:%.*]] : $T): // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[CPY:%.*]] = copy_value [[BORROWED_ARG1]] : $T // CHECK: [[READ:%.*]] = begin_access [modify] [unknown] [[ARG0]] : $*T // CHECK: assign [[CPY]] to [[READ]] : $*T // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]] // CHECK: destroy_value [[ARG1]] : $T // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s030______assigninoutyxz_xtlF' func s030______assigninout<T>(_ a: inout T, _ b: T) { a = b } // Test that we no longer use copy_addr or tuple_element_addr when copy by value is possible // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s040___tupleReturnIntS2i_xt_tlF : $@convention(thin) <T> (Int, @in T) -> Int { // CHECK: bb0([[ARG0:%.*]] : $Int, [[ARG1:%.*]] : $T): // CHECK: [[TPL:%.*]] = tuple ([[ARG0]] : $Int, [[ARG1]] : $T) // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[TPL]] : $(Int, T) // CHECK: [[CPY:%.*]] = copy_value [[BORROWED_ARG1]] : $(Int, T) // CHECK: [[BORROWED_CPY:%.*]] = begin_borrow [[CPY]] // CHECK: [[INT:%.*]] = tuple_extract [[BORROWED_CPY]] : $(Int, T), 0 // CHECK: [[GEN:%.*]] = tuple_extract [[BORROWED_CPY]] : $(Int, T), 1 // CHECK: [[COPY_GEN:%.*]] = copy_value [[GEN]] // CHECK: destroy_value [[COPY_GEN]] // CHECK: end_borrow [[BORROWED_CPY]] from [[CPY]] // CHECK: destroy_value [[CPY]] // CHECK: end_borrow [[BORROWED_ARG1]] from [[TPL]] : $(Int, T), $(Int, T) // CHECK: destroy_value [[TPL]] : $(Int, T) // CHECK: return [[INT]] // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s040___tupleReturnIntS2i_xt_tlF' func s040___tupleReturnInt<T>(_ x: (Int, T)) -> Int { let y = x.0 return y } // Test returning an opaque tuple of tuples. // --- // CHECK-LABEL: sil hidden [noinline] @_T020opaque_values_silgen21s050______multiResultx_x_xttxlF : $@convention(thin) <T> (@in T) -> (@out T, @out T, @out T) { // CHECK: bb0(%0 : $T): // CHECK: %[[CP1:.*]] = copy_value %{{.*}} : $T // CHECK: %[[CP2:.*]] = copy_value %{{.*}} : $T // CHECK: %[[CP3:.*]] = copy_value %{{.*}} : $T // CHECK: destroy_value %0 : $T // CHECK: %[[TPL:.*]] = tuple (%[[CP1]] : $T, %[[CP2]] : $T, %[[CP3]] : $T) // CHECK: return %[[TPL]] : $(T, T, T) // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s050______multiResultx_x_xttxlF' @inline(never) func s050______multiResult<T>(_ t: T) -> (T, (T, T)) { return (t, (t, t)) } // Test returning an opaque tuple of tuples as a concrete tuple. // --- // CHECK-LABEL: sil @_T020opaque_values_silgen21s060__callMultiResultSi_Si_SittSi1i_tF : $@convention(thin) (Int) -> (Int, Int, Int) { // CHECK: bb0(%0 : $Int): // CHECK: %[[FN:.*]] = function_ref @_T020opaque_values_silgen21s050______multiResultx_x_xttxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @out τ_0_0, @out τ_0_0) // CHECK: %[[TPL:.*]] = apply %[[FN]]<Int>(%0) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @out τ_0_0, @out τ_0_0) // CHECK: %[[I1:.*]] = tuple_extract %[[TPL]] : $(Int, Int, Int), 0 // CHECK: %[[I2:.*]] = tuple_extract %[[TPL]] : $(Int, Int, Int), 1 // CHECK: %[[I3:.*]] = tuple_extract %[[TPL]] : $(Int, Int, Int), 2 // CHECK: %[[R:.*]] = tuple (%[[I1]] : $Int, %[[I2]] : $Int, %[[I3]] : $Int) // CHECK: return %[[R]] : $(Int, Int, Int) // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s060__callMultiResultSi_Si_SittSi1i_tF' public func s060__callMultiResult(i: Int) -> (Int, (Int, Int)) { return s050______multiResult(i) } // SILGen, prepareArchetypeCallee. Materialize a // non-class-constrainted self from a class-constrained archetype. // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s070__materializeSelfyx1t_tRlzCAA3FooRzlF : $@convention(thin) <T where T : AnyObject, T : Foo> (@owned T) -> () { // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[WITNESS_METHOD:%.*]] = witness_method $T, #Foo.foo!1 : <Self where Self : Foo> (Self) -> () -> () : $@convention(witness_method: Foo) <τ_0_0 where τ_0_0 : Foo> (@in_guaranteed τ_0_0) -> () // CHECK: apply [[WITNESS_METHOD]]<T>([[BORROWED_ARG]]) : $@convention(witness_method: Foo) <τ_0_0 where τ_0_0 : Foo> (@in_guaranteed τ_0_0) -> () // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] : $T // CHECK: return %{{[0-9]+}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s070__materializeSelfyx1t_tRlzCAA3FooRzlF' func s070__materializeSelf<T: Foo>(t: T) where T: AnyObject { t.foo() } // Test open existential with opaque values // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s080______________barSiAA1P_p1p_tF : $@convention(thin) (@in P) -> Int { // CHECK: bb0([[ARG:%.*]] : $P): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[OPENED_ARG:%.*]] = open_existential_value [[BORROWED_ARG]] : $P to $@opened // CHECK: [[WITNESS_FUNC:%.*]] = witness_method $@opened // CHECK: [[RESULT:%.*]] = apply [[WITNESS_FUNC]]<{{.*}}>([[OPENED_ARG]]) : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> Int // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] : $P // CHECK: return [[RESULT]] : $Int func s080______________bar(p: P) -> Int { return p.x } // Test OpaqueTypeLowering copyValue and destroyValue. // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s090___________callerxxlF : $@convention(thin) <T> (@in T) -> @out T { // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY:%.*]] = copy_value [[BORROWED_ARG]] : $T // CHECK: [[RESULT:%.*]] = apply {{%.*}}<T>([[COPY]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out τ_0_0 // CHECK: end_borrow [[BORROWED_ARG:%.*]] from [[ARG]] // CHECK: destroy_value [[ARG]] : $T // CHECK: return %{{.*}} : $T // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s090___________callerxxlF' func s090___________caller<T>(_ t: T) -> T { return s090___________caller(t) } // Test a simple opaque parameter and return value. // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s100_________identityxxlF : $@convention(thin) <T> (@in T) -> @out T { // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] : $T // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] : $T // CHECK: return [[COPY_ARG]] : $T // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s100_________identityxxlF' func s100_________identity<T>(_ t: T) -> T { return t } // Test a guaranteed opaque parameter. // --- // CHECK-LABEL: sil private [transparent] [thunk] @_T020opaque_values_silgen21s110___GuaranteedSelfVAA3FooA2aDP3fooyyFTW : $@convention(witness_method: Foo) (@in_guaranteed s110___GuaranteedSelf) -> () { // CHECK: bb0(%0 : $s110___GuaranteedSelf): // CHECK: %[[F:.*]] = function_ref @_T020opaque_values_silgen21s110___GuaranteedSelfV3fooyyF : $@convention(method) (s110___GuaranteedSelf) -> () // CHECK: apply %[[F]](%0) : $@convention(method) (s110___GuaranteedSelf) -> () // CHECK: return // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s110___GuaranteedSelfVAA3FooA2aDP3fooyyFTW' struct s110___GuaranteedSelf : Foo { func foo() {} } // Tests a corner case wherein we used to do a temporary and return a pointer to T instead of T // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s120______returnValuexxlF : $@convention(thin) <T> (@in T) -> @out T { // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY_ARG1:%.*]] = copy_value [[BORROWED_ARG1]] : $T // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG]] // CHECK: [[BORROWED_ARG2:%.*]] = begin_borrow [[COPY_ARG1]] // CHECK: [[COPY_ARG2:%.*]] = copy_value [[BORROWED_ARG2]] : $T // CHECK: end_borrow [[BORROWED_ARG2]] from [[COPY_ARG1]] // CHECK: return [[COPY_ARG2]] : $T // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s120______returnValuexxlF' func s120______returnValue<T>(_ x: T) -> T { let y = x return y } // Tests Optional initialization by value // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s130_____________wrapxSgxlF : $@convention(thin) <T> (@in T) -> @out Optional<T> { // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] : $T // CHECK: [[OPTIONAL_ARG:%.*]] = enum $Optional<T>, #Optional.some!enumelt.1, [[COPY_ARG]] : $T // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] : $T // CHECK: return [[OPTIONAL_ARG]] : $Optional<T> // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s130_____________wrapxSgxlF' func s130_____________wrap<T>(_ x: T) -> T? { return x } // Tests For-each statements // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s140______forEachStmtyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[PROJ_BOX_ARG:%.*]] = project_box %{{.*}} : ${ var IndexingIterator<CountableRange<Int>> } // CHECK: [[APPLY_ARG1:%.*]] = apply // CHECK-NOT: alloc_stack $Int // CHECK-NOT: store [[APPLY_ARG1]] to [trivial] // CHECK-NOT: alloc_stack $CountableRange<Int> // CHECK-NOT: dealloc_stack // CHECK: [[APPLY_ARG2:%.*]] = apply %{{.*}}<CountableRange<Int>> // CHECK: store [[APPLY_ARG2]] to [trivial] [[PROJ_BOX_ARG]] // CHECK: br bb1 // CHECK: bb1: // CHECK-NOT: alloc_stack $Optional<Int> // CHECK: [[APPLY_ARG3:%.*]] = apply %{{.*}}<CountableRange<Int>> // CHECK-NOT: dealloc_stack // CHECK: switch_enum [[APPLY_ARG3]] // CHECK: bb2: // CHECK: br bb3 // CHECK: bb3: // CHECK: return %{{.*}} : $() // CHECK: bb4([[ENUM_ARG:%.*]] : $Int): // CHECK-NOT: unchecked_enum_data // CHECK: br bb1 // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s140______forEachStmtyyF' func s140______forEachStmt() { for _ in 1..<42 { } } func s150___________anyArg(_: Any) {} // Tests init of opaque existentials // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s160_______callAnyArgyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[INT_TYPE:%.*]] = metatype $@thin Int.Type // CHECK: [[INT_LIT:%.*]] = integer_literal $Builtin.Int2048, 42 // CHECK: [[INT_ARG:%.*]] = apply %{{.*}}([[INT_LIT]], [[INT_TYPE]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int // CHECK: [[INIT_OPAQUE:%.*]] = init_existential_value [[INT_ARG]] : $Int, $Int, $Any // CHECK: apply %{{.*}}([[INIT_OPAQUE]]) : $@convention(thin) (@in Any) -> () // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s160_______callAnyArgyyF' func s160_______callAnyArg() { s150___________anyArg(42) } // Tests unconditional_checked_cast for opaque values // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s170____force_convertxylF : $@convention(thin) <T> () -> @out T { // CHECK: bb0: // CHECK-NOT: alloc_stack // CHECK: [[INT_TYPE:%.*]] = metatype $@thin Int.Type // CHECK: [[INT_LIT:%.*]] = integer_literal $Builtin.Int2048, 42 // CHECK: [[INT_ARG:%.*]] = apply %{{.*}}([[INT_LIT]], [[INT_TYPE]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int // CHECK: [[INT_CAST:%.*]] = unconditional_checked_cast_value [[INT_ARG]] : $Int to $T // CHECK: [[CAST_BORROW:%.*]] = begin_borrow [[INT_CAST]] : $T // CHECK: [[RETURN_VAL:%.*]] = copy_value [[CAST_BORROW]] : $T // CHECK: end_borrow [[CAST_BORROW]] from [[INT_CAST]] : $T, $T // CHECK: destroy_value [[INT_CAST]] : $T // CHECK: return [[RETURN_VAL]] : $T // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s170____force_convertxylF' func s170____force_convert<T>() -> T { let x : T = 42 as! T return x } // Tests supporting function for s190___return_foo_var - cast and return of protocol // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s180_______return_fooAA3Foo_pyF : $@convention(thin) () -> @out Foo { // CHECK: bb0: // CHECK: [[INT_LIT:%.*]] = integer_literal $Builtin.Int2048, 42 // CHECK: [[INT_ARG:%.*]] = apply %{{.*}}([[INT_LIT]], [[INT_TYPE]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int // CHECK: [[INT_CAST:%.*]] = unconditional_checked_cast_value [[INT_ARG]] : $Int to $Foo // CHECK: return [[INT_CAST]] : $Foo // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s180_______return_fooAA3Foo_pyF' func s180_______return_foo() -> Foo { return 42 as! Foo } var foo_var : Foo = s180_______return_foo() // Tests return of global variables by doing a load of copy // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s190___return_foo_varAA3Foo_pyF : $@convention(thin) () -> @out Foo { // CHECK: bb0: // CHECK: [[GLOBAL:%.*]] = global_addr {{.*}} : $*Foo // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBAL]] : $*Foo // CHECK: [[LOAD_GLOBAL:%.*]] = load [copy] [[READ]] : $*Foo // CHECK: return [[LOAD_GLOBAL]] : $Foo // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s190___return_foo_varAA3Foo_pyF' func s190___return_foo_var() -> Foo { return foo_var } // Tests deinit of opaque existentials // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s200______use_foo_varyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[GLOBAL:%.*]] = global_addr {{.*}} : $*Foo // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBAL]] : $*Foo // CHECK: [[LOAD_GLOBAL:%.*]] = load [copy] [[READ]] : $*Foo // CHECK: [[BORROW:%.*]] = begin_borrow [[LOAD_GLOBAL]] : $Foo // CHECK: [[OPEN_VAR:%.*]] = open_existential_value [[BORROW]] : $Foo // CHECK: [[WITNESS:%.*]] = witness_method $@opened // CHECK: apply [[WITNESS]] // CHECK: end_borrow [[BORROW]] // CHECK: destroy_value [[LOAD_GLOBAL]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s200______use_foo_varyyF' func s200______use_foo_var() { foo_var.foo() } // Tests composition erasure of opaque existentials + copy into of opaques // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s210______compErasures5Error_psAC_AA3FoopF : $@convention(thin) (@in Error & Foo) -> @owned Error { // CHECK: bb0([[ARG:%.*]] : $Error & Foo): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[OPAQUE_ARG:%.*]] = open_existential_value [[BORROWED_ARG]] : $Error & Foo to $@opened({{.*}}) Error & Foo // CHECK: [[EXIST_BOX:%.*]] = alloc_existential_box $Error, $@opened({{.*}}) Error & Foo // CHECK: [[PROJ_BOX:%.*]] = project_existential_box $@opened({{.*}}) Error & Foo in [[EXIST_BOX]] // CHECK: [[COPY_OPAQUE:%.*]] = copy_value [[OPAQUE_ARG]] : $@opened({{.*}}) Error & Foo // CHECK: store [[COPY_OPAQUE]] to [init] [[PROJ_BOX]] : $*@opened({{.*}}) Error & Foo // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] : $Error & Foo // CHECK: return [[EXIST_BOX]] : $Error // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s210______compErasures5Error_psAC_AA3FoopF' func s210______compErasure(_ x: Foo & Error) -> Error { return x } // Tests that existential boxes can contain opaque types // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s220_____openExistBoxSSs5Error_pF : $@convention(thin) (@owned Error) -> @owned String { // CHECK: bb0([[ARG:%.*]] : $Error): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[OPAQUE_ARG:%.*]] = open_existential_box_value [[BORROWED_ARG]] : $Error to $@opened({{.*}}) Error // CHECK: [[ALLOC_OPEN:%.*]] = alloc_stack $@opened({{.*}}) Error // CHECK: store_borrow [[OPAQUE_ARG]] to [[ALLOC_OPEN]] // CHECK: dealloc_stack [[ALLOC_OPEN]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] : $Error // CHECK: return {{.*}} : $String // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s220_____openExistBoxSSs5Error_pF' func s220_____openExistBox(_ x: Error) -> String { return x._domain } // Tests conditional value casts and correspondingly generated reabstraction thunk // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s230______condFromAnyyypF : $@convention(thin) (@in Any) -> () { // CHECK: bb0([[ARG:%.*]] : $Any): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: checked_cast_value_br [[COPY__ARG]] : $Any to $@callee_guaranteed (@in (Int, (Int, (Int, Int)), Int)) -> @out (Int, (Int, (Int, Int)), Int), bb2, bb1 // CHECK: bb2([[THUNK_PARAM:%.*]] : $@callee_guaranteed (@in (Int, (Int, (Int, Int)), Int)) -> @out (Int, (Int, (Int, Int)), Int)): // CHECK: [[THUNK_REF:%.*]] = function_ref @{{.*}} : $@convention(thin) (Int, Int, Int, Int, Int, @guaranteed @callee_guaranteed (@in (Int, (Int, (Int, Int)), Int)) -> @out (Int, (Int, (Int, Int)), Int)) -> (Int, Int, Int, Int, Int) // CHECK: partial_apply [callee_guaranteed] [[THUNK_REF]]([[THUNK_PARAM]]) // CHECK: bb6: // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s230______condFromAnyyypF' func s230______condFromAny(_ x: Any) { if let f = x as? (Int, (Int, (Int, Int)), Int) -> (Int, (Int, (Int, Int)), Int) { _ = f(24, (4,(2, 42)), 42) } } // Tests LValue of error types / existential boxes // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s240_____propOfLValueSSs5Error_pF : $@convention(thin) (@owned Error) -> @owned String { // CHECK: bb0([[ARG:%.*]] : $Error): // CHECK: [[ALLOC_OF_BOX:%.*]] = alloc_box ${ var Error } // CHECK: [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: store [[COPY_ARG]] to [init] [[PROJ_BOX]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PROJ_BOX]] : $*Error // CHECK: [[LOAD_BOX:%.*]] = load [copy] [[READ]] // CHECK: [[OPAQUE_ARG:%.*]] = open_existential_box [[LOAD_BOX]] : $Error to $*@opened({{.*}}) Error // CHECK: [[LOAD_OPAQUE:%.*]] = load [copy] [[OPAQUE_ARG]] // CHECK: [[ALLOC_OPEN:%.*]] = alloc_stack $@opened({{.*}}) Error // CHECK: store [[LOAD_OPAQUE]] to [init] [[ALLOC_OPEN]] // CHECK: [[RET_VAL:%.*]] = apply {{.*}}<@opened({{.*}}) Error>([[ALLOC_OPEN]]) // CHECK: return [[RET_VAL]] : $String // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s240_____propOfLValueSSs5Error_pF' func s240_____propOfLValue(_ x: Error) -> String { var x = x return x._domain } // Tests Implicit Value Construction under Opaque value mode // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s250_________testBoxTyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[BOX_MTYPE:%.*]] = metatype $@thin Box<Int>.Type // CHECK: [[MTYPE:%.*]] = metatype $@thin Int.Type // CHECK: [[INTLIT:%.*]] = integer_literal $Builtin.Int2048, 42 // CHECK: [[AINT:%.*]] = apply {{.*}}([[INTLIT]], [[MTYPE]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int // CHECK: apply {{.*}}<Int>([[AINT]], [[BOX_MTYPE]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @thin Box<τ_0_0>.Type) -> @out Box<τ_0_0> // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s250_________testBoxTyyF' func s250_________testBoxT() { let _ = Box(t: 42) } // Tests Address only enums // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s260_______AOnly_enumyAA17AddressOnlyStructVF : $@convention(thin) (AddressOnlyStruct) -> () { // CHECK: bb0([[ARG:%.*]] : $AddressOnlyStruct): // CHECK: [[MTYPE1:%.*]] = metatype $@thin AddressOnlyEnum.Type // CHECK: [[APPLY1:%.*]] = apply {{.*}}([[MTYPE1]]) : $@convention(thin) (@thin AddressOnlyEnum.Type) -> @owned @callee_guaranteed (@in EmptyP) -> @out AddressOnlyEnum // CHECK: destroy_value [[APPLY1]] // CHECK: [[MTYPE2:%.*]] = metatype $@thin AddressOnlyEnum.Type // CHECK: [[ENUM1:%.*]] = enum $AddressOnlyEnum, #AddressOnlyEnum.nought!enumelt // CHECK: [[MTYPE3:%.*]] = metatype $@thin AddressOnlyEnum.Type // CHECK: [[INIT_OPAQUE:%.*]] = init_existential_value [[ARG]] : $AddressOnlyStruct, $AddressOnlyStruct, $EmptyP // CHECK: [[ENUM2:%.*]] = enum $AddressOnlyEnum, #AddressOnlyEnum.mere!enumelt.1, [[INIT_OPAQUE]] : $EmptyP // CHECK: destroy_value [[ENUM2]] // CHECK: [[MTYPE4:%.*]] = metatype $@thin AddressOnlyEnum.Type // CHECK: [[ENUM3:%.*]] = enum $AddressOnlyEnum, #AddressOnlyEnum.phantom!enumelt.1, [[ARG]] : $AddressOnlyStruct // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s260_______AOnly_enumyAA17AddressOnlyStructVF' func s260_______AOnly_enum(_ s: AddressOnlyStruct) { _ = AddressOnlyEnum.mere _ = AddressOnlyEnum.nought _ = AddressOnlyEnum.mere(s) _ = AddressOnlyEnum.phantom(s) } // Tests InjectOptional for opaque value types + conversion of opaque structs // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s270_convOptAnyStructyAA0gH0VADSgcF : $@convention(thin) (@owned @callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct) -> () { // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[PAPPLY:%.*]] = partial_apply [callee_guaranteed] %{{.*}}([[COPY_ARG]]) : $@convention(thin) (@in Optional<AnyStruct>, @guaranteed @callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct) -> @out Optional<AnyStruct> // CHECK: destroy_value [[PAPPLY]] : $@callee_guaranteed (@in Optional<AnyStruct>) -> @out Optional<AnyStruct> // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct, $@callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct // CHECK: destroy_value [[ARG]] : $@callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s270_convOptAnyStructyAA0gH0VADSgcF' func s270_convOptAnyStruct(_ a1: @escaping (AnyStruct?) -> AnyStruct) { let _: (AnyStruct?) -> AnyStruct? = a1 } // Tests conversion between existential types // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s280_convExistTrivialyAA0G6StructVAA1P_pcF : $@convention(thin) (@owned @callee_guaranteed (@in P) -> TrivialStruct) -> () { // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed (@in P) -> TrivialStruct): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[PAPPLY:%.*]] = partial_apply [callee_guaranteed] %{{.*}}([[COPY_ARG]]) : $@convention(thin) (@in P2, @guaranteed @callee_guaranteed (@in P) -> TrivialStruct) -> @out P2 // CHECK: destroy_value [[PAPPLY]] : $@callee_guaranteed (@in P2) -> @out P2 // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_guaranteed (@in P) -> TrivialStruct // CHECK: destroy_value [[ARG]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s280_convExistTrivialyAA0G6StructVAA1P_pcF' func s280_convExistTrivial(_ s: @escaping (P) -> TrivialStruct) { let _: (P2) -> P2 = s } // Tests conversion between existential types - optionals case // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s290_convOptExistTrivyAA13TrivialStructVAA1P_pSgcF : $@convention(thin) (@owned @callee_guaranteed (@in Optional<P>) -> TrivialStruct) -> () { // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed (@in Optional<P>) -> TrivialStruct): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[PAPPLY:%.*]] = partial_apply [callee_guaranteed] %{{.*}}([[COPY_ARG]]) : $@convention(thin) (Optional<TrivialStruct>, @guaranteed @callee_guaranteed (@in Optional<P>) -> TrivialStruct) -> @out P2 // CHECK: destroy_value [[PAPPLY]] : $@callee_guaranteed (Optional<TrivialStruct>) -> @out P2 // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_guaranteed (@in Optional<P>) -> TrivialStruct, $@callee_guaranteed (@in Optional<P>) -> TrivialStruct // CHECK: destroy_value [[ARG]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s290_convOptExistTrivyAA13TrivialStructVAA1P_pSgcF' func s290_convOptExistTriv(_ s: @escaping (P?) -> TrivialStruct) { let _: (TrivialStruct?) -> P2 = s } // Tests corner-case: reabstraction of an empty tuple to any // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s300__convETupleToAnyyyycF : $@convention(thin) (@owned @callee_guaranteed () -> ()) -> () { // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed () -> ()): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[PAPPLY:%.*]] = partial_apply [callee_guaranteed] %{{.*}}([[COPY_ARG]]) : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out Any // CHECK: destroy_value [[PAPPLY]] : $@callee_guaranteed () -> @out Any // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_guaranteed () -> (), $@callee_guaranteed () -> () // CHECK: destroy_value [[ARG]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s300__convETupleToAnyyyycF' func s300__convETupleToAny(_ t: @escaping () -> ()) { let _: () -> Any = t } // Tests corner-case: reabstraction of a non-empty tuple to any // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s310__convIntTupleAnyySi_SitycF : $@convention(thin) (@owned @callee_guaranteed () -> (Int, Int)) -> () { // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed () -> (Int, Int)): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[PAPPLY:%.*]] = partial_apply [callee_guaranteed] %{{.*}}([[COPY_ARG]]) : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Int, Int)) -> @out Any // CHECK: destroy_value [[PAPPLY]] : $@callee_guaranteed () -> @out Any // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_guaranteed () -> (Int, Int), $@callee_guaranteed () -> (Int, Int) // CHECK: destroy_value [[ARG]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s310__convIntTupleAnyySi_SitycF' func s310__convIntTupleAny(_ t: @escaping () -> (Int, Int)) { let _: () -> Any = t } // Tests translating and imploding into Any under opaque value mode // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s320__transImplodeAnyyyypcF : $@convention(thin) (@owned @callee_guaranteed (@in Any) -> ()) -> () { // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed (@in Any) -> ()): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[PAPPLY:%.*]] = partial_apply [callee_guaranteed] %{{.*}}([[COPY_ARG]]) : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in Any) -> ()) -> () // CHECK: destroy_value [[PAPPLY]] : $@callee_guaranteed (Int, Int) -> () // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $@callee_guaranteed (@in Any) -> (), $@callee_guaranteed (@in Any) -> () // CHECK: destroy_value [[ARG]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s320__transImplodeAnyyyypcF' func s320__transImplodeAny(_ t: @escaping (Any) -> ()) { let _: ((Int, Int)) -> () = t } // Tests support for address only let closures under opaque value mode - they are not by-address anymore // --- // CHECK-LABEL: sil private @_T020opaque_values_silgen21s330___addrLetClosurexxlFxycfU_xycfU_ : $@convention(thin) <T> (@in_guaranteed T) -> @out T { // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[COPY_ARG:%.*]] = copy_value [[ARG]] : $T // CHECK: return [[COPY_ARG]] : $T // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s330___addrLetClosurexxlFxycfU_xycfU_' func s330___addrLetClosure<T>(_ x:T) -> T { return { { x }() }() } // Tests support for capture of a mutable opaque value type // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s340_______captureBoxyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[ALLOC_OF_BOX:%.*]] = alloc_box ${ var EmptyP }, var, name "mutableAddressOnly" // CHECK: [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]] // CHECK: [[APPLY_FOR_BOX:%.*]] = apply %{{.*}}(%{{.*}}) : $@convention(method) (@thin AddressOnlyStruct.Type) -> AddressOnlyStruct // CHECK: [[INIT_OPAQUE:%.*]] = init_existential_value [[APPLY_FOR_BOX]] : $AddressOnlyStruct, $AddressOnlyStruct, $EmptyP // CHECK: store [[INIT_OPAQUE]] to [init] [[PROJ_BOX]] : $*EmptyP // CHECK: [[BORROW_BOX:%.*]] = begin_borrow [[ALLOC_OF_BOX]] : ${ var EmptyP } // CHECK: mark_function_escape [[PROJ_BOX]] : $*EmptyP // CHECK: apply %{{.*}}([[BORROW_BOX]]) : $@convention(thin) (@guaranteed { var EmptyP }) -> () // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s340_______captureBoxyyF' func s340_______captureBox() { var mutableAddressOnly: EmptyP = AddressOnlyStruct() func captureEverything() { _ = s100_________identity((mutableAddressOnly)) } captureEverything() } // Tests support for if statements for opaque value(s) under new mode // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s350_______addrOnlyIfAA6EmptyP_pSb1x_tF : $@convention(thin) (Bool) -> @out EmptyP { // CHECK: bb0([[ARG:%.*]] : $Bool): // CHECK: [[ALLOC_OF_BOX:%.*]] = alloc_box ${ var EmptyP }, var // CHECK: [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]] // CHECK: [[APPLY_FOR_BOX:%.*]] = apply %{{.*}}(%{{.*}}) : $@convention(method) (@thin AddressOnlyStruct.Type) -> AddressOnlyStruct // CHECK: [[INIT_OPAQUE:%.*]] = init_existential_value [[APPLY_FOR_BOX]] : $AddressOnlyStruct, $AddressOnlyStruct, $EmptyP // CHECK: store [[INIT_OPAQUE]] to [init] [[PROJ_BOX]] : $*EmptyP // CHECK: [[APPLY_FOR_BRANCH:%.*]] = apply %{{.*}}([[ARG]]) : $@convention(method) (Bool) -> Builtin.Int1 // CHECK: cond_br [[APPLY_FOR_BRANCH]], bb2, bb1 // CHECK: bb1: // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PROJ_BOX]] : $*EmptyP // CHECK: [[RETVAL1:%.*]] = load [copy] [[READ]] : $*EmptyP // CHECK: br bb3([[RETVAL1]] : $EmptyP) // CHECK: bb2: // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PROJ_BOX]] : $*EmptyP // CHECK: [[RETVAL2:%.*]] = load [copy] [[READ]] : $*EmptyP // CHECK: br bb3([[RETVAL2]] : $EmptyP) // CHECK: bb3([[RETVAL:%.*]] : $EmptyP): // CHECK: destroy_value [[ALLOC_OF_BOX]] // CHECK: return [[RETVAL]] : $EmptyP // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s350_______addrOnlyIfAA6EmptyP_pSb1x_tF' func s350_______addrOnlyIf(x: Bool) -> EmptyP { var a : EmptyP = AddressOnlyStruct() return x ? a : a } // Tests support for guards and indirect enums for opaque values // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s360________guardEnumyAA08IndirectF0OyxGlF : $@convention(thin) <T> (@owned IndirectEnum<T>) -> () { // CHECK: bb0([[ARG:%.*]] : $IndirectEnum<T>): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: switch_enum [[COPY__ARG]] : $IndirectEnum<T>, case #IndirectEnum.Node!enumelt.1: [[NODE_BB:bb[0-9]+]], case #IndirectEnum.Nil!enumelt: [[NIL_BB:bb[0-9]+]] // // CHECK: [[NIL_BB]]: // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $IndirectEnum<T>, $IndirectEnum<T> // CHECK: br [[NIL_TRAMPOLINE:bb[0-9]+]] // // CHECK: [[NIL_TRAMPOLINE]]: // CHECK: br [[EPILOG_BB:bb[0-9]+]] // // CHECK: [[NODE_BB]]([[EARG:%.*]] : $<τ_0_0> { var τ_0_0 } <T>): // CHECK: [[PROJ_BOX:%.*]] = project_box [[EARG]] // CHECK: [[LOAD_BOX:%.*]] = load [take] [[PROJ_BOX]] : $*T // CHECK: [[COPY_BOX:%.*]] = copy_value [[LOAD_BOX]] : $T // CHECK: destroy_value [[EARG]] // CHECK: br [[CONT_BB:bb[0-9]+]] // // CHECK: [[CONT_BB]]: // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $IndirectEnum<T>, $IndirectEnum<T> // CHECK: destroy_value [[COPY_BOX]] // CHECK: br [[EPILOG_BB]] // // CHECK: [[EPILOG_BB]]: // CHECK: destroy_value [[ARG]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s360________guardEnumyAA08IndirectF0OyxGlF' func s360________guardEnum<T>(_ e: IndirectEnum<T>) { do { guard case .Node(let x) = e else { return } _ = x } } // Tests contextual init() of opaque value types // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s370_____optToOptCastxSgSQyxGlF : $@convention(thin) <T> (@in Optional<T>) -> @out Optional<T> { // CHECK: bb0([[ARG:%.*]] : $Optional<T>): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] : $Optional<T>, $Optional<T> // CHECK: destroy_value [[ARG]] // CHECK: return [[COPY__ARG]] : $Optional<T> // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s370_____optToOptCastxSgSQyxGlF' func s370_____optToOptCast<T>(_ x : T!) -> T? { return x } // Tests casting optional opaques to optional opaques // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s380___contextualInitySiSgF : $@convention(thin) (Optional<Int>) -> () { // CHECK: bb0([[ARG:%.*]] : $Optional<Int>): // CHECK: [[ALLOC_OF_BOX:%.*]] = alloc_box ${ var Optional<Int> }, var // CHECK: [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]] // CHECK: store [[ARG]] to [trivial] [[PROJ_BOX]] : $*Optional<Int> // CHECK: destroy_value [[ALLOC_OF_BOX]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s380___contextualInitySiSgF' func s380___contextualInit(_ a : Int?) { var x: Int! = a _ = x } // Tests opaque call result types // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s390___addrCallResultyxycSglF : $@convention(thin) <T> (@owned Optional<@callee_guaranteed () -> @out T>) -> () { // CHECK: bb0([[ARG:%.*]] : $Optional<@callee_guaranteed () -> @out T>): // CHECK: [[ALLOC_OF_BOX:%.*]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK: [[PROJ_BOX:%.*]] = project_box [[ALLOC_OF_BOX]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[SENUM:%.*]] = select_enum [[COPY__ARG]] // CHECK: cond_br [[SENUM]], bb3, bb1 // CHECK: bb1: // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: br bb2 // CHECK: bb2: // CHECK: [[ONONE:%.*]] = enum $Optional<T>, #Optional.none!enumelt // CHECK: br bb4([[ONONE]] : $Optional<T>) // CHECK: bb4(%{{.*}} : $Optional<T>): // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s390___addrCallResultyxycSglF' func s390___addrCallResult<T>(_ f: (() -> T)?) { var x = f?() _ = x } // Tests reabstraction / partial apply of protocols under opaque value mode // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s400______maybeClonePyAA8Clonable_p1c_tF : $@convention(thin) (@in Clonable) -> () { // CHECK: bb0([[ARG:%.*]] : $Clonable): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[OPEN_ARG:%.*]] = open_existential_value [[BORROWED_ARG]] : $Clonable // CHECK: [[COPY_OPAQUE:%.*]] = copy_value [[OPEN_ARG]] // CHECK: [[APPLY_OPAQUE:%.*]] = apply %{{.*}}<@opened({{.*}}) Clonable>([[COPY_OPAQUE]]) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@in τ_0_0) -> @owned @callee_guaranteed () -> @out Optional<τ_0_0> // CHECK: [[PAPPLY:%.*]] = partial_apply [callee_guaranteed] %{{.*}}<@opened({{.*}}) Clonable>([[APPLY_OPAQUE]]) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out Optional<τ_0_0>) -> @out Optional<Clonable> // CHECK: end_borrow [[BORROWED_ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s400______maybeClonePyAA8Clonable_p1c_tF' func s400______maybeCloneP(c: Clonable) { let _: () -> Clonable? = c.maybeClone } // Tests global opaque values / subscript rvalues // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s410__globalRvalueGetS2iF : $@convention(thin) (Int) -> Int { // CHECK: bb0([[ARG:%.*]] : $Int): // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @_T020opaque_values_silgen16subscriptableGetAA013SubscriptableE0_pvp : $*SubscriptableGet // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBAL_ADDR]] : $*SubscriptableGet // CHECK: [[OPEN_ARG:%.*]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGet to $*@opened // CHECK: [[GET_OPAQUE:%.*]] = load [copy] [[OPEN_ARG]] : $*@opened // CHECK: [[RETVAL:%.*]] = apply %{{.*}}<@opened({{.*}}) SubscriptableGet>([[ARG]], [[GET_OPAQUE]]) : $@convention(witness_method: SubscriptableGet) <τ_0_0 where τ_0_0 : SubscriptableGet> (Int, @in_guaranteed τ_0_0) -> Int // CHECK: destroy_value [[GET_OPAQUE]] // CHECK: return [[RETVAL]] : $Int // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s410__globalRvalueGetS2iF' func s410__globalRvalueGet(_ i : Int) -> Int { return subscriptableGet[i] } // Tests global opaque values / subscript lvalues // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s420__globalLvalueGetS2iF : $@convention(thin) (Int) -> Int { // CHECK: bb0([[ARG:%.*]] : $Int): // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @_T020opaque_values_silgen19subscriptableGetSetAA013SubscriptableeF0_pvp : $*SubscriptableGetSet // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBAL_ADDR]] : $*SubscriptableGetSet // CHECK: [[OPEN_ARG:%.*]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGetSet to $*@opened // CHECK: [[GET_OPAQUE:%.*]] = load [copy] [[OPEN_ARG]] : $*@opened // CHECK: [[RETVAL:%.*]] = apply %{{.*}}<@opened({{.*}}) SubscriptableGetSet>([[ARG]], [[GET_OPAQUE]]) : $@convention(witness_method: SubscriptableGetSet) <τ_0_0 where τ_0_0 : SubscriptableGetSet> (Int, @in_guaranteed τ_0_0) -> Int // CHECK: destroy_value [[GET_OPAQUE]] // CHECK: return [[RETVAL]] : $Int // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s420__globalLvalueGetS2iF' func s420__globalLvalueGet(_ i : Int) -> Int { return subscriptableGetSet[i] } // Tests tuple transformation // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s430_callUnreachableFyx1t_tlF : $@convention(thin) <T> (@in T) -> () { // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[APPLY_T:%.*]] = apply %{{.*}}<((T) -> (), T)>() : $@convention(thin) <τ_0_0> () -> @out Optional<(Int, τ_0_0)> // CHECK: switch_enum [[APPLY_T]] : $Optional<(Int, (@callee_guaranteed (@in T) -> @out (), T))>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1 // CHECK: bb2([[ENUMARG:%.*]] : $(Int, (@callee_guaranteed (@in T) -> @out (), T))): // CHECK: ([[TELEM0:%.*]], [[TELEM1:%.*]]) = destructure_tuple [[ENUMARG]] : $(Int, (@callee_guaranteed (@in T) -> @out (), T)) // CHECK: ([[TELEM10:%.*]], [[TELEM11:%.*]]) = destructure_tuple [[TELEM1]] : $(@callee_guaranteed (@in T) -> @out (), T) // CHECK: [[PAPPLY:%.*]] = partial_apply [callee_guaranteed] %{{.*}}<T>([[TELEM10]]) : $@convention(thin) <τ_0_0> (@in τ_0_0, @guaranteed @callee_guaranteed (@in τ_0_0) -> @out ()) -> () // CHECK: [[NEWT0:%.*]] = tuple ([[PAPPLY]] : $@callee_guaranteed (@in T) -> (), [[TELEM11]] : $T) // CHECK: [[NEWT1:%.*]] = tuple ([[TELEM0]] : $Int, [[NEWT0]] : $(@callee_guaranteed (@in T) -> (), T)) // CHECK: [[NEWENUM:%.*]] = enum $Optional<(Int, (@callee_guaranteed (@in T) -> (), T))>, #Optional.some!enumelt.1, [[NEWT1]] : $(Int, (@callee_guaranteed (@in T) -> (), T)) // CHECK: br bb3([[NEWENUM]] : $Optional<(Int, (@callee_guaranteed (@in T) -> (), T))>) // CHECK: bb3([[ENUMIN:%.*]] : $Optional<(Int, (@callee_guaranteed (@in T) -> (), T))>): // CHECK: destroy_value [[ENUMIN]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s430_callUnreachableFyx1t_tlF' func s430_callUnreachableF<T>(t: T) { let _: (Int, ((T) -> (), T))? = unreachableF() } // Further testing for conditional checked cast under opaque value mode - make sure we don't create a buffer for results // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s440__cleanupEmissionyxlF : $@convention(thin) <T> (@in T) -> () { // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPY_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: checked_cast_value_br [[COPY_ARG]] : $T to $EmptyP, bb2, bb1 // // CHECK: bb2([[PTYPE:%.*]] : $EmptyP): // CHECK: [[PSOME:%.*]] = enum $Optional<EmptyP>, #Optional.some!enumelt.1, [[PTYPE]] : $EmptyP // CHECK: br bb3([[PSOME]] : $Optional<EmptyP>) // // CHECK: bb3([[ENUMRES:%.*]] : $Optional<EmptyP>): // CHECK: switch_enum [[ENUMRES]] : $Optional<EmptyP>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[NONE_BB]]: // CHECK: end_borrow [[BORROWED_ARG]] // CHECK: br [[NONE_TRAMPOLINE:bb[0-9]+]] // // CHECK: [[NONE_TRAMPOLINE]]: // CHECK: br [[EPILOG_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[ENUMRES2:%.*]] : $EmptyP): // CHECK: br [[CONT_BB:bb[0-9]+]] // // CHECK: [[CONT_BB]]: // CHECK: end_borrow [[BORROWED_ARG]] // CHECK: destroy_value [[ENUMRES2]] // CHECK: br [[EPILOG_BB]] // // CHECK: [[EPILOG_BB]]: // CHECK: destroy_value [[ARG]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s440__cleanupEmissionyxlF' func s440__cleanupEmission<T>(_ x: T) { guard let x2 = x as? EmptyP else { return } _ = x2 } // Test SILGenBuilder.loadCopy(). // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s450__________lastValxxd_tlF : $@convention(thin) <T> (@owned Array<T>) -> @out T // CHECK: [[LOAD:%.*]] = load [copy] %{{.*}} : $*T // CHECK: return [[LOAD]] : $T // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s450__________lastValxxd_tlF' func s450__________lastVal<T>(_ rest: T...) -> T { var minValue: T for value in rest { minValue = value } return minValue } // Test SILGenFunction::emitPointerToPointer. // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s460______________fooSRyxGSPyxG1p_tlF : $@convention(thin) <Element> (UnsafePointer<Element>) -> UnsafeBufferPointer<Element> { // CHECK: [[F:%.*]] = function_ref @_T0s017_convertPointerToB8Argumentq_xs01_B0RzsABR_r0_lF : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : _Pointer, τ_0_1 : _Pointer> (@in τ_0_0) -> @out τ_0_1 // CHECK: apply [[F]]<UnsafePointer<Element>, UnsafePointer<Element>>(%0) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : _Pointer, τ_0_1 : _Pointer> (@in τ_0_0) -> @out τ_0_1 // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s460______________fooSRyxGSPyxG1p_tlF' func s460______________foo<Element>(p: UnsafePointer<Element>) -> UnsafeBufferPointer<Element> { return UnsafeBufferPointer(start: p, count: 1) } // Test emitNativeToCBridgedNonoptionalValue. // --- // CHECK-objc-LABEL: sil hidden @_T020opaque_values_silgen21s470________nativeToCyXlyp7fromAny_tF : $@convention(thin) (@in Any) -> @owned AnyObject { // CHECK-objc bb0(%0 : $Any): // CHECK-objc [[BORROW:%.*]] = begin_borrow %0 : $Any // CHECK-objc [[SRC:%.*]] = copy_value [[BORROW]] : $Any // CHECK-objc [[OPEN:%.*]] = open_existential_opaque [[SRC]] : $Any to $@opened // CHECK-objc [[COPY:%.*]] = copy_value [[OPEN]] : $@opened // CHECK-objc [[F:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveCyXlxlF : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @owned AnyObject // CHECK-objc [[RET:%.*]] = apply [[F]]<@opened("{{.*}}") Any>([[COPY]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @owned AnyObject // CHECK-objc destroy_value [[SRC]] : $Any // CHECK-objc destroy_value %0 : $Any // CHECK-objc return [[RET]] : $AnyObject // CHECK-objc-LABEL: } // end sil function '_T020opaque_values_silgen21s470________nativeToCyXlyp7fromAny_tF' #if _runtime(_ObjC) func s470________nativeToC(fromAny any: Any) -> AnyObject { return any as AnyObject } #endif // Test emitOpenExistential. // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s480_________getErroryps0F0_p04someF0_tF : $@convention(thin) (@owned Error) -> @out Any { // CHECK: bb0(%0 : $Error): // CHECK: [[BORROW:%.*]] = begin_borrow %0 : $Error // CHECK: [[VAL:%.*]] = open_existential_box_value [[BORROW]] : $Error to $@opened("{{.*}}") Error // CHECK: [[COPY:%.*]] = copy_value [[VAL]] : $@opened("{{.*}}") Error // CHECK: [[ANY:%.*]] = init_existential_value [[COPY]] : $@opened("{{.*}}") Error, $@opened("{{.*}}") Error, $Any // CHECK: destroy_value %0 : $Error // CHECK: return [[ANY]] : $Any // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s480_________getErroryps0F0_p04someF0_tF' func s480_________getError(someError: Error) -> Any { return someError } // Test SILBuilder.createLoadBorrow. // --- // CHECK-LABEL: sil private @_T020opaque_values_silgen21s490_______loadBorrowyyF3FooL_V3foo7ElementQzSg5IndexQz3pos_tF : $@convention(method) <Elements where Elements : Collection> (@in Elements.Index, @inout Foo<Elements>) -> @out Optional<Elements.Element> { // CHECK: bb0(%0 : $Elements.Index, %1 : $*Foo<Elements>): // CHECK: [[READ:%.*]] = begin_access [read] [unknown] %1 : $*Foo<Elements> // CHECK: [[LOAD:%.*]] = load [copy] [[READ]] : $*Foo<Elements> // CHECK: end_access [[READ]] : $*Foo<Elements> // CHECK: [[BORROW_LOAD:%.*]] = begin_borrow [[LOAD]] // CHECK: [[EXTRACT:%.*]] = struct_extract [[BORROW_LOAD]] : $Foo<Elements>, #<abstract function>Foo._elements // CHECK: [[COPYELT:%.*]] = copy_value [[EXTRACT]] : $Elements // CHECK: [[BORROW:%.*]] = begin_borrow %0 : $Elements.Index // CHECK: [[COPYIDX:%.*]] = copy_value [[BORROW]] : $Elements.Index // CHECK: [[WT:%.*]] = witness_method $Elements, #Collection.subscript!getter.1 : <Self where Self : Collection> (Self) -> (Self.Index) -> Self.Element : $@convention(witness_method: Collection) <τ_0_0 where τ_0_0 : Collection> (@in τ_0_0.Index, @in_guaranteed τ_0_0) -> @out τ_0_0.Element // CHECK: %{{.*}} = apply [[WT]]<Elements>([[COPYIDX]], [[COPYELT]]) : $@convention(witness_method: Collection) <τ_0_0 where τ_0_0 : Collection> (@in τ_0_0.Index, @in_guaranteed τ_0_0) -> @out τ_0_0.Element // CHECK: destroy_value [[COPYELT]] : $Elements // CHECK: [[ENUM:%.*]] = enum $Optional<Elements.Element>, #Optional.some!enumelt.1, %13 : $Elements.Element // CHECK: end_borrow [[BORROW]] from %0 : $Elements.Index, $Elements.Index // CHECK: destroy_value [[LOAD]] // CHECK: destroy_value %0 : $Elements.Index // CHECK: return %15 : $Optional<Elements.Element> // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s490_______loadBorrowyyF3FooL_V3foo7ElementQzSg5IndexQz3pos_tF' func s490_______loadBorrow() { struct Foo<Elements : Collection> { internal let _elements: Elements public mutating func foo(pos: Elements.Index) -> Elements.Element? { return _elements[pos] } } var foo = Foo(_elements: []) _ = foo.foo(pos: 1) } protocol ConvertibleToP { func asP() -> P } // Test visitBindOptionalExpr // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s500_______getAnyHashAA1P_pSgAA14ConvertibleToP_pSgF : $@convention(thin) (@in Optional<ConvertibleToP>) -> @out Optional<P> { // CHECK: bb0(%0 : $Optional<ConvertibleToP>): // CHECK: [[BORROW_ARG:%.*]] = begin_borrow %0 : $Optional<ConvertibleToP> // CHECK: [[COPY:%.*]] = copy_value [[BORROW_ARG]] : $Optional<ConvertibleToP> // CHECK: [[DATA:%.*]] = unchecked_enum_data [[COPY]] : $Optional<ConvertibleToP>, #Optional.some!enumelt.1 // CHECK: [[BORROW_DATA:%.*]] = begin_borrow [[DATA]] : $ConvertibleToP // CHECK: [[VAL:%.*]] = open_existential_value [[BORROW_DATA]] : $ConvertibleToP to $@opened("{{.*}}") ConvertibleToP // CHECK: [[WT:%.*]] = witness_method $@opened("{{.*}}") ConvertibleToP, #ConvertibleToP.asP!1 : <Self where Self : ConvertibleToP> (Self) -> () -> P, [[VAL]] : $@opened("{{.*}}") ConvertibleToP : $@convention(witness_method: ConvertibleToP) <τ_0_0 where τ_0_0 : ConvertibleToP> (@in_guaranteed τ_0_0) -> @out P // CHECK: [[AS_P:%.*]] = apply [[WT]]<@opened("{{.*}}") ConvertibleToP>([[VAL]]) : $@convention(witness_method: ConvertibleToP) <τ_0_0 where τ_0_0 : ConvertibleToP> (@in_guaranteed τ_0_0) -> @out P // CHECK: [[ENUM:%.*]] = enum $Optional<P>, #Optional.some!enumelt.1, [[AS_P]] : $P // CHECK: destroy_value [[DATA]] : $ConvertibleToP // CHECK: end_borrow [[BORROW_ARG]] from %0 : $Optional<ConvertibleToP>, $Optional<ConvertibleToP> // CHECK: br bb{{.*}}([[ENUM]] : $Optional<P>) // CHECK: // end sil function '_T020opaque_values_silgen21s500_______getAnyHashAA1P_pSgAA14ConvertibleToP_pSgF' func s500_______getAnyHash(_ value: ConvertibleToP?) -> P? { return value?.asP() } public protocol FooP { func foo() -> Self } // Test emitting a protocol witness for a method (with @in_guaranteed self) on a dependent generic type. // --- // CHECK-LABEL: sil private [transparent] [thunk] @_T020opaque_values_silgen21s510_______OpaqueSelfVyxGAA4FooPA2aEP3fooxyFTW : $@convention(witness_method: FooP) <τ_0_0> (@in_guaranteed s510_______OpaqueSelf<τ_0_0>) -> @out s510_______OpaqueSelf<τ_0_0> { // CHECK: bb0(%0 : $s510_______OpaqueSelf<τ_0_0>): // CHECK: [[FN:%.*]] = function_ref @_T020opaque_values_silgen21s510_______OpaqueSelfV3fooACyxGyF : $@convention(method) <τ_0_0> (@in_guaranteed s510_______OpaqueSelf<τ_0_0>) -> @out s510_______OpaqueSelf<τ_0_0> // CHECK: [[RESULT:%.*]] = apply [[FN]]<τ_0_0>(%0) : $@convention(method) <τ_0_0> (@in_guaranteed s510_______OpaqueSelf<τ_0_0>) -> @out s510_______OpaqueSelf<τ_0_0> // CHECK: return [[RESULT]] : $s510_______OpaqueSelf<τ_0_0> // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s510_______OpaqueSelfVyxGAA4FooPA2aEP3fooxyFTW' struct s510_______OpaqueSelf<Base> : FooP { var x: Base func foo() -> s510_______OpaqueSelf<Base> { return self } } // Tests conditional value casts and correspondingly generated reabstraction thunk, with <T> types // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen21s999_____condTFromAnyyyp_xtlF : $@convention(thin) <T> (@in Any, @in T) -> () { // CHECK: bb0([[ARG0:%.*]] : $Any, [[ARG1:%.*]] : $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG0]] // CHECK: [[COPY__ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: checked_cast_value_br [[COPY__ARG]] : $Any to $@callee_guaranteed (@in (Int, T)) -> @out (Int, T), bb2, bb1 // CHECK: bb2([[THUNK_PARAM:%.*]] : $@callee_guaranteed (@in (Int, T)) -> @out (Int, T)): // CHECK: [[THUNK_REF:%.*]] = function_ref @{{.*}} : $@convention(thin) <τ_0_0> (Int, @in τ_0_0, @guaranteed @callee_guaranteed (@in (Int, τ_0_0)) -> @out (Int, τ_0_0)) -> (Int, @out τ_0_0) // CHECK: partial_apply [callee_guaranteed] [[THUNK_REF]]<T>([[THUNK_PARAM]]) // CHECK: bb6: // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen21s999_____condTFromAnyyyp_xtlF' func s999_____condTFromAny<T>(_ x: Any, _ y: T) { if let f = x as? (Int, T) -> (Int, T) { _ = f(42, y) } } // Make sure that we insert a destroy of the box even though we used an Int type. // CHECK-LABEL: sil @_T020opaque_values_silgen22s020_______assignToVaryyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[Y_BOX:%.*]] = alloc_box ${ var Int }, var, name "y" // CHECK: [[PROJECT_Y_BOX:%.*]] = project_box [[Y_BOX]] : ${ var Int }, 0 // CHECK: [[X_BOX:%.*]] = alloc_box ${ var Any }, var, name "x" // CHECK: [[PROJECT_X_BOX:%.*]] = project_box [[X_BOX]] : ${ var Any }, 0 // CHECK: [[ACCESS_PROJECT_Y_BOX:%.*]] = begin_access [read] [unknown] [[PROJECT_Y_BOX]] : $*Int // CHECK: [[Y:%.*]] = load [trivial] [[ACCESS_PROJECT_Y_BOX]] : $*Int // CHECK: [[Y_ANY_FOR_X:%.*]] = init_existential_value [[Y]] : $Int, $Int, $Any // CHECK: store [[Y_ANY_FOR_X]] to [init] [[PROJECT_X_BOX]] // CHECK: [[ACCESS_PROJECT_Y_BOX:%.*]] = begin_access [read] [unknown] [[PROJECT_Y_BOX]] : $*Int // CHECK: [[Y:%.*]] = load [trivial] [[ACCESS_PROJECT_Y_BOX]] : $*Int // CHECK: [[Y_ANY_FOR_Z:%.*]] = init_existential_value [[Y]] : $Int, $Int, $Any // CHECK: destroy_value [[Y_ANY_FOR_Z]] // CEHCK: destroy_value [[X_BOX]] // CHECK: destroy_value [[Y_BOX]] // CHECK: } // end sil function '_T020opaque_values_silgen22s020_______assignToVaryyF' public func s020_______assignToVar() { var y: Int = 3 var x: Any = y let z: Any = y } // s250_________testBoxT continued Test Implicit Value Construction under Opaque value mode // --- // CHECK-LABEL: sil hidden @_T020opaque_values_silgen3BoxVACyxGx1t_tcfC : $@convention(method) <T> (@in T, @thin Box<T>.Type) -> @out Box<T> { // CHECK: bb0([[ARG0:%.*]] : $T, [[ARG1:%.*]] : $@thin Box<T>.Type): // CHECK: [[RETVAL:%.*]] = struct $Box<T> ([[ARG0]] : $T) // CHECK: return [[RETVAL]] : $Box<T> // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen3BoxVACyxGx1t_tcfC' // s270_convOptAnyStruct continued Test: reabstraction thunk helper // --- // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T020opaque_values_silgen9AnyStructVSgACIegir_A2DIegir_TR : $@convention(thin) (@in Optional<AnyStruct>, @guaranteed @callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct) -> @out Optional<AnyStruct> { // CHECK: bb0([[ARG0:%.*]] : $Optional<AnyStruct>, [[ARG1:%.*]] : $@callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct): // CHECK: [[APPLYARG:%.*]] = apply [[ARG1]]([[ARG0]]) : $@callee_guaranteed (@in Optional<AnyStruct>) -> @out AnyStruct // CHECK: [[RETVAL:%.*]] = enum $Optional<AnyStruct>, #Optional.some!enumelt.1, [[APPLYARG]] : $AnyStruct // CHECK: return [[RETVAL]] : $Optional<AnyStruct> // CHECK-LABEL: } // end sil function '_T020opaque_values_silgen9AnyStructVSgACIegir_A2DIegir_TR' // s300__convETupleToAny continued Test: reabstraction of () to Any // --- // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0Ieg_ypIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out Any { // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed () -> ()): // CHECK: [[ASTACK:%.*]] = alloc_stack $Any // CHECK: [[IADDR:%.*]] = init_existential_addr [[ASTACK]] : $*Any, $() // CHECK: [[APPLYARG:%.*]] = apply [[ARG]]() : $@callee_guaranteed () -> () // CHECK: [[LOAD_EXIST:%.*]] = load [trivial] [[IADDR]] : $*() // CHECK: [[RETVAL:%.*]] = init_existential_value [[LOAD_EXIST]] : $(), $(), $Any // CHECK: return [[RETVAL]] : $Any // CHECK-LABEL: } // end sil function '_T0Ieg_ypIegr_TR' // s310_convIntTupleAny continued Test: reabstraction of non-empty tuple to Any // --- // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0S2iIegdd_ypIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Int, Int)) -> @out Any { // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed () -> (Int, Int)): // CHECK: [[ASTACK:%.*]] = alloc_stack $Any // CHECK: [[IADDR:%.*]] = init_existential_addr [[ASTACK]] : $*Any, $(Int, Int) // CHECK: [[TADDR0:%.*]] = tuple_element_addr [[IADDR]] : $*(Int, Int), 0 // CHECK: [[TADDR1:%.*]] = tuple_element_addr [[IADDR]] : $*(Int, Int), 1 // CHECK: [[APPLYARG:%.*]] = apply [[ARG]]() : $@callee_guaranteed () -> (Int, Int) // CHECK: [[TEXTRACT0:%.*]] = tuple_extract [[APPLYARG]] : $(Int, Int), 0 // CHECK: [[TEXTRACT1:%.*]] = tuple_extract [[APPLYARG]] : $(Int, Int), 1 // CHECK: store [[TEXTRACT0]] to [trivial] [[TADDR0]] : $*Int // CHECK: store [[TEXTRACT1]] to [trivial] [[TADDR1]] : $*Int // CHECK: [[LOAD_EXIST:%.*]] = load [trivial] [[IADDR]] : $*(Int, Int) // CHECK: [[RETVAL:%.*]] = init_existential_value [[LOAD_EXIST]] : $(Int, Int), $(Int, Int), $Any // CHECK: dealloc_stack [[ASTACK]] : $*Any // CHECK: return [[RETVAL]] : $Any // CHECK-LABEL: } // end sil function '_T0S2iIegdd_ypIegr_TR' // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @{{.*}} : $@convention(thin) (Int, Int, Int, Int, Int, @guaranteed @callee_guaranteed (@in (Int, (Int, (Int, Int)), Int)) -> @out (Int, (Int, (Int, Int)), Int)) -> (Int, Int, Int, Int, Int) // CHECK: bb0([[ARG0:%.*]] : $Int, [[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $Int, [[ARG3:%.*]] : $Int, [[ARG4:%.*]] : $Int, [[ARG5:%.*]] : $@callee_guaranteed (@in (Int, (Int, (Int, Int)), Int)) -> @out (Int, (Int, (Int, Int)), Int)): // CHECK: [[TUPLE_TO_APPLY0:%.*]] = tuple ([[ARG2]] : $Int, [[ARG3]] : $Int) // CHECK: [[TUPLE_TO_APPLY1:%.*]] = tuple ([[ARG1]] : $Int, [[TUPLE_TO_APPLY0]] : $(Int, Int)) // CHECK: [[TUPLE_TO_APPLY2:%.*]] = tuple ([[ARG0]] : $Int, [[TUPLE_TO_APPLY1]] : $(Int, (Int, Int)), [[ARG4]] : $Int) // CHECK: [[TUPLE_APPLY:%.*]] = apply [[ARG5]]([[TUPLE_TO_APPLY2]]) : $@callee_guaranteed (@in (Int, (Int, (Int, Int)), Int)) -> @out (Int, (Int, (Int, Int)), Int) // CHECK: [[RET_VAL0:%.*]] = tuple_extract [[TUPLE_APPLY]] : $(Int, (Int, (Int, Int)), Int), 0 // CHECK: [[TUPLE_EXTRACT1:%.*]] = tuple_extract [[TUPLE_APPLY]] : $(Int, (Int, (Int, Int)), Int), 1 // CHECK: [[RET_VAL1:%.*]] = tuple_extract [[TUPLE_EXTRACT1]] : $(Int, (Int, Int)), 0 // CHECK: [[TUPLE_EXTRACT2:%.*]] = tuple_extract [[TUPLE_EXTRACT1]] : $(Int, (Int, Int)), 1 // CHECK: [[RET_VAL2:%.*]] = tuple_extract [[TUPLE_EXTRACT2]] : $(Int, Int), 0 // CHECK: [[RET_VAL3:%.*]] = tuple_extract [[TUPLE_EXTRACT2]] : $(Int, Int), 1 // CHECK: [[RET_VAL4:%.*]] = tuple_extract [[TUPLE_APPLY]] : $(Int, (Int, (Int, Int)), Int), 2 // CHECK: [[RET_VAL_TUPLE:%.*]] = tuple ([[RET_VAL0]] : $Int, [[RET_VAL1]] : $Int, [[RET_VAL2]] : $Int, [[RET_VAL3]] : $Int, [[RET_VAL4]] : $Int) // CHECK: return [[RET_VAL_TUPLE]] : $(Int, Int, Int, Int, Int) // CHECK-LABEL: } // end sil function '{{.*}}' // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @{{.*}} : $@convention(thin) <T> (Int, @in T, @guaranteed @callee_guaranteed (@in (Int, T)) -> @out (Int, T)) -> (Int, @out T) { // CHECK: bb0([[ARG0:%.*]] : $Int, [[ARG1:%.*]] : $T, [[ARG2:%.*]] : $@callee_guaranteed (@in (Int, T)) -> @out (Int, T)): // CHECK: [[TUPLE_TO_APPLY:%.*]] = tuple ([[ARG0]] : $Int, [[ARG1]] : $T) // CHECK: [[TUPLE_APPLY:%.*]] = apply [[ARG2]]([[TUPLE_TO_APPLY]]) : $@callee_guaranteed (@in (Int, T)) -> @out (Int, T) // CHECK: [[TUPLE_BORROW:%.*]] = begin_borrow [[TUPLE_APPLY]] : $(Int, T) // CHECK: [[RET_VAL0:%.*]] = tuple_extract [[TUPLE_BORROW]] : $(Int, T), 0 // CHECK: [[TUPLE_EXTRACT:%.*]] = tuple_extract [[TUPLE_BORROW]] : $(Int, T), 1 // CHECK: [[RET_VAL1:%.*]] = copy_value [[TUPLE_EXTRACT]] : $T // CHECK: end_borrow [[TUPLE_BORROW]] from [[TUPLE_APPLY]] : $(Int, T), $(Int, T) // CHECK: destroy_value [[TUPLE_APPLY]] : $(Int, T) // CHECK: [[RET_VAL_TUPLE:%.*]] = tuple ([[RET_VAL0]] : $Int, [[RET_VAL1]] : $T) // CHECK: return [[RET_VAL_TUPLE]] : $(Int, T) // CHECK-LABEL: } // end sil function '{{.*}}' // Tests LogicalPathComponent's writeback for opaque value types // --- // CHECK-LABEL: sil @_T0s10DictionaryV20opaque_values_silgenE22inoutAccessOfSubscriptyq_3key_tF : $@convention(method) <Key, Value where Key : Hashable> (@in Value, @inout Dictionary<Key, Value>) -> () { // CHECK: bb0([[ARG0:%.*]] : $Value, [[ARG1:%.*]] : $*Dictionary<Key, Value>): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[ARG1]] : $*Dictionary<Key, Value> // CHECK: [[OPTIONAL_ALLOC:%.*]] = alloc_stack $Optional<Value> // CHECK: switch_enum_addr [[OPTIONAL_ALLOC]] : $*Optional<Value>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1 // CHECK: bb2: // CHECK: [[OPTIONAL_LOAD:%.*]] = load [take] [[OPTIONAL_ALLOC]] : $*Optional<Value> // CHECK: apply {{.*}}<Key, Value>([[OPTIONAL_LOAD]], {{.*}}, [[WRITE]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@in Optional<τ_0_1>, @in τ_0_1, @inout Dictionary<τ_0_0, τ_0_1>) -> () // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T0s10DictionaryV20opaque_values_silgenE22inoutAccessOfSubscriptyq_3key_tF' // Tests materializeForSet's createSetterCallback for opaque values // --- // CHECK-LABEL: sil shared [transparent] [serialized] @_T0s10DictionaryV20opaque_values_silgenEq_Sgq_cimytfU_ : $@convention(method) <Key, Value where Key : Hashable> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Dictionary<Key, Value>, @thick Dictionary<Key, Value>.Type) -> () { // CHECK: bb0([[ARG0:%.*]] : $Builtin.RawPointer, [[ARG1:%.*]] : $*Builtin.UnsafeValueBuffer, [[ARG2:%.*]] : $*Dictionary<Key, Value>, [[ARG3:%.*]] : $@thick Dictionary<Key, Value>.Type): // CHECK: [[PROJ_VAL1:%.*]] = project_value_buffer $Value in [[ARG1]] : $*Builtin.UnsafeValueBuffer // CHECK: [[LOAD_VAL1:%.*]] = load [take] [[PROJ_VAL1]] : $*Value // CHECK: [[ADDR_VAL0:%.*]] = pointer_to_address [[ARG0]] : $Builtin.RawPointer to [strict] $*Optional<Value> // CHECK: [[LOAD_VAL0:%.*]] = load [take] [[ADDR_VAL0]] : $*Optional<Value> // CHECK: apply {{.*}}<Key, Value>([[LOAD_VAL0]], [[LOAD_VAL1]], [[ARG2]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@in Optional<τ_0_1>, @in τ_0_1, @inout Dictionary<τ_0_0, τ_0_1>) -> () // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T0s10DictionaryV20opaque_values_silgenEq_Sgq_cimytfU_' extension Dictionary { public subscript(key: Value) -> Value? { @inline(__always) get { return key } set(newValue) { } } public mutating func inoutAccessOfSubscript(key: Value) { func increment(x: inout Value) { } increment(x: &self[key]!) } } // s400______maybeCloneP continued Test: reabstraction thunk // --- // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0xSgIegr_20opaque_values_silgen8Clonable_pSgIegr_AbCRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@guaranteed @callee_guaranteed () -> @out Optional<τ_0_0>) -> @out Optional<Clonable> { // CHECK: bb0([[ARG:%.*]] : $@callee_guaranteed () -> @out Optional<τ_0_0>): // CHECK: [[APPLY_ARG:%.*]] = apply [[ARG]]() : $@callee_guaranteed () -> @out Optional<τ_0_0> // CHECK: switch_enum [[APPLY_ARG]] : $Optional<τ_0_0>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1 // CHECK: bb1: // CHECK: [[ONONE:%.*]] = enum $Optional<Clonable>, #Optional.none!enumelt // CHECK: br bb3([[ONONE]] : $Optional<Clonable>) // CHECK: bb2([[ENUM_SOME:%.*]] : $τ_0_0): // CHECK: [[INIT_OPAQUE:%.*]] = init_existential_value [[ENUM_SOME]] : $τ_0_0, $τ_0_0, $Clonable // CHECK: [[OSOME:%.*]] = enum $Optional<Clonable>, #Optional.some!enumelt.1, [[INIT_OPAQUE]] : $Clonable // CHECK: br bb3([[OSOME]] : $Optional<Clonable>) // CHECK: bb3([[RETVAL:%.*]] : $Optional<Clonable>): // CHECK: return [[RETVAL]] : $Optional<Clonable> // CHECK-LABEL: } // end sil function '_T0xSgIegr_20opaque_values_silgen8Clonable_pSgIegr_AbCRzlTR' // s320__transImplodeAny continued Test: reabstraction thunk // --- // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0ypIegi_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in Any) -> ()) -> () { // CHECK: bb0([[ARG0:%.*]] : $Int, [[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $@callee_guaranteed (@in Any) -> ()): // CHECK: [[ASTACK:%.*]] = alloc_stack $Any // CHECK: [[IADDR:%.*]] = init_existential_addr [[ASTACK]] : $*Any, $(Int, Int) // CHECK: [[TADDR0:%.*]] = tuple_element_addr [[IADDR]] : $*(Int, Int), 0 // CHECK: store [[ARG0]] to [trivial] [[TADDR0]] : $*Int // CHECK: [[TADDR1:%.*]] = tuple_element_addr [[IADDR]] : $*(Int, Int), 1 // CHECK: store [[ARG1]] to [trivial] [[TADDR1]] : $*Int // CHECK: [[LOAD_EXIST:%.*]] = load [trivial] [[IADDR]] : $*(Int, Int) // CHECK: [[INIT_OPAQUE:%.*]] = init_existential_value [[LOAD_EXIST]] : $(Int, Int), $(Int, Int), $Any // CHECK: [[APPLYARG:%.*]] = apply [[ARG2]]([[INIT_OPAQUE]]) : $@callee_guaranteed (@in Any) -> () // CHECK: dealloc_stack [[ASTACK]] : $*Any // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '_T0ypIegi_S2iIegyy_TR'
apache-2.0
f653a695f481e9e007b2470150fc1c62
57.575781
360
0.6074
3.130825
false
false
false
false
PatrickChow/Swift-Awsome
News/Modules/Profile/Main/Model/ProfileModel.swift
1
3602
// // Created by Patrick Chow on 2017/5/23. // Copyright (c) 2017 Jiemian Technology. All rights reserved. import UIKit enum ProfileFeature { // 订阅类型 enum SubscriptionType { case author case album case theme } enum DisplayMode { case filterImage // 无图模式 case nightMode } case setting // 设置 case integralMall // 面点商城 case integral // 面点 ??? why? ¯\_(ツ)_/¯ case favorite // 我收藏的精华 case subscription(SubscriptionType) // 我订阅的主题,我收听的专辑,我关注的作者 case displayMode(DisplayMode) // 无图模式,夜间模式 case offline // 离线阅读 case feedback // 意见反馈 case message // 消息 case submissions // 爆料 case signIn // 登录 case register // 注册 } extension ProfileFeature { var icon: ImageAssets { switch self { case .integralMall: return .profile(.miandian) case .favorite: return .profile(.favorite) case let .subscription(e) where e == .album: return .profile(.album) case let .subscription(e) where e == .theme: return .profile(.theme) case let .subscription(e) where e == .author: return .profile(.author) case let .displayMode(e) where e == .filterImage: return .profile(.filter) case let .displayMode(e) where e == .nightMode: return .profile(.nightMode) case .offline: return .profile(.download) case .feedback: return .profile(.feedback) default: return .profile(.miandian) } } } extension ProfileFeature { var underlyingModuleNavigator: ModuleNavigator { switch self { case .integralMall: return .profile(.integralMall) case .setting: return .profile(.setting) case .favorite: return .profile(.favorite) case let .subscription(e) where e == .album: return .profile(.subscription(e)) case let .subscription(e) where e == .theme: return .profile(.subscription(e)) case let .subscription(e) where e == .author: return .profile(.subscription(e)) case .offline: return .profile(.offline) case .feedback: return .profile(.feedback) case .message: return .profile(.messages) case .submissions: return .profile(.submissions) case .signIn: return .auth(.auth(.signIn)) case .register: return .auth(.auth(.signUp)) default: fatalError("没有指定控制器,请仔细检查") } } var viewController: UIViewController { return Mediator.viewController(for: underlyingModuleNavigator) } } extension ProfileFeature: CustomStringConvertible { var description: String { switch self { case .integralMall: return "面点商城" case .integral: return "面点" case .favorite: return "我收藏的精华" case let .subscription(e) where e == .album: return "我收听的专辑" case let .subscription(e) where e == .theme: return "我订阅的主题" case let .subscription(e) where e == .author: return "我关注的作者" case let .displayMode(e) where e == .filterImage: return "无图模式" case let .displayMode(e) where e == .nightMode: return "夜间模式" case .offline: return "离线阅读" case .feedback: return "意见反馈" case .message: return "消息" case .submissions: return "爆料" default: return "" } } }
mit
747ccca2f5fe4d22058629480e4b904d
33.122449
87
0.613337
4.038647
false
false
false
false
alexpotter1/Weight-Tracker
Project/Weight Tracker/External Libraries/CorePlot_2.0r1/Source/examples/CPTTestApp-iPhone/Classes/ScatterPlotController.swift
2
6938
import UIKit class ScatterPlotController : UIViewController, CPTScatterPlotDataSource { private var scatterGraph : CPTXYGraph? = nil typealias plotDataType = [CPTScatterPlotField : Double] private var dataForPlot = [plotDataType]() // MARK: Initialization override func viewDidAppear(animated : Bool) { super.viewDidAppear(animated) // Create graph from theme let newGraph = CPTXYGraph(frame: CGRectZero) newGraph.applyTheme(CPTTheme(named: kCPTDarkGradientTheme)) let hostingView = self.view as! CPTGraphHostingView hostingView.hostedGraph = newGraph // Paddings newGraph.paddingLeft = 10.0 newGraph.paddingRight = 10.0 newGraph.paddingTop = 10.0 newGraph.paddingBottom = 10.0 // Plot space let plotSpace = newGraph.defaultPlotSpace as! CPTXYPlotSpace plotSpace.allowsUserInteraction = true plotSpace.yRange = CPTPlotRange(location:1.0, length:2.0) plotSpace.xRange = CPTPlotRange(location:1.0, length:3.0) // Axes let axisSet = newGraph.axisSet as! CPTXYAxisSet if let x = axisSet.xAxis { x.majorIntervalLength = 0.5 x.orthogonalPosition = 2.0 x.minorTicksPerInterval = 2 x.labelExclusionRanges = [ CPTPlotRange(location: 0.99, length: 0.02), CPTPlotRange(location: 1.99, length: 0.02), CPTPlotRange(location: 2.99, length: 0.02) ] } if let y = axisSet.xAxis { y.majorIntervalLength = 0.5 y.minorTicksPerInterval = 5 y.orthogonalPosition = 2.0 y.labelExclusionRanges = [ CPTPlotRange(location: 0.99, length: 0.02), CPTPlotRange(location: 1.99, length: 0.02), CPTPlotRange(location: 3.99, length: 0.02) ] y.delegate = self } // Create a blue plot area let boundLinePlot = CPTScatterPlot(frame: CGRectZero) let blueLineStyle = CPTMutableLineStyle() blueLineStyle.miterLimit = 1.0 blueLineStyle.lineWidth = 3.0 blueLineStyle.lineColor = CPTColor.blueColor() boundLinePlot.dataLineStyle = blueLineStyle boundLinePlot.identifier = "Blue Plot" boundLinePlot.dataSource = self newGraph.addPlot(boundLinePlot) let fillImage = CPTImage(named:"BlueTexture") fillImage.tiled = true boundLinePlot.areaFill = CPTFill(image: fillImage) boundLinePlot.areaBaseValue = 0.0 // Add plot symbols let symbolLineStyle = CPTMutableLineStyle() symbolLineStyle.lineColor = CPTColor.blackColor() let plotSymbol = CPTPlotSymbol.ellipsePlotSymbol() plotSymbol.fill = CPTFill(color: CPTColor.blueColor()) plotSymbol.lineStyle = symbolLineStyle plotSymbol.size = CGSize(width: 10.0, height: 10.0) boundLinePlot.plotSymbol = plotSymbol // Create a green plot area let dataSourceLinePlot = CPTScatterPlot(frame: CGRectZero) let greenLineStyle = CPTMutableLineStyle() greenLineStyle.lineWidth = 3.0 greenLineStyle.lineColor = CPTColor.greenColor() greenLineStyle.dashPattern = [5.0, 5.0] dataSourceLinePlot.dataLineStyle = greenLineStyle dataSourceLinePlot.identifier = "Green Plot" dataSourceLinePlot.dataSource = self // Put an area gradient under the plot above let areaColor = CPTColor(componentRed: 0.3, green: 1.0, blue: 0.3, alpha: 0.8) let areaGradient = CPTGradient(beginningColor: areaColor, endingColor: CPTColor.clearColor()) areaGradient.angle = -90.0 let areaGradientFill = CPTFill(gradient: areaGradient) dataSourceLinePlot.areaFill = areaGradientFill dataSourceLinePlot.areaBaseValue = 1.75 // Animate in the new plot, as an example dataSourceLinePlot.opacity = 0.0 newGraph.addPlot(dataSourceLinePlot) let fadeInAnimation = CABasicAnimation(keyPath: "opacity") fadeInAnimation.duration = 1.0 fadeInAnimation.removedOnCompletion = false fadeInAnimation.fillMode = kCAFillModeForwards fadeInAnimation.toValue = 1.0 dataSourceLinePlot.addAnimation(fadeInAnimation, forKey: "animateOpacity") // Add some initial data var contentArray = [plotDataType]() for i in 0 ..< 60 { let x = 1.0 + Double(i) * 0.05 let y = 1.2 * Double(arc4random()) / Double(UInt32.max) + 1.2 let dataPoint: plotDataType = [.X: x, .Y: y] contentArray.append(dataPoint) } self.dataForPlot = contentArray self.scatterGraph = newGraph } // MARK: - Plot Data Source Methods func numberOfRecordsForPlot(plot: CPTPlot) -> UInt { return UInt(self.dataForPlot.count) } func numberForPlot(plot: CPTPlot, field: UInt, recordIndex: UInt) -> AnyObject? { let plotField = CPTScatterPlotField(rawValue: Int(field)) if let num = self.dataForPlot[Int(recordIndex)][plotField!] { let plotID = plot.identifier as! String if (plotField! == .Y) && (plotID == "Green Plot") { return (num + 1.0) as NSNumber } else { return num as NSNumber } } else { return nil } } // MARK: - Axis Delegate Methods func axis(axis: CPTAxis, shouldUpdateAxisLabelsAtLocations locations: NSSet!) -> Bool { if let formatter = axis.labelFormatter { let labelOffset = axis.labelOffset var newLabels = Set<CPTAxisLabel>() for tickLocation in locations { if let labelTextStyle = axis.labelTextStyle?.mutableCopy() as? CPTMutableTextStyle { if tickLocation.doubleValue >= 0.0 { labelTextStyle.color = CPTColor.greenColor() } else { labelTextStyle.color = CPTColor.redColor() } let labelString = formatter.stringForObjectValue(tickLocation) let newLabelLayer = CPTTextLayer(text: labelString, style: labelTextStyle) let newLabel = CPTAxisLabel(contentLayer: newLabelLayer) newLabel.tickLocation = tickLocation as? NSNumber newLabel.offset = labelOffset newLabels.insert(newLabel) } axis.axisLabels = newLabels } } return false } }
apache-2.0
a853b206ec5ea40084ac1757309d43ae
36.101604
101
0.593399
4.436061
false
false
false
false
mickeyckm/nanodegree-mememe
MemeMe/MemeEditorViewController.swift
1
6210
// // MemeEditorViewController.swift // MemeMe // // Created by Mickey Cheong on 20/10/16. // Copyright © 2016 CHEO.NG. All rights reserved. // import UIKit class MemeEditorViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate { @IBOutlet weak var cameraBarButton: UIBarButtonItem! @IBOutlet weak var albumBarButton: UIBarButtonItem! @IBOutlet weak var cancelButton: UIBarButtonItem! @IBOutlet weak var shareButton: UIBarButtonItem! @IBOutlet weak var imageDisplay: UIImageView! @IBOutlet weak var bottomToolbar: UIToolbar! @IBOutlet weak var topTextField: UITextField! @IBOutlet weak var bottomTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if !UIImagePickerController.isSourceTypeAvailable(.camera) { cameraBarButton.isEnabled = false } if imageDisplay.image == nil { shareButton.isEnabled = false } topTextField.delegate = self stylizeTextField(textField: topTextField) bottomTextField.delegate = self stylizeTextField(textField: bottomTextField) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) subscribeToKeyboardNotifications() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) unsubscribeFromKeyboardNotifications() } func subscribeToKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: Notification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: Notification.Name.UIKeyboardWillHide, object: nil) } func unsubscribeFromKeyboardNotifications() { NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillHide, object: nil) } func presentImagePicker(sourceType: UIImagePickerControllerSourceType) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = sourceType present(imagePicker, animated: true, completion: nil) } @IBAction func captureImage(_ sender: AnyObject) { if UIImagePickerController.isSourceTypeAvailable(.camera) { presentImagePicker(sourceType: .camera) } else { cameraBarButton.isEnabled = false } } @IBAction func pickImage(_ sender: AnyObject) { presentImagePicker(sourceType: .photoLibrary) } @IBAction func shareMeme(_ sender: AnyObject) { let memedImage = generateMemedImage() let shareItems = [ memedImage ] let shareActivity = UIActivityViewController(activityItems: shareItems, applicationActivities: nil) shareActivity.completionWithItemsHandler = { activity, success, items, error in let meme = Meme(topText: self.topTextField.text, bottomText: self.bottomTextField.text, image: self.imageDisplay.image, memedImage: memedImage) // Add it to the memes array in the Application Delegate let object = UIApplication.shared.delegate let appDelegate = object as! AppDelegate appDelegate.memes.append(meme) } present(shareActivity, animated: true, completion: nil) } @IBAction func cancelImage(_ sender: AnyObject) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage imageDisplay.image = chosenImage shareButton.isEnabled = true dismiss(animated: true, completion: nil) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func keyboardWillShow(notification: Notification) { view.frame.origin.y = getKeyboardHeight(notification: notification) * (-1) } func keyboardWillHide(notification: Notification) { view.frame.origin.y = 0 } func getKeyboardHeight(notification: Notification) -> CGFloat { let userInfo = notification.userInfo let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect if bottomTextField.isFirstResponder { return keyboardSize.cgRectValue.height } else { return 0 } } func stylizeTextField(textField: UITextField) { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = NSTextAlignment.center let memeTextAttributes = [ NSStrokeColorAttributeName : UIColor.black, NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName : UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!, NSStrokeWidthAttributeName : -5.0, NSParagraphStyleAttributeName: paragraphStyle ] as [String : Any] textField.defaultTextAttributes = memeTextAttributes } func generateMemedImage() -> UIImage { // Hide toolbar and navbar navigationController?.navigationBar.isHidden = true bottomToolbar.isHidden = true // Render view to an image UIGraphicsBeginImageContext(view.frame.size) view.drawHierarchy(in: view.frame, afterScreenUpdates: true) let memedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() // Show toolbar and navbar navigationController?.navigationBar.isHidden = false bottomToolbar.isHidden = false return memedImage } }
mit
b0ba51624fc068edddc98923ca3e2a82
36.179641
155
0.679981
5.896486
false
false
false
false
LittleRockInGitHub/LLAlgorithm
Project/LLAlgorithmTests/BinarySearchingTests.swift
1
6469
// // BinarySearchingTests.swift // LLAlgorithmTests // // Created by Rock Yang on 2017/6/29. // Copyright © 2017年 Rock Yang. All rights reserved. // import XCTest import LLAlgorithm func _testBinarySearching<C : RandomAccessCollection>(in collection: C, with element: Int, position: BinarySearching.EqualPosition, ascending: Bool = true) where C.SubSequence : RandomAccessCollection, C.Element == Int { let result = collection.binarySearch(element, equalPosition: position, ascending: ascending) switch result { case let .found(idx): XCTAssertEqual(collection[idx], element) switch position { case .any: break case .first: if idx > collection.startIndex { if ascending { XCTAssertLessThan(collection[collection.index(before: idx)], element) } else { XCTAssertGreaterThan(collection[collection.index(before: idx)], element) } } case .last: if collection.index(after: idx) < collection.endIndex { if ascending { XCTAssertLessThan(element, collection[collection.index(after: idx)]) } else { XCTAssertGreaterThan(element, collection[collection.index(after: idx)]) } } } case let .notFound(insertion): if insertion > collection.startIndex { if ascending { XCTAssertLessThan(collection[collection.index(before: insertion)], element) } else { XCTAssertGreaterThan(collection[collection.index(before: insertion)], element) } } if insertion < collection.endIndex { if ascending { XCTAssertLessThan(element, collection[insertion]) } else { XCTAssertGreaterThan(element, collection[insertion]) } } } } class BinarySearchingTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSearching() { var array = [Int]() var result = array.binarySearch(0) // [] XCTAssertEqual(result.insertion, 0) array.append(0) result = array.binarySearch(0) // [0] XCTAssertEqual(result.found, 0) array.append(contentsOf: [1, 1, 1, 1, 1, 3, 4, 5]) result = array.binarySearch(5) // [0, 1, 1, 1, 1, 1, 3, 4, 5] XCTAssertEqual(result.found, 8) result = array.binarySearch(1) // [0, 1, 1, 1, 1, 1, 3, 4, 5] XCTAssertEqual(result.found, 4) result = array.binarySearch(1, equalPosition: .first) // [0, 1, 1, 1, 1, 1, 3, 4, 5] XCTAssertEqual(result.found, 1) result = array.binarySearch(1, equalPosition: .last) // [0, 1, 1, 1, 1, 1, 3, 4, 5] XCTAssertEqual(result.found, 5) result = array.binarySearch(-1) // [0, 1, 1, 1, 1, 1, 3, 4, 5] XCTAssertEqual(result.insertion, 0) result = array.binarySearch(2) // [0, 1, 1, 1, 1, 1, 3, 4, 5] XCTAssertEqual(result.insertion, 6) result = array.binarySearch(6) // [0, 1, 1, 1, 1, 1, 3, 4, 5] XCTAssertEqual(result.insertion, 9) } func testRandom() { for _ in 0..<1000 { var array = [Int]() array.append(contentsOf: _randomArray(1000)) array.sort() _testBinarySearching(in: array, with: Int(arc4random()) % 110 - 5, position: .random()) } for _ in 0..<1000 { var array = [Int]() array.append(contentsOf: _randomArray(1000)) let r = array.sorted().reversed() _testBinarySearching(in: r, with: Int(arc4random()) % 110 - 5, position: .random(), ascending: false) } } func testSorted() { var array = [1, 2, 3, 3, 4, 5] XCTAssertEqual(array.isSorted(), true) XCTAssertEqual(array.isSorted(ascending: false), false) array = [5, 4, 4, 2, 1] XCTAssertEqual(array.isSorted(), false) XCTAssertEqual(array.isSorted(ascending: false), true) array = [] XCTAssertEqual(array.isSorted(), true) XCTAssertEqual(array.isSorted(ascending: false), true) array = [1] XCTAssertEqual(array.isSorted(), true) XCTAssertEqual(array.isSorted(ascending: false), true) array = [1, 2, 1, 3, 2] XCTAssertEqual(array.isSorted(), false) XCTAssertEqual(array.isSorted(ascending: false), false) var tupleArray: [(Int, String)] = [(0, "A"), (1, "B"), (0, "B")] let comparator: ElementComparator<(Int, String)> = { (l: (Int, String), r: (Int, String)) -> ComparisonResult in if l.1 < r.1 { return .orderedAscending } else if l.1 > r.1 { return .orderedDescending } else { return .orderedSame } } XCTAssertEqual(tupleArray.isSorted(usingComparator: comparator), true) XCTAssertEqual(tupleArray.isSorted(usingComparator: reversed(comparator)), false) tupleArray = [(0, "C"), (1, "B"), (0, "A")] XCTAssertEqual(tupleArray.isSorted(usingComparator: comparator), false) XCTAssertEqual(tupleArray.isSorted(usingComparator: reversed(comparator)), true) } } extension BinarySearching.Result { var found: Index? { switch self { case .found(let idx): return idx default: return nil } } var insertion: Index? { switch self { case .notFound(insertion: let idx): return idx default: return nil } } } extension BinarySearching.EqualPosition { static func random() -> BinarySearching.EqualPosition { return self.init(rawValue: Int(arc4random()) % 3 - 1)! } }
apache-2.0
d042dab91bf4bfa3fbd10b0be814ce80
32.329897
220
0.547788
4.401634
false
true
false
false
keitin/MatsushitaSan
MatsushitaSan/Classes/MatsushitaSan.swift
1
1071
// // MatsushitaSan.swift // MatsushitaSan // // Created by 松下慶大 on 2017/03/31. // Copyright © 2017年 matsushita keita. All rights reserved. // import Foundation import UIKit public class MatsushitaSan: NSObject { public var name: String? public var firstName: String? public var familuName: String? public var age: Int? public var introduction: String? public var image: UIImage? public var work: String? public override init() { self.name = "Matsushita Keita" self.firstName = "Keita" self.familuName = "Matsushita" self.age = 23 self.introduction = "Hello I am Matsushita san." self.image = UIImage.bundledImage(named: "omoto") self.work = "Engineer" } } extension UIImage { class func bundledImage(named: String) -> UIImage? { let image = UIImage(named: named) if image == nil { return UIImage(named: named, in: Bundle(for: MatsushitaSan.classForCoder()), compatibleWith: nil) } return image } }
mit
3a1ac54bb44fc886921c668a26286b9b
24.853659
109
0.632075
3.69338
false
false
false
false
LYM-mg/DemoTest
indexView/Extesion/Inherit(继承)/TextImageView.swift
1
2473
// // TextImageView.swift // ProductionReport // // Created by i-Techsys.com on 17/2/24. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit class TextImageView: UIView { lazy var titleLabel: UILabel = { let lb = UILabel() lb.textColor = UIColor.white lb.textAlignment = .center lb.font = UIFont.boldSystemFont(ofSize: 20) return lb }() var title: String? { didSet{ titleLabel.text = title } } override func awakeFromNib() { super.awakeFromNib() self.addSubview(titleLabel) self.layoutIfNeeded() layer.cornerRadius = self.frame.size.height/2 self.clipsToBounds = true let colorArr = [UIColor(r: 200, g: 66, b: 55).withAlphaComponent(0.8), UIColor(r: 97, g: 91, b: 175).withAlphaComponent(0.8), UIColor(r: 226, g: 150, b: 46).withAlphaComponent(0.8), UIColor(r: 38, g:176, b: 124).withAlphaComponent(0.8), UIColor(r: 254, g:176, b: 38).withAlphaComponent(0.8), UIColor(r: 69, g: 105, b: 181).withAlphaComponent(0.8), UIColor(r: 22, g: 169, b: 134), UIColor(r: 130, g:152, b: 178), UIColor(r: 121, g:208, b: 249), UIColor(r: 231, g:233, b: 209)] let color = colorArr[Int(arc4random_uniform(UInt32(colorArr.count)))] self.backgroundColor = color titleLabel.backgroundColor = self.backgroundColor! } override func layoutSubviews() { super.layoutSubviews() titleLabel.frame = self.bounds } // 绘制的代码放在drawRect中去 // override func draw(_ rect: CGRect) { // let path = UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height/2) // 4.关闭路径 // color.setFill() // path.close() // path.fill() // var dict = [String: Any]() // dict[NSFontAttributeName] = 18 // dict[NSForegroundColorAttributeName] = UIColor.white // // // let str = "dsa" // let label = UILabel() // label.text = "D" // label.center = CGPoint(x: rect.size.width/2, y: rect.size.height/2) // str.draw(at: CGPoint(x: rect.size.width/2, y: rect.size.height/2), withAttributes: nil) // } }
mit
989571dd2088b825aa383fc2efe27de5
30.74026
97
0.537643
3.81875
false
false
false
false
themonki/onebusaway-iphone
OneBusAway Today/TodayViewController.swift
1
10111
// // TodayViewController.swift // OneBusAway Today // // Created by Aaron Brethorst on 10/5/17. // Copyright © 2017 OneBusAway. All rights reserved. // import UIKit import NotificationCenter import OBAKit import Fabric import Crashlytics import SnapKit let kMinutes: UInt = 60 class TodayViewController: UIViewController { let app = OBAApplication.init() let deepLinkRouter = DeepLinkRouter(baseURL: URL(string: OBAInAppDeepLinkSchemeAddress)!) var group: OBABookmarkGroup = OBABookmarkGroup.init(bookmarkGroupType: .todayWidget) var bookmarkViewsMap: [OBABookmarkV2: TodayRowView] = [:] private let outerStackView: UIStackView = TodayViewController.buildStackView() private lazy var frontMatterStack: UIStackView = { let stack = TodayViewController.buildStackView() stack.addArrangedSubview(refreshControl) stack.addArrangedSubview(errorTitleLabel) stack.addArrangedSubview(errorDescriptionLabel) return stack }() private lazy var frontMatterWrapper: UIView = { return frontMatterStack.oba_embedInWrapper() }() private let bookmarkStackView: UIStackView = TodayViewController.buildStackView() private lazy var bookmarkWrapper: UIView = { return bookmarkStackView.oba_embedInWrapper() }() private lazy var errorTitleLabel: UILabel = { let label = UILabel.oba_autolayoutNew() label.textAlignment = .center label.numberOfLines = 0 label.font = OBATheme.boldBodyFont label.text = OBAStrings.error label.isHidden = true return label }() private lazy var errorDescriptionLabel: UILabel = { let label = UILabel.oba_autolayoutNew() label.textAlignment = .center label.numberOfLines = 0 label.font = OBATheme.bodyFont label.text = OBAStrings.inexplicableErrorPleaseContactUs label.isHidden = true return label }() private lazy var refreshControl: TodayRefreshView = { let refresh = TodayRefreshView.oba_autolayoutNew() refresh.lastUpdatedAt = lastUpdatedAt refresh.addTarget(self, action: #selector(beginRefreshing), for: .touchUpInside) return refresh }() private lazy var spacerView: UIView = { let spacer = UIView.oba_autolayoutNew() spacer.setContentCompressionResistancePriority(.defaultLow, for: .vertical) return spacer }() // MARK: - Init/View Controller Lifecycle required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) Fabric.with([Crashlytics.self]) } override func viewDidLoad() { super.viewDidLoad() extensionContext?.widgetLargestAvailableDisplayMode = .expanded outerStackView.addArrangedSubview(frontMatterWrapper) outerStackView.addArrangedSubview(bookmarkWrapper) outerStackView.addArrangedSubview(spacerView) self.view.addSubview(outerStackView) outerStackView.snp.makeConstraints { (make) in let inset = UIEdgeInsets(top: OBATheme.compactPadding, left: 10, bottom: OBATheme.compactPadding, right: 10) make.leading.top.trailing.equalToSuperview().inset(inset) } let configuration = OBAApplicationConfiguration.init() configuration.extensionMode = true app.start(with: configuration) rebuildUI() } } // MARK: - UI Construction extension TodayViewController { private func rebuildUI() { group = app.modelDao.todayBookmarkGroup for v in bookmarkStackView.arrangedSubviews { bookmarkStackView.removeArrangedSubview(v) v.removeFromSuperview() } bookmarkViewsMap.removeAll() displayErrorMessagesIfAppropriate() for (idx, bm) in group.bookmarks.enumerated() { let view = viewForBookmark(bm, index: idx) bookmarkStackView.addArrangedSubview(view) bookmarkViewsMap[bm] = view } } private func viewForBookmark(_ bookmark: OBABookmarkV2, index: Int) -> TodayRowView { let v = TodayRowView.oba_autolayoutNew() v.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(TodayViewController.bookmarkTapped(sender:)))) v.bookmark = bookmark v.setContentHuggingPriority(.defaultHigh, for: .vertical) v.setContentCompressionResistancePriority(.defaultHigh, for: .vertical) let inCompactMode = extensionContext?.widgetActiveDisplayMode == .compact v.isHidden = inCompactMode && index > 1 return v } private func displayErrorMessagesIfAppropriate() { if group.bookmarks.isEmpty { showErrorMessage(title: NSLocalizedString("today_screen.no_data_title", comment: "No Bookmarks - empty data set title."), description: NSLocalizedString("today_screen.no_data_description", comment: "Add bookmarks to Today View Bookmarks to see them here. - empty data set description.")) } else if app.modelDao.currentRegion == nil { showErrorMessage(title: OBAStrings.error, description: NSLocalizedString("today_screen.no_region_description", comment: "We don't know where you're located. Please choose a region in OneBusAway.")) } else { errorTitleLabel.isHidden = true errorDescriptionLabel.isHidden = true } } private func showErrorMessage(title: String, description: String) { errorTitleLabel.isHidden = false errorDescriptionLabel.isHidden = false errorTitleLabel.text = title errorDescriptionLabel.text = description } @objc func bookmarkTapped(sender: UITapGestureRecognizer?) { guard let sender = sender, let rowView = sender.view as? TodayRowView, let bookmark = rowView.bookmark else { return } let url = deepLinkRouter.deepLinkURL(stopID: bookmark.stopId, regionID: bookmark.regionIdentifier) ?? URL.init(string: OBAInAppDeepLinkSchemeAddress)! extensionContext?.open(url, completionHandler: nil) } private static func buildStackView() -> UIStackView { let stack = UIStackView.init() stack.translatesAutoresizingMaskIntoConstraints = false stack.axis = .vertical stack.spacing = OBATheme.compactPadding return stack } } // MARK: - Widget Protocol extension TodayViewController: NCWidgetProviding { func widgetPerformUpdate(completionHandler: @escaping (NCUpdateResult) -> Void) { rebuildUI() reloadData(completionHandler) } func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) { let isCompact = activeDisplayMode == .compact for (idx, v) in bookmarkStackView.arrangedSubviews.enumerated() { v.isHidden = isCompact && idx > 1 } let frontMatterSize = self.frontMatterWrapper.systemLayoutSizeFitting(maxSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultHigh) let bookmarkSize = self.bookmarkWrapper.systemLayoutSizeFitting(maxSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultHigh) let extra = OBATheme.defaultPadding self.preferredContentSize = CGSize.init(width: frontMatterSize.width, height: frontMatterSize.height + bookmarkSize.height + extra) } } // MARK: - Refresh Control UI extension TodayViewController { @objc private func beginRefreshing() { reloadData(nil) } private func reloadData(_ completionHandler: ((NCUpdateResult) -> Void)?) { if group.bookmarks.isEmpty { completionHandler?(NCUpdateResult.noData) return } refreshControl.beginRefreshing() let promises: [Promise<Any>] = group.bookmarks.compactMap { self.promiseStop(bookmark: $0) } _ = when(resolved: promises).then { _ -> Void in self.lastUpdatedAt = Date.init() self.refreshControl.stopRefreshing() completionHandler?(NCUpdateResult.newData) } } } // MARK: - Last Updated Section extension TodayViewController { private static let lastUpdatedAtUserDefaultsKey = "lastUpdatedAtUserDefaultsKey" var lastUpdatedAt: Date? { get { guard let defaultsDate = self.app.userDefaults.value(forKey: TodayViewController.lastUpdatedAtUserDefaultsKey) else { return nil } return defaultsDate as? Date } set(val) { self.app.userDefaults.setValue(val, forKey: TodayViewController.lastUpdatedAtUserDefaultsKey) refreshControl.lastUpdatedAt = val } } } // MARK: - Data Loading extension TodayViewController { func promiseStop(bookmark: OBABookmarkV2) -> Promise<Any>? { if bookmark.bookmarkVersion == .version252 { // whole stop bookmark, and nothing to retrieve from server. return Promise.init(value: true) } return loadBookmarkedRoute(bookmark) } func loadBookmarkedRoute(_ bookmark: OBABookmarkV2) -> Promise<Any>? { guard let view = self.bookmarkViewsMap[bookmark], let modelService = app.modelService else { return Promise(value: false) } let promiseWrapper = modelService.requestStopArrivalsAndDepartures(withID: bookmark.stopId, minutesBefore: 0, minutesAfter: kMinutes) return promiseWrapper.promise.then { networkResponse -> Void in // swiftlint:disable force_cast let departures: [OBAArrivalAndDepartureV2] = bookmark.matchingArrivalsAndDepartures(forStop: networkResponse.object as! OBAArrivalsAndDeparturesForStopV2) view.departures = departures view.loadingState = .complete // swiftlint:enable force_cast }.catch { error in DDLogError("Error loading data: \(error)") }.always { view.loadingState = .complete } } }
apache-2.0
06217fe709f3ebfc432b2ff1a0c1f24e
35.366906
299
0.681306
5.116397
false
false
false
false
ahoppen/swift
test/SourceKit/CodeComplete/complete_popular_api.swift
7
4783
func test(x: Foo) { x. } func bad() {} func good() {} func okay() {} struct Foo { func bad() { } func good() { } func good(_ p1: Int, p2: Any..., p3: ()->(), p4: (Int, Int), p5: inout Int) { } func okay() {} var sad: Int var xhappy: Int var zmeh: Int } // REQUIRES: objc_interop // RUN: %sourcekitd-test -req=complete.open -pos=2:1 -req-opts=hidelowpriority=0 %s -- %s > %t.nopopular.top // RUN: %sourcekitd-test -req=complete.open -pos=3:5 %s -- %s > %t.nopopular.foo // RUN: %FileCheck %s -check-prefix=NOPOP_TOP < %t.nopopular.top // RUN: %FileCheck %s -check-prefix=NOPOP_FOO < %t.nopopular.foo // RUN: %sourcekitd-test -req=complete.setpopularapi -req-opts=popular=%s.popular,unpopular=%s.unpopular \ // RUN: == -req=complete.open -req-opts=hidelowpriority=0 -pos=2:1 %s -- %s > %t.popular.top // RUN: %sourcekitd-test -req=complete.setpopularapi -req-opts=popular=%s.popular,unpopular=%s.unpopular \ // RUN: == -req=complete.open -pos=3:5 %s -- %s > %t.popular.foo // RUN: %FileCheck %s -check-prefix=POP_TOP < %t.popular.top // RUN: %FileCheck %s -check-prefix=POP_FOO < %t.popular.foo // NOPOP_TOP: key.name: "bad() // NOPOP_TOP: key.name: "good() // NOPOP_TOP: key.name: "okay() // POP_TOP: key.name: "good() // POP_TOP: key.name: "okay() // POP_TOP: key.name: "bad() // NOPOP_FOO: key.name: "bad() // NOPOP_FOO: key.name: "good() // NOPOP_FOO: key.name: "good(:p2:p3:p4:p5:) // NOPOP_FOO: key.name: "okay() // NOPOP_FOO: key.name: "sad // NOPOP_FOO: key.name: "xhappy // NOPOP_FOO: key.name: "zmeh // POP_FOO: key.name: "good(:p2:p3:p4:p5:) // POP_FOO: key.name: "good() // POP_FOO: key.name: "xhappy // POP_FOO: key.name: "okay() // POP_FOO: key.name: "zmeh // POP_FOO: key.name: "sad // POP_FOO: key.name: "bad() // RUN: %complete-test -hide-none -fuzz -group=none -popular="%s.popular" -unpopular="%s.unpopular" -tok=POPULAR_STMT_0 %s -- -I %S/Inputs > %t.popular.stmt.0 // RUN: %FileCheck %s -check-prefix=POPULAR_STMT_0 < %t.popular.stmt.0 import PopularAPI var globalColor = 0 struct OuterNominal { var fromOuterNominalColor: Int = 0 class Super { var fromSuperColor: Int = 0 } class Derived : Super { var fromDerivedColor: Int = 0 func test(argColor: Int) { let localColor = 1 #^POPULAR_STMT_0,,col^# // POPULAR_STMT_0-LABEL: Results for filterText: [ // POPULAR_STMT_0: argColor // POPULAR_STMT_0: localColor // POPULAR_STMT_0: good() // POPULAR_STMT_0: fromDerivedColor // POPULAR_STMT_0: fromSuperColor // POPULAR_STMT_0: DDModuleColor // POPULAR_STMT_0: EEModuleColor // POPULAR_STMT_0: CCModuleColor // POPULAR_STMT_0: globalColor // POPULAR_STMT_0: okay() // POPULAR_STMT_0: ModuleCollaborate // POPULAR_STMT_0: bad() // POPULAR_STMT_0: ] // POPULAR_STMT_0-LABEL: Results for filterText: col [ // POPULAR_STMT_0: argColor // POPULAR_STMT_0: localColor // POPULAR_STMT_0: fromDerivedColor // POPULAR_STMT_0: fromSuperColor // POPULAR_STMT_0: DDModuleColor // POPULAR_STMT_0: EEModuleColor // POPULAR_STMT_0: CCModuleColor // POPULAR_STMT_0: globalColor // POPULAR_STMT_0: ModuleCollaborate // POPULAR_STMT_0: BBModuleColor // POPULAR_STMT_0: AAModuleColor // POPULAR_STMT_0: ] } } } struct Outer { struct ABTabularMonkey {} struct ABTextMockery {} struct ABTradeableEquity {} struct ABVocalContour {} struct ABBobtail {} struct ABFont {} } // RUN: %complete-test -hide-none -fuzz -group=none -popular="%s.popular" -unpopular="%s.unpopular" -tok=POPULAR_VS_PREFIX_1 %s -- -I %S/Inputs | %FileCheck %s -check-prefix=POPULAR_VS_PREFIX_1 func testPopularityVsPrefixMatch1() { let x: Outer.#^POPULAR_VS_PREFIX_1,,AB,ABT^# } // POPULAR_VS_PREFIX_1-LABEL: Results for filterText: [ // POPULAR_VS_PREFIX_1-NEXT: ABVocalContour // POPULAR_VS_PREFIX_1-NEXT: ABBobtail // POPULAR_VS_PREFIX_1-NEXT: ABFont // POPULAR_VS_PREFIX_1-NEXT: ABTabularMonkey // POPULAR_VS_PREFIX_1-NEXT: ABTextMockery // POPULAR_VS_PREFIX_1-NEXT: ABTradeableEquity // POPULAR_VS_PREFIX_1: ] // POPULAR_VS_PREFIX_1-LABEL: Results for filterText: AB [ // POPULAR_VS_PREFIX_1-NEXT: ABVocalContour // POPULAR_VS_PREFIX_1-NEXT: ABBobtail // POPULAR_VS_PREFIX_1-NEXT: ABFont // POPULAR_VS_PREFIX_1-NEXT: ABTextMockery // POPULAR_VS_PREFIX_1-NEXT: ABTabularMonkey // POPULAR_VS_PREFIX_1-NEXT: ABTradeableEquity // POPULAR_VS_PREFIX_1-NEXT: ] // POPULAR_VS_PREFIX_1-LABEL: Results for filterText: ABT [ // POPULAR_VS_PREFIX_1-NEXT: ABTextMockery // POPULAR_VS_PREFIX_1-NEXT: ABTabularMonkey // POPULAR_VS_PREFIX_1-NEXT: ABTradeableEquity // POPULAR_VS_PREFIX_1-NEXT: ABVocalContour // POPULAR_VS_PREFIX_1-NEXT: ABBobtail // POPULAR_VS_PREFIX_1-NEXT: ABFont // POPULAR_VS_PREFIX_1-NEXT: ]
apache-2.0
daa5d2e519a0a157aa35a526fde55e4a
32.215278
193
0.662346
2.629467
false
true
false
false
neonichu/PeerKit
PeerKit/PeerKit.swift
1
4494
// // PeerKit.swift // CardsAgainst // // Created by JP Simard on 11/5/14. // Copyright (c) 2014 JP Simard. All rights reserved. // import Foundation import MultipeerConnectivity // MARK: Type Aliases public typealias PeerBlock = ((myPeerID: MCPeerID, peerID: MCPeerID) -> Void) public typealias EventBlock = ((peerID: MCPeerID, event: String, object: AnyObject?) -> Void) public typealias ObjectBlock = ((peerID: MCPeerID, object: AnyObject?) -> Void) public typealias ResourceBlock = ((myPeerID: MCPeerID, resourceName: String, peer: MCPeerID, localURL: NSURL) -> Void) // MARK: Event Blocks public var onConnecting: PeerBlock? public var onConnect: PeerBlock? public var onDisconnect: PeerBlock? public var onEvent: EventBlock? public var onEventObject: ObjectBlock? public var onFinishReceivingResource: ResourceBlock? public var eventBlocks = [String: ObjectBlock]() // MARK: PeerKit Globals #if os(iOS) import UIKit public let myName = UIDevice.currentDevice().name #else public let myName = NSHost.currentHost().localizedName ?? "" #endif public var transceiver = Transceiver(displayName: myName) public var session: MCSession? // MARK: Event Handling func didConnecting(myPeerID: MCPeerID, peer: MCPeerID) { if let onConnecting = onConnecting { dispatch_async(dispatch_get_main_queue()) { onConnecting(myPeerID: myPeerID, peerID: peer) } } } func didConnect(myPeerID: MCPeerID, peer: MCPeerID) { if session == nil { session = transceiver.session.mcSession } if let onConnect = onConnect { dispatch_async(dispatch_get_main_queue()) { onConnect(myPeerID: myPeerID, peerID: peer) } } } func didDisconnect(myPeerID: MCPeerID, peer: MCPeerID) { if let onDisconnect = onDisconnect { dispatch_async(dispatch_get_main_queue()) { onDisconnect(myPeerID: myPeerID, peerID: peer) } } } func didReceiveData(data: NSData, fromPeer peer: MCPeerID) { if let dict = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [String: AnyObject], let event = dict["event"] as? String, let object: AnyObject? = dict["object"] { dispatch_async(dispatch_get_main_queue()) { if let onEvent = onEvent { onEvent(peerID: peer, event: event, object: object) } if let eventBlock = eventBlocks[event] { eventBlock(peerID: peer, object: object) } } } } func didFinishReceivingResource(myPeerID: MCPeerID, resourceName: String, fromPeer peer: MCPeerID, atURL localURL: NSURL) { if let onFinishReceivingResource = onFinishReceivingResource { dispatch_async(dispatch_get_main_queue()) { onFinishReceivingResource(myPeerID: myPeerID, resourceName: resourceName, peer: peer, localURL: localURL) } } } // MARK: Advertise/Browse public func transceive(serviceType: String, discoveryInfo: [String: String]? = nil) { transceiver.startTransceiving(serviceType: serviceType, discoveryInfo: discoveryInfo) } public func advertise(serviceType: String, discoveryInfo: [String: String]? = nil) { transceiver.startAdvertising(serviceType: serviceType, discoveryInfo: discoveryInfo) } public func browse(serviceType: String) { transceiver.startBrowsing(serviceType: serviceType) } public func stopTransceiving() { transceiver.stopTransceiving() session = nil } // MARK: Events public func sendEvent(event: String, object: AnyObject? = nil, toPeers peers: [MCPeerID]? = session?.connectedPeers) { guard let peers = peers where !peers.isEmpty else { return } var rootObject: [String: AnyObject] = ["event": event] if let object: AnyObject = object { rootObject["object"] = object } let data = NSKeyedArchiver.archivedDataWithRootObject(rootObject) do { try session?.sendData(data, toPeers: peers, withMode: .Reliable) } catch _ { } } public func sendResourceAtURL(resourceURL: NSURL, withName resourceName: String, toPeers peers: [MCPeerID]? = session?.connectedPeers, withCompletionHandler completionHandler: ((NSError?) -> Void)?) -> [NSProgress?]? { if let session = session { return peers?.map { peerID in return session.sendResourceAtURL(resourceURL, withName: resourceName, toPeer: peerID, withCompletionHandler: completionHandler) } } return nil }
mit
18fb8444ac485f031ba102a534c21332
30.208333
139
0.684468
4.405882
false
false
false
false
easyui/Alamofire
Source/Response.swift
6
21231
// // Response.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type. public typealias AFDataResponse<Success> = DataResponse<Success, AFError> /// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type. public typealias AFDownloadResponse<Success> = DownloadResponse<Success, AFError> /// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`. public struct DataResponse<Success, Failure: Error> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The final metrics of the response. /// /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.` /// public let metrics: URLSessionTaskMetrics? /// The time taken to serialize the response. public let serializationDuration: TimeInterval /// The result of response serialization. public let result: Result<Success, Failure> /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Success? { result.success } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Failure? { result.failure } /// Creates a `DataResponse` instance with the specified parameters derived from the response serialization. /// /// - Parameters: /// - request: The `URLRequest` sent to the server. /// - response: The `HTTPURLResponse` from the server. /// - data: The `Data` returned by the server. /// - metrics: The `URLSessionTaskMetrics` of the `DataRequest` or `UploadRequest`. /// - serializationDuration: The duration taken by serialization. /// - result: The `Result` of response serialization. public init(request: URLRequest?, response: HTTPURLResponse?, data: Data?, metrics: URLSessionTaskMetrics?, serializationDuration: TimeInterval, result: Result<Success, Failure>) { self.request = request self.response = response self.data = data self.metrics = metrics self.serializationDuration = serializationDuration self.result = result } } // MARK: - extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { "\(result)" } /// The debug textual representation used when written to an output stream, which includes (if available) a summary /// of the `URLRequest`, the request's headers and body (if decodable as a `String` below 100KB); the /// `HTTPURLResponse`'s status code, headers, and body; the duration of the network and serialization actions; and /// the `Result` of serialization. public var debugDescription: String { guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" } let requestDescription = DebugDescription.description(of: urlRequest) let responseDescription = response.map { response in let responseBodyDescription = DebugDescription.description(for: data, headers: response.headers) return """ \(DebugDescription.description(of: response)) \(responseBodyDescription.indentingNewlines()) """ } ?? "[Response]: None" let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" return """ \(requestDescription) \(responseDescription) [Network Duration]: \(networkDuration) [Serialization Duration]: \(serializationDuration)s [Result]: \(result) """ } } // MARK: - extension DataResponse { /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleInt = possibleData.map { $0.count } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's /// result is a failure, returns a response wrapping the same failure. public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DataResponse<NewSuccess, Failure> { DataResponse<NewSuccess, Failure>(request: request, response: response, data: data, metrics: metrics, serializationDuration: serializationDuration, result: result.map(transform)) } /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result /// value as a parameter. /// /// Use the `tryMap` method with a closure that may throw an error. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleObject = possibleData.tryMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's /// result is a failure, returns the same failure. public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DataResponse<NewSuccess, Error> { DataResponse<NewSuccess, Error>(request: request, response: response, data: data, metrics: metrics, serializationDuration: serializationDuration, result: result.tryMap(transform)) } /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. /// /// Use the `mapError` function with a closure that does not throw. For example: /// /// let possibleData: DataResponse<Data> = ... /// let withMyError = possibleData.mapError { MyError.error($0) } /// /// - Parameter transform: A closure that takes the error of the instance. /// /// - Returns: A `DataResponse` instance containing the result of the transform. public func mapError<NewFailure: Error>(_ transform: (Failure) -> NewFailure) -> DataResponse<Success, NewFailure> { DataResponse<Success, NewFailure>(request: request, response: response, data: data, metrics: metrics, serializationDuration: serializationDuration, result: result.mapError(transform)) } /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. /// /// Use the `tryMapError` function with a closure that may throw an error. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleObject = possibleData.tryMapError { /// try someFailableFunction(taking: $0) /// } /// /// - Parameter transform: A throwing closure that takes the error of the instance. /// /// - Returns: A `DataResponse` instance containing the result of the transform. public func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> DataResponse<Success, Error> { DataResponse<Success, Error>(request: request, response: response, data: data, metrics: metrics, serializationDuration: serializationDuration, result: result.tryMapError(transform)) } } // MARK: - /// Used to store all data associated with a serialized response of a download request. public struct DownloadResponse<Success, Failure: Error> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The final destination URL of the data returned from the server after it is moved. public let fileURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The final metrics of the response. /// /// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.` /// public let metrics: URLSessionTaskMetrics? /// The time taken to serialize the response. public let serializationDuration: TimeInterval /// The result of response serialization. public let result: Result<Success, Failure> /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Success? { result.success } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Failure? { result.failure } /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. /// /// - Parameters: /// - request: The `URLRequest` sent to the server. /// - response: The `HTTPURLResponse` from the server. /// - temporaryURL: The temporary destination `URL` of the data returned from the server. /// - destinationURL: The final destination `URL` of the data returned from the server, if it was moved. /// - resumeData: The resume `Data` generated if the request was cancelled. /// - metrics: The `URLSessionTaskMetrics` of the `DownloadRequest`. /// - serializationDuration: The duration taken by serialization. /// - result: The `Result` of response serialization. public init(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, resumeData: Data?, metrics: URLSessionTaskMetrics?, serializationDuration: TimeInterval, result: Result<Success, Failure>) { self.request = request self.response = response self.fileURL = fileURL self.resumeData = resumeData self.metrics = metrics self.serializationDuration = serializationDuration self.result = result } } // MARK: - extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { "\(result)" } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the temporary and destination URLs, the resume data, the durations of the network and serialization /// actions, and the response serialization result. public var debugDescription: String { guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" } let requestDescription = DebugDescription.description(of: urlRequest) let responseDescription = response.map(DebugDescription.description(of:)) ?? "[Response]: None" let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None" let resumeDataDescription = resumeData.map { "\($0)" } ?? "None" return """ \(requestDescription) \(responseDescription) [File URL]: \(fileURL?.path ?? "None") [Resume Data]: \(resumeDataDescription) [Network Duration]: \(networkDuration) [Serialization Duration]: \(serializationDuration)s [Result]: \(result) """ } } // MARK: - extension DownloadResponse { /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let possibleInt = possibleData.map { $0.count } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's /// result is a failure, returns a response wrapping the same failure. public func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> DownloadResponse<NewSuccess, Failure> { DownloadResponse<NewSuccess, Failure>(request: request, response: response, fileURL: fileURL, resumeData: resumeData, metrics: metrics, serializationDuration: serializationDuration, result: result.map(transform)) } /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `tryMap` method with a closure that may throw an error. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let possibleObject = possibleData.tryMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this /// instance's result is a failure, returns the same failure. public func tryMap<NewSuccess>(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse<NewSuccess, Error> { DownloadResponse<NewSuccess, Error>(request: request, response: response, fileURL: fileURL, resumeData: resumeData, metrics: metrics, serializationDuration: serializationDuration, result: result.tryMap(transform)) } /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. /// /// Use the `mapError` function with a closure that does not throw. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let withMyError = possibleData.mapError { MyError.error($0) } /// /// - Parameter transform: A closure that takes the error of the instance. /// /// - Returns: A `DownloadResponse` instance containing the result of the transform. public func mapError<NewFailure: Error>(_ transform: (Failure) -> NewFailure) -> DownloadResponse<Success, NewFailure> { DownloadResponse<Success, NewFailure>(request: request, response: response, fileURL: fileURL, resumeData: resumeData, metrics: metrics, serializationDuration: serializationDuration, result: result.mapError(transform)) } /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. /// /// Use the `tryMapError` function with a closure that may throw an error. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let possibleObject = possibleData.tryMapError { /// try someFailableFunction(taking: $0) /// } /// /// - Parameter transform: A throwing closure that takes the error of the instance. /// /// - Returns: A `DownloadResponse` instance containing the result of the transform. public func tryMapError<NewFailure: Error>(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse<Success, Error> { DownloadResponse<Success, Error>(request: request, response: response, fileURL: fileURL, resumeData: resumeData, metrics: metrics, serializationDuration: serializationDuration, result: result.tryMapError(transform)) } } private enum DebugDescription { static func description(of request: URLRequest) -> String { let requestSummary = "\(request.httpMethod!) \(request)" let requestHeadersDescription = DebugDescription.description(for: request.headers) let requestBodyDescription = DebugDescription.description(for: request.httpBody, headers: request.headers) return """ [Request]: \(requestSummary) \(requestHeadersDescription.indentingNewlines()) \(requestBodyDescription.indentingNewlines()) """ } static func description(of response: HTTPURLResponse) -> String { """ [Response]: [Status Code]: \(response.statusCode) \(DebugDescription.description(for: response.headers).indentingNewlines()) """ } static func description(for headers: HTTPHeaders) -> String { guard !headers.isEmpty else { return "[Headers]: None" } let headerDescription = "\(headers.sorted())".indentingNewlines() return """ [Headers]: \(headerDescription) """ } static func description(for data: Data?, headers: HTTPHeaders, allowingPrintableTypes printableTypes: [String] = ["json", "xml", "text"], maximumLength: Int = 100_000) -> String { guard let data = data, !data.isEmpty else { return "[Body]: None" } guard data.count <= maximumLength, printableTypes.compactMap({ headers["Content-Type"]?.contains($0) }).contains(true) else { return "[Body]: \(data.count) bytes" } return """ [Body]: \(String(decoding: data, as: UTF8.self) .trimmingCharacters(in: .whitespacesAndNewlines) .indentingNewlines()) """ } } extension String { fileprivate func indentingNewlines(by spaceCount: Int = 4) -> String { let spaces = String(repeating: " ", count: spaceCount) return replacingOccurrences(of: "\n", with: "\n\(spaces)") } }
mit
8193ca542f7d0c1b7a6e6f98998834d2
45.764317
129
0.608167
5.347859
false
false
false
false
oskarpearson/rileylink_ios
NightscoutUploadKit/Treatments/MealBolusNightscoutTreatment.swift
1
1478
// // MealBolusNightscoutTreatment.swift // RileyLink // // Created by Pete Schwamb on 3/10/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public class MealBolusNightscoutTreatment: NightscoutTreatment { let carbs: Int let absorptionTime: TimeInterval? let insulin: Double? let glucose: Int? let units: Units? // of glucose entry let glucoseType: GlucoseType? public init(timestamp: Date, enteredBy: String, id: String?, carbs: Int, absorptionTime: TimeInterval? = nil, insulin: Double? = nil, glucose: Int? = nil, glucoseType: GlucoseType? = nil, units: Units? = nil) { self.carbs = carbs self.absorptionTime = absorptionTime self.glucose = glucose self.glucoseType = glucoseType self.units = units self.insulin = insulin super.init(timestamp: timestamp, enteredBy: enteredBy, id: id) } override public var dictionaryRepresentation: [String: Any] { var rval = super.dictionaryRepresentation rval["eventType"] = "Meal Bolus" rval["carbs"] = carbs if let absorptionTime = absorptionTime { rval["absorptionTime"] = absorptionTime.minutes } rval["insulin"] = insulin if let glucose = glucose { rval["glucose"] = glucose rval["glucoseType"] = glucoseType?.rawValue rval["units"] = units?.rawValue } return rval } }
mit
fed8a8abbb9a0a20b9c2bbc8e3b37ad6
31.822222
214
0.637102
4.51682
false
false
false
false
stefanilie/swift-playground
Swift3 and iOS10/Playgrounds/Numbers.playground/Contents.swift
1
399
//: Playground - noun: a place where people can play import UIKit //Type Inference var age = 30 //Explicity declared type var weight: Int = 200 //Int var milesRan = 56.45 //Arithmetic Operators //+ - / * var area = 15*20 var sum = 5+6 var diff = 10-3 var div1 = 12 / 3 var div2 = 13 / 5 var remainder = 13 % 5 var result = "The result of 13/5 is \(div1) with a remainder of \(remainder)"
mit
6bc9da53d3b182568ed0a48d606e4312
13.777778
77
0.654135
2.933824
false
false
false
false
nodes-ios/Codemine
Codemine/Extensions/String+Range.swift
1
2089
// // String+Range.swift // Codemine // // Created by Marius Constantinescu on 18/02/16. // Copyright © 2016 Nodes. All rights reserved. // import Foundation public extension String { /** Checks if a range appears in a String. - parameter range: the range that is checked - returns: true if the string contains that range, false otherwise */ private func contains(_ range: Range<Index>) -> Bool { if range.lowerBound < self.startIndex || range.upperBound > self.endIndex { return false } return true } enum RangeSearchType: Int { case leftToRight case rightToLeft case broadest case narrowest } /** Returns the range between two substrings, including the 2 substrings. - parameter string: first substring - parameter toString: second substring - parameter searchType: direction of search - parameter inRange: the range of the string in which the search is performed. If nil, it will be done in the whole string. - returns: the range between the start of the first substring and the end of the last substring */ func range(from fromString: String, toString: String, searchType: RangeSearchType = .leftToRight, inRange: Range<Index>? = nil) -> Range<Index>? { let range = inRange ?? Range(uncheckedBounds: (lower: self.startIndex, upper: self.endIndex)) if !contains(range) { return nil } guard let firstRange = self.range(of: fromString, options: NSString.CompareOptions(rawValue: 0), range: range, locale: nil) else { return nil } guard let secondRange = self.range(of: toString, options: NSString.CompareOptions(rawValue: 0), range: range, locale: nil) else { return nil } switch searchType { case .leftToRight: return firstRange.lowerBound..<secondRange.upperBound default: print("Other search options not yet implemented.") } return nil } }
mit
7ef5a3b1b2161cf81a829d92eeabe563
32.677419
151
0.635057
4.745455
false
false
false
false
u10int/Kinetic
Example/Tests/PathTests.swift
1
1348
// // PathTests.swift // Kinetic // // Created by Nicholas Shipes on 7/30/17. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest import Nimble import Kinetic class PathTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testLinearPathTween() { let view = UIView(frame: CGRect(x: 0, y: 0, width: 50.0, height: 50.0)) let path = Line(start: CGPoint(x: 20.0, y: 20.0), end: CGPoint(x: 200.0, y: 200.0)) var completeTriggered = false let tween = Tween(target: view).along(path).duration(2.0).ease(Cubic.easeInOut) tween.on(.updated) { (tween) in print(view.center) }.on(.completed) { (tween) in print(view.center) completeTriggered = true } expect(tween.duration).to(equal(2.0)) expect(tween.time).to(equal(0)) tween.play() // tween.progress = 0.5 // expect(tween.time).to(equal(1.0)) // expect(view.frame.size).to(equal(CGSize(width: 75.0, height: 75.0))) expect(completeTriggered).toEventually(beTrue(), timeout: 2.5) } }
mit
21c596178e80d0023c762f7463573ea3
24.903846
111
0.640683
3.269417
false
true
false
false
FirstPersonSF/FPKit
FPKit/FPKit/FPLazyImageView.swift
1
3595
// // FPLazyImageView.swift // FPKit // // Created by Fernando Toledo on 1/21/16. // Copyright © 2016 First Person. All rights reserved. // import Foundation import UIKit public class FPLazyImageView: UIImageView { //MARK:- Private Properties private var sessionTask: NSURLSessionTask? = nil //MARK: Public Properties // read only public private(set) var downloading: Bool = false public private(set) var downloaded: Bool = false // read & write public var imageURL: NSURL? { didSet { if self.imageURL != oldValue { if self.downloading { self.cancelDownload() } self.image = self.placeholderImage self.downloaded = false } } } public var placeholderImage:UIImage? { didSet { if !self.downloaded { self.image = self.placeholderImage } } } public var animatedTransition: Bool = true public var transitionDuration:CFTimeInterval = 0.25 public var completionHandler: (imageView: FPLazyImageView, result: FPLazyImageResult) -> Void = { _ in } //MARK:- View Lifecycle required public init?(coder aDecoder: NSCoder) { self.placeholderImage = nil self.imageURL = nil super.init(coder: aDecoder) } public init(imageURL: NSURL, placeholderImage: UIImage?) { self.imageURL = imageURL self.placeholderImage = placeholderImage super.init(image: placeholderImage) } //MARK:- Network Support public func startDownload() { if self.imageURL == nil { return; } if self.downloading { self.cancelDownload() } // setup network request let request = NSURLRequest(URL: self.imageURL!) self.sessionTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in self.downloading = false if let data = data, image = UIImage(data: data) { NSOperationQueue.mainQueue().addOperationWithBlock({ if self.animatedTransition { let transition = CATransition() transition.duration = self.transitionDuration transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) transition.type = kCATransitionFade self.layer .addAnimation(transition, forKey: nil) } self.image = image self.downloaded = true let result = FPLazyImageResult.Success(data: data, response: response, error: error) self.completionHandler(imageView: self, result: result) }) } else { let result = FPLazyImageResult.Failure(data: data, response: response, error: error) self.completionHandler(imageView: self, result: result) } }) self.sessionTask?.resume() self.downloading = true } public func cancelDownload() { if self.downloading { if let sessionTask = self.sessionTask { sessionTask.cancel() self.sessionTask = nil self.downloading = false } } } }
mit
70fc5d8ce186b1ac97be02b3be9f249c
29.991379
110
0.55064
5.580745
false
false
false
false
Nihility-Ming/MVVM_ARC_Demo
Demo_02/Demo_02/ProductModel.swift
1
1185
// // ProductModel.swift // Demo_02 // // Created by 伟明 毕 on 15/7/15. // Copyright (c) 2015年 Bi Weiming. All rights reserved. // import UIKit class ProductModel: NSObject { var productID:String? // 产品ID var imageURL:String? // 产品图片 var productName:String? // 产品名称 var size:String? // 规格 var storeCount:NSInteger? // 库存数量 var stockPrice:Double? // 优惠价格 var marketPrice:Double? // 市场价格 var saleNum:NSInteger? // 销售数 var startSaleDate:String? // 开始销售的时间 init(dict:NSDictionary) { self.productID = dict["id"] as? String self.imageURL = dict["mainImgUrl"] as? String self.productName = dict["productName"] as? String self.size = dict["_size"] as? String self.storeCount = dict["_number"]?.integerValue self.stockPrice = dict["_finalPrice"]?.doubleValue self.marketPrice = dict["_marketPrice"]?.doubleValue self.saleNum = dict["saleNum"]?.integerValue self.startSaleDate = dict["onSaleDate"] as? String super.init() } }
mit
96b30e9611b8db1bdd0f2aad725e4013
28.184211
60
0.600541
3.636066
false
false
false
false
crewshin/GasLog
Pods/Material/Sources/MaterialKeyframeAnimation.swift
2
2563
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit public typealias MaterialAnimationRotationModeType = String public enum MaterialAnimationRotationMode { case None case Auto case AutoReverse } /** :name: MaterialAnimationRotationModeToValue */ public func MaterialAnimationRotationModeToValue(mode: MaterialAnimationRotationMode) -> MaterialAnimationRotationModeType? { switch mode { case .None: return nil case .Auto: return kCAAnimationRotateAuto case .AutoReverse: return kCAAnimationRotateAutoReverse } } public extension MaterialAnimation { /** :name: path */ public static func path(bezierPath: UIBezierPath, mode: MaterialAnimationRotationMode = .Auto, duration: CFTimeInterval? = nil) -> CAKeyframeAnimation { let animation: CAKeyframeAnimation = CAKeyframeAnimation() animation.keyPath = "position" animation.path = bezierPath.CGPath animation.rotationMode = MaterialAnimationRotationModeToValue(mode) if let d = duration { animation.duration = d } return animation } }
mit
52cbcc8ba90aae47177ecd71acc0cddb
36.15942
153
0.783847
4.329392
false
false
false
false
carabina/SYNQueue
SYNQueue/SYNQueue/SYNQueue.swift
1
6084
// // SYNQueue.swift // SYNQueue // // Created by John Hurliman on 6/18/15. // Copyright (c) 2015 Syntertainment. All rights reserved. // import Foundation /** Log level for use in the SYNQueueLogProvider `log()` call - Trace: "Trace" - Debug: "Debug" - Info: "Info" - Warning: "Warning" - Error: "Error" */ @objc public enum LogLevel: Int { case Trace = 0 case Debug = 1 case Info = 2 case Warning = 3 case Error = 4 public func toString() -> String { switch (self) { case .Trace: return "Trace" case .Debug: return "Debug" case .Info: return "Info" case .Warning: return "Warning" case .Error: return "Error" } } } /** * Conform to this protocol to provide logging to SYNQueue */ @objc public protocol SYNQueueLogProvider { func log(level: LogLevel, _ msg: String) } /** * Conform to this protocol to provide serialization (persistence) to SYNQueue */ @objc public protocol SYNQueueSerializationProvider { func serializeTask(task: SYNQueueTask, queueName: String) func deserializeTasksInQueue(queue: SYNQueue) -> [SYNQueueTask] func removeTask(taskID: String, queue: SYNQueue) } /** * SYNQueue is a generic queue with customizable serialization, logging, task handling, retries, and concurrency behavior */ @objc public class SYNQueue : NSOperationQueue { /// The maximum number of times a task will be retried if it fails public let maxRetries: Int let serializationProvider: SYNQueueSerializationProvider? let logProvider: SYNQueueLogProvider? var tasksMap = [String: SYNQueueTask]() var taskHandlers = [String: SYNTaskCallback]() let completionBlock: SYNTaskCompleteCallback? public var tasks: [SYNQueueTask] { let array = operations var output = [SYNQueueTask]() output.reserveCapacity(array.count) for obj in array { if let cast = obj as? SYNQueueTask { output.append(cast) } } return output } /** Initializes a SYNQueue with the provided options - parameter queueName: The name of the queue - parameter maxConcurrency: The maximum number of tasks to run in parallel - parameter maxRetries: The maximum times a task will be retried if it fails - parameter logProvider: An optional logger, nothing will be logged if this is nil - parameter serializationProvider: An optional serializer, there will be no serialzation (persistence) if nil - parameter completionBlock: The closure to call when a task finishes - returns: A new SYNQueue */ public required init(queueName: String, maxConcurrency: Int = 1, maxRetries: Int = 5, logProvider: SYNQueueLogProvider? = nil, serializationProvider: SYNQueueSerializationProvider? = nil, completionBlock: SYNTaskCompleteCallback? = nil) { self.maxRetries = maxRetries self.logProvider = logProvider self.serializationProvider = serializationProvider self.completionBlock = completionBlock super.init() self.name = queueName self.maxConcurrentOperationCount = maxConcurrency } /** Add a handler for a task type - parameter taskType: The task type for the handler - parameter taskHandler: The handler for this particular task type, must be generic for the task type */ public func addTaskHandler(taskType: String, taskHandler:SYNTaskCallback) { taskHandlers[taskType] = taskHandler } /** Deserializes tasks that were serialized (persisted) */ public func loadSerializedTasks() { if let sp = serializationProvider { let tasks = sp.deserializeTasksInQueue(self) for task in tasks { task.setupDependencies(tasks) addDeserializedTask(task) } } } public func getTask(taskID: String) -> SYNQueueTask? { return tasksMap[taskID] } /** Adds a SYNQueueTask to the queue and serializes it - parameter op: A SYNQueueTask to execute on the queue */ override public func addOperation(op: NSOperation) { if let task = op as? SYNQueueTask { if tasksMap[task.taskID] != nil { log(.Warning, "Attempted to add duplicate task \(task.taskID)") return } tasksMap[task.taskID] = task // Serialize this operation if let sp = serializationProvider, let queueName = task.queue.name { sp.serializeTask(task, queueName: queueName) } } op.completionBlock = { self.taskComplete(op) } super.addOperation(op) } func addDeserializedTask(task: SYNQueueTask) { if tasksMap[task.taskID] != nil { log(.Warning, "Attempted to add duplicate deserialized task \(task.taskID)") return } task.completionBlock = { self.taskComplete(task) } super.addOperation(task) } func runTask(task: SYNQueueTask) { if let handler = taskHandlers[task.taskType] { handler(task) } else { log(.Warning, "No handler registered for task \(task.taskID)") task.cancel() } } func taskComplete(op: NSOperation) { if let task = op as? SYNQueueTask { tasksMap.removeValueForKey(task.taskID) if let handler = completionBlock { handler(task.lastError, task) } // Remove this operation from serialization if let sp = serializationProvider { sp.removeTask(task.taskID, queue: task.queue) } } } func log(level: LogLevel, _ msg: String) { logProvider?.log(level, msg) } }
mit
2ac2586fd63527d45c6b66020f2eff14
29.268657
121
0.608974
4.584778
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift
6
2945
// // UIControl+Rx.swift // RxCocoa // // Created by Daniel Tartaglia on 5/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation #if !RX_NO_MODULE import RxSwift #endif import UIKit extension Reactive where Base: UIControl { /** Bindable sink for `enabled` property. */ public var enabled: AnyObserver<Bool> { return UIBindingObserver(UIElement: self.base) { control, value in control.isEnabled = value }.asObserver() } /** Bindable sink for `selected` property. */ public var selected: AnyObserver<Bool> { return UIBindingObserver(UIElement: self.base) { control, selected in control.isSelected = selected }.asObserver() } /** Reactive wrapper for target action pattern. - parameter controlEvents: Filter for observed event types. */ public func controlEvent(_ controlEvents: UIControlEvents) -> ControlEvent<Void> { let source: Observable<Void> = Observable.create { [weak control = self.base] observer in MainScheduler.ensureExecutingOnScheduler() guard let control = control else { observer.on(.completed) return Disposables.create() } let controlTarget = ControlTarget(control: control, controlEvents: controlEvents) { control in observer.on(.next()) } return Disposables.create(with: controlTarget.dispose) }.takeUntil(deallocated) return ControlEvent(events: source) } /** You might be wondering why the ugly `as!` casts etc, well, for some reason if Swift compiler knows C is UIControl type and optimizations are turned on, it will crash. */ static func value<C: NSObject, T: Equatable>(_ control: C, getter: @escaping (C) -> T, setter: @escaping (C, T) -> Void) -> ControlProperty<T> { let source: Observable<T> = Observable.create { [weak weakControl = control] observer in guard let control = weakControl else { observer.on(.completed) return Disposables.create() } observer.on(.next(getter(control))) let controlTarget = ControlTarget(control: control as! UIControl, controlEvents: [.allEditingEvents, .valueChanged]) { _ in if let control = weakControl { observer.on(.next(getter(control))) } } return Disposables.create(with: controlTarget.dispose) } .takeUntil((control as NSObject).rx.deallocated) let bindingObserver = UIBindingObserver(UIElement: control, binding: setter) return ControlProperty<T>(values: source, valueSink: bindingObserver) } } #endif
mit
5ee6184f9d7e46563657b367e9b90985
31
148
0.601563
4.964587
false
false
false
false
merlos/iOS-Open-GPX-Tracker
Pods/CoreGPX/Classes/GPXPerson.swift
1
1860
// // GPXPerson.swift // GPXKit // // Created by Vincent on 18/11/18. // import Foundation /// A value type that is designated to hold information regarding the person or organisation who has created the GPX file. public class GPXPerson: GPXElement, Codable { /// Name of person who has created the GPX file. public var name: String? /// The email address of the person who has created the GPX file. public var email: GPXEmail? /// An external website that holds information on the person who has created the GPX file. Additional information may be supported as well. public var link: GPXLink? // MARK:- Initializers // Default Initializer. public required init() { super.init() } /// Inits native element from raw parser value /// /// - Parameters: /// - raw: Raw element expected from parser init(raw: GPXRawElement) { for child in raw.children { switch child.name { case "name": self.name = child.text case "email": self.email = GPXEmail(raw: child) case "link": self.link = GPXLink(raw: child) default: continue } } } // MARK:- Tag override func tagName() -> String { return "person" } // MARK:- GPX override func addChildTag(toGPX gpx: NSMutableString, indentationLevel: Int) { super.addChildTag(toGPX: gpx, indentationLevel: indentationLevel) self.addProperty(forValue: name, gpx: gpx, tagName: "name", indentationLevel: indentationLevel) if email != nil { self.email?.gpx(gpx, indentationLevel: indentationLevel) } if link != nil { self.link?.gpx(gpx, indentationLevel: indentationLevel) } } }
gpl-3.0
b23be9d49ba35d3b7e70a6271c78bb51
27.181818
143
0.597312
4.638404
false
false
false
false
KeisukeSoma/RSSreader
RSSReader/View3.swift
1
3105
// // View3.swift // RSSReader // // Created by mikilab on 2015/06/19. // import UIKit class View3: UITableViewController, MWFeedParserDelegate { var items = [MWFeedItem]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) request() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func request() { let URL = NSURL(string: "http://news.livedoor.com/topics/rss/dom.xml") let feedParser = MWFeedParser(feedURL: URL); feedParser.delegate = self feedParser.parse() } func feedParserDidStart(parser: MWFeedParser) { SVProgressHUD.show() self.items = [MWFeedItem]() } func feedParserDidFinish(parser: MWFeedParser) { SVProgressHUD.dismiss() self.tableView.reloadData() } func feedParser(parser: MWFeedParser, didParseFeedInfo info: MWFeedInfo) { print(info) self.title = info.title } func feedParser(parser: MWFeedParser, didParseFeedItem item: MWFeedItem) { print(item) self.items.append(item) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100 } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "FeedCell") self.configureCell(cell, atIndexPath: indexPath) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let item = self.items[indexPath.row] as MWFeedItem let con = KINWebBrowserViewController() let URL = NSURL(string: item.link) con.loadURL(URL) self.navigationController?.pushViewController(con, animated: true) } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let item = self.items[indexPath.row] as MWFeedItem cell.textLabel?.text = item.title cell.textLabel?.font = UIFont.systemFontOfSize(14.0) cell.textLabel?.numberOfLines = 0 let projectURL = item.link.componentsSeparatedByString("?")[0] let imgURL: NSURL? = NSURL(string: projectURL + "/cover_image?style=200x200#") cell.imageView?.contentMode = UIViewContentMode.ScaleAspectFit // cell.imageView?.setImageWithURL(imgURL, placeholderImage: UIImage(named: "logo.png")) } }
mit
f9455ce98d09eb4a04f12332c6141de4
31.34375
118
0.657005
4.960064
false
false
false
false
stolycizmus/WowToken
WowToken/DataHandler.swift
1
7674
// // DataHandler.swift // WowToken // // Created by Kadasi Mate on 2015. 11. 20.. // Copyright © 2015. Tairpake Inc. All rights reserved. // import UIKit import CoreData var urlSessionObject = URLSession() var lastUpdated = userDefaults.value(forKey: "lastUpdated") as! Int var firstRun = userDefaults.value(forKey: "firstRun") as! Bool var userDefaults = AppDelegate.sharedAppDelegate.userDefaults var jsonIsNotNil = true let managedObjectContext = AppDelegate.sharedAppDelegate.managedObjectContext var currentRawPrice = 0 //MARK: - Data pull func parsingData(_ json: JSON){ //check whether swiftyJSON can handle the pulled JSON if json != nil { //handle JSON data handleData(json) }else { // handle error jsonIsNotNil = false } } func handleData(_ json: JSON){ let prefferedRegion = userDefaults.value(forKey: "prefferedRegion") as! String let updateData = json["update"][prefferedRegion].dictionaryObject! let rawData = updateData["raw"] as! [String: AnyObject] let formattedData = updateData["formatted"] as! [String: AnyObject] //Firts run if firstRun { let entity = NSEntityDescription.entity(forEntityName: "Regions", in: managedObjectContext) let region = Regions(entity: entity!, insertInto: managedObjectContext) let regionData = ["NA": "North American Realms", "EU": "European Realms", "CN": "Chinese Realms", "TW": "Taiwanese Realms", "KR": "Korean Realms"] region.shortName = prefferedRegion region.fullName = regionData[prefferedRegion] let update = Update(entity: NSEntityDescription.entity(forEntityName: "Update", in: managedObjectContext)!, insertInto: managedObjectContext) update.timestamp = updateData["timestamp"] as? NSNumber update.region = region let raw = Raw(entity: NSEntityDescription.entity(forEntityName: "Raw", in: managedObjectContext)!, insertInto: managedObjectContext) raw.buy = rawData["buy"] as! NSNumber? currentRawPrice = raw.buy as! Int raw.min24 = rawData["24min"] as! NSNumber? raw.max24 = rawData["24max"] as! NSNumber? raw.updatedOn = rawData["updated"] as! NSNumber? raw.update = update let formatted = Formatted(entity: NSEntityDescription.entity(forEntityName: "Formatted", in: managedObjectContext)!, insertInto: managedObjectContext) formatted.buy = formattedData["buy"] as? String formatted.min24 = formattedData["24min"] as? String formatted.max24 = formattedData["24max"] as? String formatted.timeToSell = formattedData["tomeToSell"] as? String formatted.updatedOn = formattedData["updated"] as? String formatted.update = update let historyData = json["history"][prefferedRegion].arrayValue for history in historyData { let _history = History(entity: NSEntityDescription.entity(forEntityName: "History", in: managedObjectContext)!, insertInto: managedObjectContext) _history.gold = history[1].intValue as NSNumber _history.time = history[0].intValue as NSNumber _history.region = region } } //Not first run if !firstRun { //update raw section let fetchRequestRaw = NSFetchRequest<Raw>(entityName: "Raw") fetchRequestRaw.predicate = NSPredicate(format: "update.region.shortName == %@", prefferedRegion) do { if let raws = try managedObjectContext.fetch(fetchRequestRaw) as? [Raw]{ for raw in raws { raw.buy = rawData["buy"] as! NSNumber currentRawPrice = raw.buy as! Int raw.min24 = rawData["24min"] as! NSNumber raw.max24 = rawData["24max"] as! NSNumber raw.updatedOn = rawData["updated"] as! NSNumber } } } catch {} //update formatted section let fetchRequestFormatted = NSFetchRequest<Formatted>(entityName: "Formatted") fetchRequestFormatted.predicate = NSPredicate(format: "update.region.shortName == %@", prefferedRegion) do { if let formatteds = try managedObjectContext.fetch(fetchRequestFormatted) as? [Formatted]{ for formatted in formatteds { formatted.buy = formattedData["buy"] as? String formatted.min24 = formattedData["24min"] as? String formatted.max24 = formattedData["24max"] as? String formatted.timeToSell = formattedData["tomeToSell"] as? String formatted.updatedOn = formattedData["updated"] as? String } } } catch {} //update update section let fetchRequestUpdate = NSFetchRequest<Update>(entityName: "Update") fetchRequestUpdate.predicate = NSPredicate(format: "region.shortName == %@", prefferedRegion) do { if let updates = try managedObjectContext.fetch(fetchRequestUpdate) as? [Update]{ for update in updates { update.timestamp = updateData["timestamp"] as? NSNumber } } }catch {} //update history section let fetchRequestRegions = NSFetchRequest<Regions>(entityName: "Regions") fetchRequestRegions.predicate = NSPredicate(format: "shortName == %@", prefferedRegion) var region: Regions? do { let result = try managedObjectContext.fetch(fetchRequestRegions) try region = result[0] } catch {} let fetchRequestHistory = NSFetchRequest<History>(entityName: "History") fetchRequestHistory.predicate = NSPredicate(format: "region.shortName == %@", prefferedRegion) fetchRequestHistory.sortDescriptors = [NSSortDescriptor(key: "time", ascending: false)] fetchRequestHistory.fetchLimit = 1 do { if let latestHistory = try managedObjectContext.fetch(fetchRequestHistory) as? [History]{ let jsonHistory = json["history"][prefferedRegion].arrayObject as! [NSArray] for arrays in jsonHistory { if arrays[0] as! NSNumber > latestHistory[0].time! { let entity = NSEntityDescription.entity(forEntityName: "History", in: managedObjectContext) let history = History(entity: entity!, insertInto: managedObjectContext) history.time = arrays[0] as? NSNumber history.gold = arrays[1] as? NSNumber history.region = region } } } } catch {} } //set firstrun to false if firstRun { userDefaults.set(false, forKey: "firstRun") } userDefaults.setValue(Date(timeIntervalSinceNow: 0).timeIntervalSince1970, forKey: "lastUpdated") userDefaults.synchronize() //save all change AppDelegate.sharedAppDelegate.saveContext() }
gpl-3.0
66993f1ec6e73d7472ee270214f0df48
48.185897
162
0.583214
5.335883
false
false
false
false