repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
prey/prey-ios-client
refs/heads/master
Prey/Classes/QRCodeScannerVC.swift
gpl-3.0
1
// // QRCodeScannerVC.swift // Prey // // Created by Javier Cala Uribe on 19/07/16. // Copyright © 2016 Prey, Inc. All rights reserved. // import Foundation import AVFoundation import UIKit class QRCodeScannerVC: UIViewController, AVCaptureMetadataOutputObjectsDelegate { // MARK: Properties let device : AVCaptureDevice! = AVCaptureDevice.default(for: AVMediaType.video) let session : AVCaptureSession = AVCaptureSession() let output : AVCaptureMetadataOutput = AVCaptureMetadataOutput() var preview : AVCaptureVideoPreviewLayer! // MARK: Init override func viewDidLoad() { super.viewDidLoad() // View title for GAnalytics //self.screenName = "QRCodeScanner" // Set background color self.view.backgroundColor = UIColor.black // Config navigationBar let widthScreen = UIScreen.main.bounds.size.width let navBar = UINavigationBar(frame:CGRect(x: 0,y: 0,width: widthScreen,height: 44)) navBar.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin] self.view.addSubview(navBar) // Config navItem let navItem = UINavigationItem(title:"Prey Control Panel".localized) navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem:.cancel, target:self, action:#selector(cancel)) navBar.pushItem(navItem, animated:false) // Check camera available guard isCameraAvailable() else { displayErrorAlert("Couldn't add your device".localized, titleMessage:"Error camera isn't available".localized) return } // Config session QR-Code do { let inputDevice : AVCaptureDeviceInput = try AVCaptureDeviceInput(device:device) setupScanner(inputDevice) // Start scanning startScanning() } catch let error as NSError{ PreyLogger("QrCode error: \(error.localizedDescription)") displayErrorAlert("Couldn't add your device".localized, titleMessage:"The scanned QR code is invalid".localized) return } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Methods // Setup scanner func setupScanner(_ input:AVCaptureDeviceInput) { // Config session session.addOutput(output) session.addInput(input) // Config output output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr] // Config preview preview = AVCaptureVideoPreviewLayer(session:session) preview.videoGravity = AVLayerVideoGravity.resizeAspectFill preview.frame = CGRect(x: 0, y: 0,width: self.view.frame.size.width, height: self.view.frame.size.height) preview.connection?.videoOrientation = .portrait self.view.layer.insertSublayer(preview, at:0) // Config label let screen = UIScreen.main.bounds.size let widthLbl = screen.width let fontSize:CGFloat = IS_IPAD ? 16.0 : 12.0 let message = IS_IPAD ? "Visit panel.preyproject.com/qr on your computer and scan the QR code".localized : "Visit panel.preyproject.com/qr \non your computer and scan the QR code".localized let infoQR = UILabel(frame:CGRect(x: 0, y: screen.height-50, width: widthLbl, height: 50)) infoQR.textColor = UIColor(red:0.3019, green:0.3411, blue:0.4, alpha:0.7) infoQR.backgroundColor = UIColor.white infoQR.textAlignment = .center infoQR.font = UIFont(name:fontTitilliumRegular, size:fontSize) infoQR.text = message infoQR.numberOfLines = 2 infoQR.adjustsFontSizeToFitWidth = true self.view.addSubview(infoQR) // Config QrZone image let qrZoneSize = IS_IPAD ? screen.width*0.6 : screen.width*0.78 let qrZonePosY = (screen.height - qrZoneSize)/2 let qrZonePosX = (screen.width - qrZoneSize)/2 let qrZoneImg = UIImageView(image:UIImage(named:"QrZone")) qrZoneImg.frame = CGRect(x: qrZonePosX, y: qrZonePosY, width: qrZoneSize, height: qrZoneSize) self.view.addSubview(qrZoneImg) } // Success scan func successfullyScan(_ scannedValue: NSString) { let validQr = "prey?api_key=" as NSString let checkQr:NSString = (scannedValue.length > validQr.length) ? scannedValue.substring(to: validQr.length) as NSString : "" as NSString let apikeyQr:NSString = (scannedValue.length > validQr.length) ? scannedValue.substring(from: validQr.length) as NSString : "" as NSString stopScanning() self.dismiss(animated: true, completion: {() -> Void in if checkQr.isEqual(to: validQr as String) { PreyDeployment.sharedInstance.addDeviceWith(apikeyQr as String, fromQRCode:true) } else { displayErrorAlert("The scanned QR code is invalid".localized, titleMessage:"Couldn't add your device".localized) } }) } func startScanning() { self.session.startRunning() } func stopScanning() { self.session.stopRunning() } func isCameraAvailable() -> Bool { return AVCaptureDevice.devices(for: AVMediaType.video).count > 0 ? true : false } @objc func cancel() { self.dismiss(animated: true, completion:nil) } // MARK: AVCaptureMetadataOutputObjectsDelegate // CaptureOutput func metadataOutput(_ captureOutput: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { for current in metadataObjects { if current is AVMetadataMachineReadableCodeObject { if let scannedValue = (current as! AVMetadataMachineReadableCodeObject).stringValue { successfullyScan(scannedValue as NSString) } } } } }
c61e8e3cffc00e17679af0307f40ef8f
38.526627
152
0.599401
false
false
false
false
wibosco/WhiteBoardCodingChallenges
refs/heads/main
WhiteBoardCodingChallenges/Challenges/CrackingTheCodingInterview/BuildOrder/ProjectBuildOrder.swift
mit
1
// // BuildOrder.swift // WhiteBoardCodingChallenges // // Created by William Boles on 02/06/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit //CtCI 4.7 class ProjectBuildOrder: NSObject { class func buildOrder(projects: [String], dependencies: [[String]]) -> [ProjectBuildOrderNode]? { let nodes = buildNodes(projects: projects, dependencies: dependencies) for node in nodes { for dependency in node.dependencies { if dependencyCycleExistsBetweenNodes(source: dependency, destination: node) { return nil } } } var orderedNodes = [ProjectBuildOrderNode]() for node in nodes { if !node.pathVisited { buildOrder(rootNode: node, vistedNodes: &orderedNodes) } } return orderedNodes } private class func buildOrder(rootNode: ProjectBuildOrderNode, vistedNodes: inout [ProjectBuildOrderNode]) { for dependency in rootNode.dependencies { if !dependency.pathVisited { buildOrder(rootNode: dependency, vistedNodes: &vistedNodes) } } vistedNodes.append(rootNode) rootNode.pathVisited = true } private class func buildNodes(projects: [String], dependencies: [[String]]) -> [ProjectBuildOrderNode] { var nodes = [String: ProjectBuildOrderNode]() for project in projects { let node = ProjectBuildOrderNode.init(value: project) nodes[project] = node } for dependencyPair in dependencies { let dependent = dependencyPair[1] let dependency = dependencyPair[0] let dependentNode = nodes[dependent] let dependencyNode = nodes[dependency] dependentNode?.addDependency(dependency: dependencyNode!) } return Array(nodes.values) } private class func dependencyCycleExistsBetweenNodes(source: ProjectBuildOrderNode, destination: ProjectBuildOrderNode) -> Bool { var queue = [ProjectBuildOrderNode]() queue.append(source) while queue.count > 0 { let node = queue.removeFirst() for dependency in node.dependencies { if dependency == destination { return true } if !dependency.visited { dependency.visited = true queue.append(dependency) } } } return false } }
ab97d615666bdd2a2383055a870ff98a
26.805556
133
0.509158
false
false
false
false
huonw/swift
refs/heads/master
stdlib/public/core/CompilerProtocols.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Intrinsic protocols shared with the compiler //===----------------------------------------------------------------------===// /// A type that can be converted to and from an associated raw value. /// /// With a `RawRepresentable` type, you can switch back and forth between a /// custom type and an associated `RawValue` type without losing the value of /// the original `RawRepresentable` type. Using the raw value of a conforming /// type streamlines interoperation with Objective-C and legacy APIs and /// simplifies conformance to other protocols, such as `Equatable`, /// `Comparable`, and `Hashable`. /// /// The `RawRepresentable` protocol is seen mainly in two categories of types: /// enumerations with raw value types and option sets. /// /// Enumerations with Raw Values /// ============================ /// /// For any enumeration with a string, integer, or floating-point raw type, the /// Swift compiler automatically adds `RawRepresentable` conformance. When /// defining your own custom enumeration, you give it a raw type by specifying /// the raw type as the first item in the enumeration's type inheritance list. /// You can also use literals to specify values for one or more cases. /// /// For example, the `Counter` enumeration defined here has an `Int` raw value /// type and gives the first case a raw value of `1`: /// /// enum Counter: Int { /// case one = 1, two, three, four, five /// } /// /// You can create a `Counter` instance from an integer value between 1 and 5 /// by using the `init?(rawValue:)` initializer declared in the /// `RawRepresentable` protocol. This initializer is failable because although /// every case of the `Counter` type has a corresponding `Int` value, there /// are many `Int` values that *don't* correspond to a case of `Counter`. /// /// for i in 3...6 { /// print(Counter(rawValue: i)) /// } /// // Prints "Optional(Counter.three)" /// // Prints "Optional(Counter.four)" /// // Prints "Optional(Counter.five)" /// // Prints "nil" /// /// Option Sets /// =========== /// /// Option sets all conform to `RawRepresentable` by inheritance using the /// `OptionSet` protocol. Whether using an option set or creating your own, /// you use the raw value of an option set instance to store the instance's /// bitfield. The raw value must therefore be of a type that conforms to the /// `FixedWidthInteger` protocol, such as `UInt8` or `Int`. For example, the /// `Direction` type defines an option set for the four directions you can /// move in a game. /// /// struct Directions: OptionSet { /// let rawValue: UInt8 /// /// static let up = Directions(rawValue: 1 << 0) /// static let down = Directions(rawValue: 1 << 1) /// static let left = Directions(rawValue: 1 << 2) /// static let right = Directions(rawValue: 1 << 3) /// } /// /// Unlike enumerations, option sets provide a nonfailable `init(rawValue:)` /// initializer to convert from a raw value, because option sets don't have an /// enumerated list of all possible cases. Option set values have /// a one-to-one correspondence with their associated raw values. /// /// In the case of the `Directions` option set, an instance can contain zero, /// one, or more of the four defined directions. This example declares a /// constant with three currently allowed moves. The raw value of the /// `allowedMoves` instance is the result of the bitwise OR of its three /// members' raw values: /// /// let allowedMoves: Directions = [.up, .down, .left] /// print(allowedMoves.rawValue) /// // Prints "7" /// /// Option sets use bitwise operations on their associated raw values to /// implement their mathematical set operations. For example, the `contains()` /// method on `allowedMoves` performs a bitwise AND operation to check whether /// the option set contains an element. /// /// print(allowedMoves.contains(.right)) /// // Prints "false" /// print(allowedMoves.rawValue & Directions.right.rawValue) /// // Prints "0" public protocol RawRepresentable { /// The raw type that can be used to represent all values of the conforming /// type. /// /// Every distinct value of the conforming type has a corresponding unique /// value of the `RawValue` type, but there may be values of the `RawValue` /// type that don't have a corresponding value of the conforming type. associatedtype RawValue /// Creates a new instance with the specified raw value. /// /// If there is no value of the type that corresponds with the specified raw /// value, this initializer returns `nil`. For example: /// /// enum PaperSize: String { /// case A4, A5, Letter, Legal /// } /// /// print(PaperSize(rawValue: "Legal")) /// // Prints "Optional("PaperSize.Legal")" /// /// print(PaperSize(rawValue: "Tabloid")) /// // Prints "nil" /// /// - Parameter rawValue: The raw value to use for the new instance. init?(rawValue: RawValue) /// The corresponding value of the raw type. /// /// A new instance initialized with `rawValue` will be equivalent to this /// instance. For example: /// /// enum PaperSize: String { /// case A4, A5, Letter, Legal /// } /// /// let selectedSize = PaperSize.Letter /// print(selectedSize.rawValue) /// // Prints "Letter" /// /// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!) /// // Prints "true" var rawValue: RawValue { get } } /// Returns a Boolean value indicating whether the two arguments are equal. /// /// - Parameters: /// - lhs: A raw-representable instance. /// - rhs: A second raw-representable instance. @inlinable // FIXME(sil-serialize-all) public func == <T : RawRepresentable>(lhs: T, rhs: T) -> Bool where T.RawValue : Equatable { return lhs.rawValue == rhs.rawValue } /// Returns a Boolean value indicating whether the two arguments are not equal. /// /// - Parameters: /// - lhs: A raw-representable instance. /// - rhs: A second raw-representable instance. @inlinable // FIXME(sil-serialize-all) public func != <T : RawRepresentable>(lhs: T, rhs: T) -> Bool where T.RawValue : Equatable { return lhs.rawValue != rhs.rawValue } // This overload is needed for ambiguity resolution against the // implementation of != for T : Equatable /// Returns a Boolean value indicating whether the two arguments are not equal. /// /// - Parameters: /// - lhs: A raw-representable instance. /// - rhs: A second raw-representable instance. @inlinable // FIXME(sil-serialize-all) public func != <T : Equatable>(lhs: T, rhs: T) -> Bool where T : RawRepresentable, T.RawValue : Equatable { return lhs.rawValue != rhs.rawValue } /// A type that provides a collection of all of its values. /// /// Types that conform to the `CaseIterable` protocol are typically /// enumerations without associated values. When using a `CaseIterable` type, /// you can access a collection of all of the type's cases by using the type's /// `allCases` property. /// /// For example, the `CompassDirection` enumeration declared in this example /// conforms to `CaseIterable`. You access the number of cases and the cases /// themselves through `CompassDirection.allCases`. /// /// enum CompassDirection: CaseIterable { /// case north, south, east, west /// } /// /// print("There are \(CompassDirection.allCases.count) directions.") /// // Prints "There are 4 directions." /// let caseList = CompassDirection.allCases /// .map({ "\($0)" }) /// .joined(separator: ", ") /// // caseList == "north, south, east, west" /// /// Conforming to the CaseIterable Protocol /// ======================================= /// /// The compiler can automatically provide an implementation of the /// `CaseIterable` requirements for any enumeration without associated values /// or `@available` attributes on its cases. The synthesized `allCases` /// collection provides the cases in order of their declaration. /// /// You can take advantage of this compiler support when defining your own /// custom enumeration by declaring conformance to `CaseIterable` in the /// enumeration's original declaration. The `CompassDirection` example above /// demonstrates this automatic implementation. public protocol CaseIterable { /// A type that can represent a collection of all values of this type. associatedtype AllCases: Collection where AllCases.Element == Self /// A collection of all values of this type. static var allCases: AllCases { get } } /// A type that can be initialized using the nil literal, `nil`. /// /// `nil` has a specific meaning in Swift---the absence of a value. Only the /// `Optional` type conforms to `ExpressibleByNilLiteral`. /// `ExpressibleByNilLiteral` conformance for types that use `nil` for other /// purposes is discouraged. public protocol ExpressibleByNilLiteral { /// Creates an instance initialized with `nil`. init(nilLiteral: ()) } public protocol _ExpressibleByBuiltinIntegerLiteral { init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) } /// A type that can be initialized with an integer literal. /// /// The standard library integer and floating-point types, such as `Int` and /// `Double`, conform to the `ExpressibleByIntegerLiteral` protocol. You can /// initialize a variable or constant of any of these types by assigning an /// integer literal. /// /// // Type inferred as 'Int' /// let cookieCount = 12 /// /// // An array of 'Int' /// let chipsPerCookie = [21, 22, 25, 23, 24, 19] /// /// // A floating-point value initialized using an integer literal /// let redPercentage: Double = 1 /// // redPercentage == 1.0 /// /// Conforming to ExpressibleByIntegerLiteral /// ========================================= /// /// To add `ExpressibleByIntegerLiteral` conformance to your custom type, /// implement the required initializer. public protocol ExpressibleByIntegerLiteral { /// A type that represents an integer literal. /// /// The standard library integer and floating-point types are all valid types /// for `IntegerLiteralType`. associatedtype IntegerLiteralType : _ExpressibleByBuiltinIntegerLiteral /// Creates an instance initialized to the specified integer value. /// /// Do not call this initializer directly. Instead, initialize a variable or /// constant using an integer literal. For example: /// /// let x = 23 /// /// In this example, the assignment to the `x` constant calls this integer /// literal initializer behind the scenes. /// /// - Parameter value: The value to create. init(integerLiteral value: IntegerLiteralType) } public protocol _ExpressibleByBuiltinFloatLiteral { init(_builtinFloatLiteral value: _MaxBuiltinFloatType) } /// A type that can be initialized with a floating-point literal. /// /// The standard library floating-point types---`Float`, `Double`, and /// `Float80` where available---all conform to the `ExpressibleByFloatLiteral` /// protocol. You can initialize a variable or constant of any of these types /// by assigning a floating-point literal. /// /// // Type inferred as 'Double' /// let threshold = 6.0 /// /// // An array of 'Double' /// let measurements = [2.2, 4.1, 3.65, 4.2, 9.1] /// /// Conforming to ExpressibleByFloatLiteral /// ======================================= /// /// To add `ExpressibleByFloatLiteral` conformance to your custom type, /// implement the required initializer. public protocol ExpressibleByFloatLiteral { /// A type that represents a floating-point literal. /// /// Valid types for `FloatLiteralType` are `Float`, `Double`, and `Float80` /// where available. associatedtype FloatLiteralType : _ExpressibleByBuiltinFloatLiteral /// Creates an instance initialized to the specified floating-point value. /// /// Do not call this initializer directly. Instead, initialize a variable or /// constant using a floating-point literal. For example: /// /// let x = 21.5 /// /// In this example, the assignment to the `x` constant calls this /// floating-point literal initializer behind the scenes. /// /// - Parameter value: The value to create. init(floatLiteral value: FloatLiteralType) } public protocol _ExpressibleByBuiltinBooleanLiteral { init(_builtinBooleanLiteral value: Builtin.Int1) } /// A type that can be initialized with the Boolean literals `true` and /// `false`. /// /// Only three types provided by Swift---`Bool`, `DarwinBoolean`, and /// `ObjCBool`---are treated as Boolean values. Expanding this set to include /// types that represent more than simple Boolean values is discouraged. /// /// To add `ExpressibleByBooleanLiteral` conformance to your custom type, /// implement the `init(booleanLiteral:)` initializer that creates an instance /// of your type with the given Boolean value. public protocol ExpressibleByBooleanLiteral { /// A type that represents a Boolean literal, such as `Bool`. associatedtype BooleanLiteralType : _ExpressibleByBuiltinBooleanLiteral /// Creates an instance initialized to the given Boolean value. /// /// Do not call this initializer directly. Instead, initialize a variable or /// constant using one of the Boolean literals `true` and `false`. For /// example: /// /// let twasBrillig = true /// /// In this example, the assignment to the `twasBrillig` constant calls this /// Boolean literal initializer behind the scenes. /// /// - Parameter value: The value of the new instance. init(booleanLiteral value: BooleanLiteralType) } public protocol _ExpressibleByBuiltinUnicodeScalarLiteral { init(_builtinUnicodeScalarLiteral value: Builtin.Int32) } /// A type that can be initialized with a string literal containing a single /// Unicode scalar value. /// /// The `String`, `StaticString`, `Character`, and `Unicode.Scalar` types all /// conform to the `ExpressibleByUnicodeScalarLiteral` protocol. You can /// initialize a variable of any of these types using a string literal that /// holds a single Unicode scalar. /// /// let ñ: Unicode.Scalar = "ñ" /// print(ñ) /// // Prints "ñ" /// /// Conforming to ExpressibleByUnicodeScalarLiteral /// =============================================== /// /// To add `ExpressibleByUnicodeScalarLiteral` conformance to your custom type, /// implement the required initializer. public protocol ExpressibleByUnicodeScalarLiteral { /// A type that represents a Unicode scalar literal. /// /// Valid types for `UnicodeScalarLiteralType` are `Unicode.Scalar`, /// `Character`, `String`, and `StaticString`. associatedtype UnicodeScalarLiteralType : _ExpressibleByBuiltinUnicodeScalarLiteral /// Creates an instance initialized to the given value. /// /// - Parameter value: The value of the new instance. init(unicodeScalarLiteral value: UnicodeScalarLiteralType) } public protocol _ExpressibleByBuiltinUTF16ExtendedGraphemeClusterLiteral : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral { init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word) } public protocol _ExpressibleByBuiltinExtendedGraphemeClusterLiteral : _ExpressibleByBuiltinUnicodeScalarLiteral { init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) } /// A type that can be initialized with a string literal containing a single /// extended grapheme cluster. /// /// An *extended grapheme cluster* is a group of one or more Unicode scalar /// values that approximates a single user-perceived character. Many /// individual characters, such as "é", "김", and "🇮🇳", can be made up of /// multiple Unicode scalar values. These code points are combined by /// Unicode's boundary algorithms into extended grapheme clusters. /// /// The `String`, `StaticString`, and `Character` types conform to the /// `ExpressibleByExtendedGraphemeClusterLiteral` protocol. You can initialize /// a variable or constant of any of these types using a string literal that /// holds a single character. /// /// let snowflake: Character = "❄︎" /// print(snowflake) /// // Prints "❄︎" /// /// Conforming to ExpressibleByExtendedGraphemeClusterLiteral /// ========================================================= /// /// To add `ExpressibleByExtendedGraphemeClusterLiteral` conformance to your /// custom type, implement the required initializer. public protocol ExpressibleByExtendedGraphemeClusterLiteral : ExpressibleByUnicodeScalarLiteral { /// A type that represents an extended grapheme cluster literal. /// /// Valid types for `ExtendedGraphemeClusterLiteralType` are `Character`, /// `String`, and `StaticString`. associatedtype ExtendedGraphemeClusterLiteralType : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral /// Creates an instance initialized to the given value. /// /// - Parameter value: The value of the new instance. init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) } extension ExpressibleByExtendedGraphemeClusterLiteral where ExtendedGraphemeClusterLiteralType == UnicodeScalarLiteralType { @inlinable // FIXME(sil-serialize-all) @_transparent public init(unicodeScalarLiteral value: ExtendedGraphemeClusterLiteralType) { self.init(extendedGraphemeClusterLiteral: value) } } public protocol _ExpressibleByBuiltinStringLiteral : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral { init( _builtinStringLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) } public protocol _ExpressibleByBuiltinUTF16StringLiteral : _ExpressibleByBuiltinStringLiteral { init( _builtinUTF16StringLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word) } public protocol _ExpressibleByBuiltinConstStringLiteral : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral { init(_builtinConstStringLiteral constantString: Builtin.RawPointer) } public protocol _ExpressibleByBuiltinConstUTF16StringLiteral : _ExpressibleByBuiltinConstStringLiteral { init(_builtinConstUTF16StringLiteral constantUTF16String: Builtin.RawPointer) } /// A type that can be initialized with a string literal. /// /// The `String` and `StaticString` types conform to the /// `ExpressibleByStringLiteral` protocol. You can initialize a variable or /// constant of either of these types using a string literal of any length. /// /// let picnicGuest = "Deserving porcupine" /// /// Conforming to ExpressibleByStringLiteral /// ======================================== /// /// To add `ExpressibleByStringLiteral` conformance to your custom type, /// implement the required initializer. public protocol ExpressibleByStringLiteral : ExpressibleByExtendedGraphemeClusterLiteral { /// A type that represents a string literal. /// /// Valid types for `StringLiteralType` are `String` and `StaticString`. associatedtype StringLiteralType : _ExpressibleByBuiltinStringLiteral /// Creates an instance initialized to the given string value. /// /// - Parameter value: The value of the new instance. init(stringLiteral value: StringLiteralType) } extension ExpressibleByStringLiteral where StringLiteralType == ExtendedGraphemeClusterLiteralType { @inlinable // FIXME(sil-serialize-all) @_transparent public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(stringLiteral: value) } } /// A type that can be initialized using an array literal. /// /// An array literal is a simple way of expressing a list of values. Simply /// surround a comma-separated list of values, instances, or literals with /// square brackets to create an array literal. You can use an array literal /// anywhere an instance of an `ExpressibleByArrayLiteral` type is expected: as /// a value assigned to a variable or constant, as a parameter to a method or /// initializer, or even as the subject of a nonmutating operation like /// `map(_:)` or `filter(_:)`. /// /// Arrays, sets, and option sets all conform to `ExpressibleByArrayLiteral`, /// and your own custom types can as well. Here's an example of creating a set /// and an array using array literals: /// /// let employeesSet: Set<String> = ["Amir", "Jihye", "Dave", "Alessia", "Dave"] /// print(employeesSet) /// // Prints "["Amir", "Dave", "Jihye", "Alessia"]" /// /// let employeesArray: [String] = ["Amir", "Jihye", "Dave", "Alessia", "Dave"] /// print(employeesArray) /// // Prints "["Amir", "Jihye", "Dave", "Alessia", "Dave"]" /// /// The `Set` and `Array` types each handle array literals in their own way to /// create new instances. In this case, the newly created set drops the /// duplicate value ("Dave") and doesn't maintain the order of the array /// literal's elements. The new array, on the other hand, matches the order /// and number of elements provided. /// /// - Note: An array literal is not the same as an `Array` instance. You can't /// initialize a type that conforms to `ExpressibleByArrayLiteral` simply by /// assigning an existing array. /// /// let anotherSet: Set = employeesArray /// // error: cannot convert value of type '[String]' to specified type 'Set' /// /// Type Inference of Array Literals /// ================================ /// /// Whenever possible, Swift's compiler infers the full intended type of your /// array literal. Because `Array` is the default type for an array literal, /// without writing any other code, you can declare an array with a particular /// element type by providing one or more values. /// /// In this example, the compiler infers the full type of each array literal. /// /// let integers = [1, 2, 3] /// // 'integers' has type '[Int]' /// /// let strings = ["a", "b", "c"] /// // 'strings' has type '[String]' /// /// An empty array literal alone doesn't provide enough information for the /// compiler to infer the intended type of the `Array` instance. When using an /// empty array literal, specify the type of the variable or constant. /// /// var emptyArray: [Bool] = [] /// // 'emptyArray' has type '[Bool]' /// /// Because many functions and initializers fully specify the types of their /// parameters, you can often use an array literal with or without elements as /// a parameter. For example, the `sum(_:)` function shown here takes an `Int` /// array as a parameter: /// /// func sum(values: [Int]) -> Int { /// return values.reduce(0, +) /// } /// /// let sumOfFour = sum([5, 10, 15, 20]) /// // 'sumOfFour' == 50 /// /// let sumOfNone = sum([]) /// // 'sumOfNone' == 0 /// /// When you call a function that does not fully specify its parameters' types, /// use the type-cast operator (`as`) to specify the type of an array literal. /// For example, the `log(name:value:)` function shown here has an /// unconstrained generic `value` parameter. /// /// func log<T>(name name: String, value: T) { /// print("\(name): \(value)") /// } /// /// log(name: "Four integers", value: [5, 10, 15, 20]) /// // Prints "Four integers: [5, 10, 15, 20]" /// /// log(name: "Zero integers", value: [] as [Int]) /// // Prints "Zero integers: []" /// /// Conforming to ExpressibleByArrayLiteral /// ======================================= /// /// Add the capability to be initialized with an array literal to your own /// custom types by declaring an `init(arrayLiteral:)` initializer. The /// following example shows the array literal initializer for a hypothetical /// `OrderedSet` type, which has setlike semantics but maintains the order of /// its elements. /// /// struct OrderedSet<Element: Hashable>: Collection, SetAlgebra { /// // implementation details /// } /// /// extension OrderedSet: ExpressibleByArrayLiteral { /// init(arrayLiteral: Element...) { /// self.init() /// for element in arrayLiteral { /// self.append(element) /// } /// } /// } public protocol ExpressibleByArrayLiteral { /// The type of the elements of an array literal. associatedtype ArrayLiteralElement /// Creates an instance initialized with the given elements. init(arrayLiteral elements: ArrayLiteralElement...) } /// A type that can be initialized using a dictionary literal. /// /// A dictionary literal is a simple way of writing a list of key-value pairs. /// You write each key-value pair with a colon (`:`) separating the key and /// the value. The dictionary literal is made up of one or more key-value /// pairs, separated by commas and surrounded with square brackets. /// /// To declare a dictionary, assign a dictionary literal to a variable or /// constant: /// /// let countryCodes = ["BR": "Brazil", "GH": "Ghana", /// "JP": "Japan", "US": "United States"] /// // 'countryCodes' has type [String: String] /// /// print(countryCodes["BR"]!) /// // Prints "Brazil" /// /// When the context provides enough type information, you can use a special /// form of the dictionary literal, square brackets surrounding a single /// colon, to initialize an empty dictionary. /// /// var frequencies: [String: Int] = [:] /// print(frequencies.count) /// // Prints "0" /// /// - Note: A dictionary literal is *not* the same as an instance of /// `Dictionary` or the similarly named `DictionaryLiteral` type. You can't /// initialize a type that conforms to `ExpressibleByDictionaryLiteral` simply /// by assigning an instance of one of these types. /// /// Conforming to the ExpressibleByDictionaryLiteral Protocol /// ========================================================= /// /// To add the capability to be initialized with a dictionary literal to your /// own custom types, declare an `init(dictionaryLiteral:)` initializer. The /// following example shows the dictionary literal initializer for a /// hypothetical `CountedSet` type, which uses setlike semantics while keeping /// track of the count for duplicate elements: /// /// struct CountedSet<Element: Hashable>: Collection, SetAlgebra { /// // implementation details /// /// /// Updates the count stored in the set for the given element, /// /// adding the element if necessary. /// /// /// /// - Parameter n: The new count for `element`. `n` must be greater /// /// than or equal to zero. /// /// - Parameter element: The element to set the new count on. /// mutating func updateCount(_ n: Int, for element: Element) /// } /// /// extension CountedSet: ExpressibleByDictionaryLiteral { /// init(dictionaryLiteral elements: (Element, Int)...) { /// self.init() /// for (element, count) in elements { /// self.updateCount(count, for: element) /// } /// } /// } public protocol ExpressibleByDictionaryLiteral { /// The key type of a dictionary literal. associatedtype Key /// The value type of a dictionary literal. associatedtype Value /// Creates an instance initialized with the given key-value pairs. init(dictionaryLiteral elements: (Key, Value)...) } /// A type that can be initialized by string interpolation with a string /// literal that includes expressions. /// /// Use string interpolation to include one or more expressions in a string /// literal, wrapped in a set of parentheses and prefixed by a backslash. For /// example: /// /// let price = 2 /// let number = 3 /// let message = "One cookie: $\(price), \(number) cookies: $\(price * number)." /// print(message) /// // Prints "One cookie: $2, 3 cookies: $6." /// /// Conforming to the ExpressibleByStringInterpolation Protocol /// =========================================================== /// /// The `ExpressibleByStringInterpolation` protocol is deprecated. Do not add /// new conformances to the protocol. @available(*, deprecated, message: "it will be replaced or redesigned in Swift 4.0. Instead of conforming to 'ExpressibleByStringInterpolation', consider adding an 'init(_:String)'") public typealias ExpressibleByStringInterpolation = _ExpressibleByStringInterpolation public protocol _ExpressibleByStringInterpolation { /// Creates an instance by concatenating the given values. /// /// Do not call this initializer directly. It is used by the compiler when /// you use string interpolation. For example: /// /// let s = "\(5) x \(2) = \(5 * 2)" /// print(s) /// // Prints "5 x 2 = 10" /// /// After calling `init(stringInterpolationSegment:)` with each segment of /// the string literal, this initializer is called with their string /// representations. /// /// - Parameter strings: An array of instances of the conforming type. init(stringInterpolation strings: Self...) /// Creates an instance containing the appropriate representation for the /// given value. /// /// Do not call this initializer directly. It is used by the compiler for /// each string interpolation segment when you use string interpolation. For /// example: /// /// let s = "\(5) x \(2) = \(5 * 2)" /// print(s) /// // Prints "5 x 2 = 10" /// /// This initializer is called five times when processing the string literal /// in the example above; once each for the following: the integer `5`, the /// string `" x "`, the integer `2`, the string `" = "`, and the result of /// the expression `5 * 2`. /// /// - Parameter expr: The expression to represent. init<T>(stringInterpolationSegment expr: T) } /// A type that can be initialized using a color literal (e.g. /// `#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)`). public protocol _ExpressibleByColorLiteral { /// Creates an instance initialized with the given properties of a color /// literal. /// /// Do not call this initializer directly. Instead, initialize a variable or /// constant using a color literal. init(_colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float) } extension _ExpressibleByColorLiteral { @inlinable // FIXME(sil-serialize-all) @available(swift, deprecated: 3.2, obsoleted: 4.0, message: "This initializer is only meant to be used by color literals") public init( colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float ) { self.init( _colorLiteralRed: red, green: green, blue: blue, alpha: alpha) } } /// A type that can be initialized using an image literal (e.g. /// `#imageLiteral(resourceName: "hi.png")`). public protocol _ExpressibleByImageLiteral { /// Creates an instance initialized with the given resource name. /// /// Do not call this initializer directly. Instead, initialize a variable or /// constant using an image literal. init(imageLiteralResourceName path: String) } /// A type that can be initialized using a file reference literal (e.g. /// `#fileLiteral(resourceName: "resource.txt")`). public protocol _ExpressibleByFileReferenceLiteral { /// Creates an instance initialized with the given resource name. /// /// Do not call this initializer directly. Instead, initialize a variable or /// constant using a file reference literal. init(fileReferenceLiteralResourceName path: String) } /// A container is destructor safe if whether it may store to memory on /// destruction only depends on its type parameters destructors. /// For example, whether `Array<Element>` may store to memory on destruction /// depends only on `Element`. /// If `Element` is an `Int` we know the `Array<Int>` does not store to memory /// during destruction. If `Element` is an arbitrary class /// `Array<MemoryUnsafeDestructorClass>` then the compiler will deduce may /// store to memory on destruction because `MemoryUnsafeDestructorClass`'s /// destructor may store to memory on destruction. /// If in this example during `Array`'s destructor we would call a method on any /// type parameter - say `Element.extraCleanup()` - that could store to memory, /// then Array would no longer be a _DestructorSafeContainer. public protocol _DestructorSafeContainer { } // Deprecated by SE-0115. @available(*, deprecated, renamed: "ExpressibleByNilLiteral") public typealias NilLiteralConvertible = ExpressibleByNilLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinIntegerLiteral") public typealias _BuiltinIntegerLiteralConvertible = _ExpressibleByBuiltinIntegerLiteral @available(*, deprecated, renamed: "ExpressibleByIntegerLiteral") public typealias IntegerLiteralConvertible = ExpressibleByIntegerLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinFloatLiteral") public typealias _BuiltinFloatLiteralConvertible = _ExpressibleByBuiltinFloatLiteral @available(*, deprecated, renamed: "ExpressibleByFloatLiteral") public typealias FloatLiteralConvertible = ExpressibleByFloatLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinBooleanLiteral") public typealias _BuiltinBooleanLiteralConvertible = _ExpressibleByBuiltinBooleanLiteral @available(*, deprecated, renamed: "ExpressibleByBooleanLiteral") public typealias BooleanLiteralConvertible = ExpressibleByBooleanLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinUnicodeScalarLiteral") public typealias _BuiltinUnicodeScalarLiteralConvertible = _ExpressibleByBuiltinUnicodeScalarLiteral @available(*, deprecated, renamed: "ExpressibleByUnicodeScalarLiteral") public typealias UnicodeScalarLiteralConvertible = ExpressibleByUnicodeScalarLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinExtendedGraphemeClusterLiteral") public typealias _BuiltinExtendedGraphemeClusterLiteralConvertible = _ExpressibleByBuiltinExtendedGraphemeClusterLiteral @available(*, deprecated, renamed: "ExpressibleByExtendedGraphemeClusterLiteral") public typealias ExtendedGraphemeClusterLiteralConvertible = ExpressibleByExtendedGraphemeClusterLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinStringLiteral") public typealias _BuiltinStringLiteralConvertible = _ExpressibleByBuiltinStringLiteral @available(*, deprecated, renamed: "_ExpressibleByBuiltinUTF16StringLiteral") public typealias _BuiltinUTF16StringLiteralConvertible = _ExpressibleByBuiltinUTF16StringLiteral @available(*, deprecated, renamed: "ExpressibleByStringLiteral") public typealias StringLiteralConvertible = ExpressibleByStringLiteral @available(*, deprecated, renamed: "ExpressibleByArrayLiteral") public typealias ArrayLiteralConvertible = ExpressibleByArrayLiteral @available(*, deprecated, renamed: "ExpressibleByDictionaryLiteral") public typealias DictionaryLiteralConvertible = ExpressibleByDictionaryLiteral @available(*, deprecated, message: "it will be replaced or redesigned in Swift 4.0. Instead of conforming to 'StringInterpolationConvertible', consider adding an 'init(_:String)'") public typealias StringInterpolationConvertible = ExpressibleByStringInterpolation @available(*, deprecated, renamed: "_ExpressibleByColorLiteral") public typealias _ColorLiteralConvertible = _ExpressibleByColorLiteral @available(*, deprecated, renamed: "_ExpressibleByImageLiteral") public typealias _ImageLiteralConvertible = _ExpressibleByImageLiteral @available(*, deprecated, renamed: "_ExpressibleByFileReferenceLiteral") public typealias _FileReferenceLiteralConvertible = _ExpressibleByFileReferenceLiteral
e5f28846ee6017c4c263c4d6174f7779
39.882486
183
0.696692
false
false
false
false
e-liu/LayoutKit
refs/heads/develop
Carthage/Checkouts/LayoutKit/LayoutKitSampleApp/StackViewController.swift
apache-2.0
6
// Copyright 2016 LinkedIn Corp. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import UIKit import LayoutKit /** Uses a stack view to layout subviews. */ class StackViewController: UIViewController { private var stackView: StackView! override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = UIRectEdge() stackView = StackView(axis: .vertical, spacing: 4) stackView.addArrangedSubviews([ UILabel(text: "Nick"), UILabel(text: "Software Engineer") ]) stackView.frame = view.bounds stackView.autoresizingMask = [.flexibleWidth, .flexibleHeight] stackView.backgroundColor = UIColor.purple view.addSubview(stackView) } } extension UILabel { convenience init(text: String) { self.init() self.text = text } }
27de917d4f72e628dc1b98571aff25a4
28.904762
131
0.682325
false
false
false
false
callam/Heimdall.swift
refs/heads/master
Heimdall/NSURLRequestExtensions.swift
apache-2.0
5
import Foundation /// An HTTP authentication is used for authorizing requests to either the token /// or the resource endpoint. public enum HTTPAuthentication: Equatable { /// HTTP Basic Authentication. /// /// :param: username The username. /// :param: password The password. case BasicAuthentication(username: String, password: String) /// Access Token Authentication. /// /// :param: _ The access token. case AccessTokenAuthentication(OAuthAccessToken) /// Returns the authentication encoded as `String` suitable for the HTTP /// `Authorization` header. private var value: String? { switch self { case .BasicAuthentication(let username, let password): if let credentials = "\(username):\(password)" .dataUsingEncoding(NSASCIIStringEncoding)? .base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0)) { return "Basic \(credentials)" } else { return nil } case .AccessTokenAuthentication(let accessToken): return "\(accessToken.tokenType) \(accessToken.accessToken)" } } } public func == (lhs: HTTPAuthentication, rhs: HTTPAuthentication) -> Bool { switch (lhs, rhs) { case (.BasicAuthentication(let lusername, let lpassword), .BasicAuthentication(let rusername, let rpassword)): return lusername == rusername && lpassword == rpassword case (.AccessTokenAuthentication(let laccessToken), .AccessTokenAuthentication(let raccessToken)): return laccessToken == raccessToken default: return false } } private let HTTPRequestHeaderFieldAuthorization = "Authorization" public extension NSURLRequest { /// Returns the HTTP `Authorization` header value or `nil` if not set. public var HTTPAuthorization: String? { return self.valueForHTTPHeaderField(HTTPRequestHeaderFieldAuthorization) } } public extension NSMutableURLRequest { /// Sets the HTTP `Authorization` header value. /// /// :param: value The value to be set or `nil`. /// /// TODO: Declarations in extensions cannot override yet. public func setHTTPAuthorization(value: String?) { self.setValue(value, forHTTPHeaderField: HTTPRequestHeaderFieldAuthorization) } /// Sets the HTTP `Authorization` header value using the given HTTP /// authentication. /// /// :param: authentication The HTTP authentication to be set. public func setHTTPAuthorization(authentication: HTTPAuthentication) { self.setHTTPAuthorization(authentication.value) } /// Sets the HTTP body using the given paramters encoded as query string. /// /// :param: parameters The parameters to be encoded or `nil`. /// /// TODO: Tests crash without named parameter. public func setHTTPBody(#parameters: [String: AnyObject]?) { if let parameters = parameters { var components: [(String, String)] = [] for (key, value) in parameters { components += queryComponents(key, value) } var bodyString = join("&", components.map { "\($0)=\($1)" } ) HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding) } else { HTTPBody = nil } } // Taken from https://github.com/Alamofire/Alamofire/blob/master/Source/ParameterEncoding.swift#L136 private func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value) } } else { components.extend([(escapeQuery(key), escapeQuery("\(value)"))]) } return components } private func escapeQuery(string: String) -> String { let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*" let charactersToLeaveUnescaped: CFStringRef = "[]." return CFURLCreateStringByAddingPercentEscapes(nil, string, charactersToLeaveUnescaped, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as! String } }
1812e9afe9474062ad20becbe4a5978d
37.655172
177
0.642953
false
false
false
false
MartinLasek/vaporberlinBE
refs/heads/master
Sources/App/Backend/Token/Model/Token.swift
mit
1
import FluentProvider import Vapor import Crypto final class Token: Model { let storage = Storage() let token: String let userId: Identifier init(token: String, user: User) throws { self.token = token self.userId = try user.assertExists() } init(row: Row) throws { self.token = try row.get("token") self.userId = try row.get(User.foreignIdKey) } func makeRow() throws -> Row{ var row = Row() try row.set("token", token) try row.set(User.foreignIdKey, userId) return row } } extension Token: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.string("token") builder.foreignId(for: User.self) } } static func revert(_ database: Database) throws { try database.delete(self) } } /// - create relation to user extension Token { var user: Parent<Token, User> { return parent(id: userId) } } /// - generate random token /// - initialize model with token and given user /// - return Token-Object extension Token { static func generate(for user: User) throws -> Token { let random = try Crypto.Random.bytes(count: 16) return try Token(token: random.base64Encoded.makeString(), user: user) } } /// - create JSON format extension Token: JSONRepresentable { func makeJSON() throws -> JSON { var json = JSON() try json.set("token", token) return json } }
50f2a416be7ac02f1261814c053ed313
21.090909
74
0.657064
false
false
false
false
ZevEisenberg/Padiddle
refs/heads/main
Experiments/Path Smoothing Tester.playground/Contents.swift
mit
1
import UIKit import PlaygroundSupport final class PathView: UIView { private var path: CGPath? = nil class func smoothedPathSegment(points: [CGPoint]) -> CGPath { assert(points.count == 4) let p0 = points[3] let p1 = points[2] let p2 = points[1] let p3 = points[0] let c1 = CGPoint( x: (p0.x + p1.x) / 2.0, y: (p0.y + p1.y) / 2.0) let c2 = CGPoint( x: (p1.x + p2.x) / 2.0, y: (p1.y + p2.y) / 2.0) let c3 = CGPoint( x: (p2.x + p3.x) / 2.0, y: (p2.y + p3.y) / 2.0) let len1 = sqrt(pow(p1.x - p0.x, 2.0) + pow(p1.y - p0.y, 2.0)) let len2 = sqrt(pow(p2.x - p1.x, 2.0) + pow(p2.y - p1.y, 2.0)) let len3 = sqrt(pow(p3.x - p2.x, 2.0) + pow(p3.y - p2.y, 2.0)) let divisor1 = len1 + len2 let divisor2 = len2 + len3 let k1 = len1 / divisor1 let k2 = len2 / divisor2 let m1 = CGPoint( x: c1.x + (c2.x - c1.x) * k1, y: c1.y + (c2.y - c1.y) * k1) let m2 = CGPoint( x: c2.x + (c3.x - c2.x) * k2, y: c2.y + (c3.y - c2.y) * k2) // Resulting control points. Here smooth_value is mentioned // above coefficient K whose value should be in range [0...1]. let smoothValue = CGFloat(1.0) let ctrl1: CGPoint = { let x = m1.x + (c2.x - m1.x) * smoothValue + p1.x - m1.x let y = m1.y + (c2.y - m1.y) * smoothValue + p1.y - m1.y return CGPoint(x: x, y: y) }() let ctrl2: CGPoint = { let x = m2.x + (c2.x - m2.x) * smoothValue + p2.x - m2.x let y = m2.y + (c2.y - m2.y) * smoothValue + p2.y - m2.y return CGPoint(x: x, y: y) }() let pathSegment = CGMutablePath() pathSegment.move(to: p1) pathSegment.addCurve(to: p2, control1: ctrl1, control2: ctrl2) return pathSegment } func update(with points: [CGPoint]) { assert(points.count == 4) let mutablePath = CGMutablePath() mutablePath.addPath(PathView.smoothedPathSegment(points: points)) path = mutablePath setNeedsDisplay() } override func draw(_ rect: CGRect) { super.draw(rect) guard let path = path else { return } let uiPath = UIBezierPath(cgPath: path) uiPath.lineWidth = 2 UIColor.red.setFill() uiPath.stroke() } } final class MovableView: UIView { private let dragNotifier: () -> () init(frame: CGRect, dragNotifier: @escaping () -> ()) { self.dragNotifier = dragNotifier super.init(frame: frame) isOpaque = false let pan = UIPanGestureRecognizer(target: self, action: #selector(panned(_:))) addGestureRecognizer(pan) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { UIColor.blue.setFill() UIBezierPath(ovalIn: bounds).fill() } func panned(_ sender: UIPanGestureRecognizer) { switch sender.state { case .changed: guard let superview = superview else { fatalError() } let location = sender.location(in: superview) center = location dragNotifier() default: break } } } let pathView = PathView(frame: CGRect(x: 0, y: 0, width: 400, height: 300)) pathView.backgroundColor = .lightGray let positions = [ CGPoint(x: 20, y: 20), CGPoint(x: 50, y: 30), CGPoint(x: 120, y: 20), CGPoint(x: 180, y: 50), ] let notifier = { let centers = pathView.subviews.map { $0.center } pathView.update(with: centers) } let movables = positions.map { point in MovableView(frame: CGRect(origin: point, size: CGSize(width: 25, height: 25)), dragNotifier: notifier) } for view in movables { pathView.addSubview(view) } notifier() PlaygroundPage.current.liveView = pathView
86274c6cb96656fd6902720667df0ebb
26.904762
106
0.541331
false
false
false
false
NeilNie/Done-
refs/heads/master
Pods/Charts/Source/Charts/Renderers/YAxisRenderer.swift
apache-2.0
2
// // YAxisRenderer.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 @objc(ChartYAxisRenderer) open class YAxisRenderer: AxisRendererBase { @objc public init(viewPortHandler: ViewPortHandler, yAxis: YAxis?, transformer: Transformer?) { super.init(viewPortHandler: viewPortHandler, transformer: transformer, axis: yAxis) } /// draws the y-axis labels to the screen open override func renderAxisLabels(context: CGContext) { guard let yAxis = self.axis as? YAxis else { return } if !yAxis.isEnabled || !yAxis.isDrawLabelsEnabled { return } let xoffset = yAxis.xOffset let yoffset = yAxis.labelFont.lineHeight / 2.5 + yAxis.yOffset let dependency = yAxis.axisDependency let labelPosition = yAxis.labelPosition var xPos = CGFloat(0.0) var textAlign: NSTextAlignment if dependency == .left { if labelPosition == .outsideChart { textAlign = .right xPos = viewPortHandler.offsetLeft - xoffset } else { textAlign = .left xPos = viewPortHandler.offsetLeft + xoffset } } else { if labelPosition == .outsideChart { textAlign = .left xPos = viewPortHandler.contentRight + xoffset } else { textAlign = .right xPos = viewPortHandler.contentRight - xoffset } } drawYLabels( context: context, fixedPosition: xPos, positions: transformedPositions(), offset: yoffset - yAxis.labelFont.lineHeight, textAlign: textAlign) } open override func renderAxisLine(context: CGContext) { guard let yAxis = self.axis as? YAxis 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.contentLeft, y: viewPortHandler.contentBottom)) context.strokePath() } else { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom)) context.strokePath() } context.restoreGState() } /// draws the y-labels on the specified x-position internal func drawYLabels( context: CGContext, fixedPosition: CGFloat, positions: [CGPoint], offset: CGFloat, textAlign: NSTextAlignment) { guard let yAxis = self.axis as? YAxis else { return } let labelFont = yAxis.labelFont let labelTextColor = yAxis.labelTextColor let from = yAxis.isDrawBottomYLabelEntryEnabled ? 0 : 1 let to = yAxis.isDrawTopYLabelEntryEnabled ? yAxis.entryCount : (yAxis.entryCount - 1) for i in stride(from: from, to: to, by: 1) { let text = yAxis.getFormattedLabel(i) ChartUtils.drawText( context: context, text: text, point: CGPoint(x: fixedPosition, y: positions[i].y + offset), align: textAlign, attributes: [NSAttributedString.Key.font: labelFont, NSAttributedString.Key.foregroundColor: labelTextColor]) } } open override func renderGridLines(context: CGContext) { guard let yAxis = self.axis as? YAxis else { return } if !yAxis.isEnabled { return } if yAxis.drawGridLinesEnabled { let positions = transformedPositions() context.saveGState() defer { context.restoreGState() } context.clip(to: self.gridClippingRect) context.setShouldAntialias(yAxis.gridAntialiasEnabled) context.setStrokeColor(yAxis.gridColor.cgColor) context.setLineWidth(yAxis.gridLineWidth) context.setLineCap(yAxis.gridLineCap) if yAxis.gridLineDashLengths != nil { context.setLineDash(phase: yAxis.gridLineDashPhase, lengths: yAxis.gridLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } // draw the grid for i in 0 ..< positions.count { drawGridLine(context: context, position: positions[i]) } } if yAxis.drawZeroLineEnabled { // draw zero line drawZeroLine(context: context) } } @objc open var gridClippingRect: CGRect { var contentRect = viewPortHandler.contentRect let dy = self.axis?.gridLineWidth ?? 0.0 contentRect.origin.y -= dy / 2.0 contentRect.size.height += dy return contentRect } @objc open func drawGridLine( context: CGContext, position: CGPoint) { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y)) context.strokePath() } @objc open 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: 0.0, y: entries[i])) } transformer.pointValuesToPixel(&positions) return positions } /// Draws the zero line at the specified position. @objc open func drawZeroLine(context: CGContext) { guard let yAxis = self.axis as? YAxis, let transformer = self.transformer, let zeroLineColor = yAxis.zeroLineColor else { return } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.y -= yAxis.zeroLineWidth / 2.0 clippingRect.size.height += 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: viewPortHandler.contentLeft, y: pos.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: pos.y)) context.drawPath(using: CGPathDrawingMode.stroke) } open override func renderLimitLines(context: CGContext) { guard let yAxis = self.axis as? YAxis, 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.y -= l.lineWidth / 2.0 clippingRect.size.height += l.lineWidth context.clip(to: clippingRect) position.x = 0.0 position.y = CGFloat(l.limit) position = position.applying(trans) context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y)) 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 = 4.0 + l.xOffset let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset if l.labelPosition == .rightTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset), align: .right, attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .rightBottom { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y + yOffset - labelLineHeight), align: .right, attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .leftTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset), align: .left, attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y + yOffset - labelLineHeight), align: .left, attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor]) } } } context.restoreGState() } }
edc012e6c00731f416e2a69ca4185800
31.522959
137
0.529689
false
false
false
false
narner/AudioKit
refs/heads/master
Playgrounds/AudioKitPlaygrounds/Playgrounds/Synthesis.playground/Pages/Microtonality.xcplaygroundpage/Contents.swift
mit
1
//: ## Microtonality import AudioKitPlaygrounds import AudioKit // SEQUENCER PARAMETERS let playRate: Double = 4 var transposition: Int = 0 var performanceCounter: Int = 0 // OSC let osc = AKMorphingOscillatorBank() osc.index = 0.8 osc.attackDuration = 0.001 osc.decayDuration = 0.25 osc.sustainLevel = 0.238_186 osc.releaseDuration = 0.125 // FILTER let filter = AKKorgLowPassFilter(osc) filter.cutoffFrequency = 5_500 filter.resonance = 0.2 let generatorBooster = AKBooster(filter) generatorBooster.gain = 0.618 // DELAY let delay = AKDelay(generatorBooster) delay.time = 1.0 / playRate delay.feedback = 0.618 delay.lowPassCutoff = 12_048 delay.dryWetMix = 0.75 let delayBooster = AKBooster(delay) delayBooster.gain = 1.550_8 // REVERB let reverb = AKCostelloReverb(delayBooster) reverb.feedback = 0.758_816_18 reverb.cutoffFrequency = 2_222 + 1_000 let reverbBooster = AKBooster(reverb) reverbBooster.gain = 0.746_7 // MIX let mixer = AKMixer(generatorBooster, reverbBooster) // MICROTONAL PRESETS var presetDictionary = [String: () -> Void]() let tuningTable = AKPolyphonicNode.tuningTable presetDictionary["Ahir Bhairav"] = { tuningTable.presetPersian17NorthIndian19AhirBhairav() } presetDictionary["Basant Mukhari"] = { tuningTable.presetPersian17NorthIndian21BasantMukhari() } presetDictionary["Champakali"] = { tuningTable.presetPersian17NorthIndian22Champakali() } presetDictionary["Chandra Kanada"] = { tuningTable.presetPersian17NorthIndian20ChandraKanada() } presetDictionary["Diaphonic Tetrachhord"] = { tuningTable.presetDiaphonicTetrachord() } presetDictionary["ET 5"] = { tuningTable.equalTemperament(notesPerOctave: 5) } presetDictionary["Hexany (1,5,9,15)"] = { tuningTable.hexany(1, 5, 9, 15) } presetDictionary["Hexany (3,4.,7.,10.)"] = { tuningTable.hexany(3, 4.051, 7.051, 10.051) } presetDictionary["Highland Bagpipes"] = { tuningTable.presetHighlandBagPipes() } presetDictionary["Madhubanti"] = { tuningTable.presetPersian17NorthIndian17Madhubanti() } presetDictionary["Mohan Kauns"] = { tuningTable.presetPersian17NorthIndian24MohanKauns() } presetDictionary["MOS 0.2381 9 tones"] = { tuningTable.momentOfSymmetry(generator: 0.238_186, level: 6) } presetDictionary["MOS 0.2641 7 tones"] = { tuningTable.momentOfSymmetry(generator: 0.264_100, level: 5) } presetDictionary["MOS 0.2926 7 tones"] = { tuningTable.momentOfSymmetry(generator: 0.292_626, level: 5, murchana: 3) } presetDictionary["MOS 0.5833 7 tones"] = { tuningTable.momentOfSymmetry(generator: 0.583_333, level: 5) } presetDictionary["MOS 0.5833 7 tones Mode 2"] = { tuningTable.momentOfSymmetry(generator: 0.583_333, level: 5, murchana: 2) } presetDictionary["Nat Bhairav"] = { tuningTable.presetPersian17NorthIndian18NatBhairav() } presetDictionary["Patdeep"] = { tuningTable.presetPersian17NorthIndian23Patdeep() } presetDictionary["Recurrence Relation"] = { tuningTable.presetRecurrenceRelation01() } presetDictionary["Tetrany Major (1,5,9,15)"] = { tuningTable.majorTetrany(1, 5, 9, 15) } presetDictionary["Tetrany Minor (1,5,9,15)"] = { tuningTable.minorTetrany(1, 5, 9, 15) } let presetArray = presetDictionary.keys.sorted() let numTunings = presetArray.count // SELECT A TUNING func selectTuning(_ index: Int) { let i = index % numTunings let key = presetArray[i] presetDictionary[key]?() } // DEFAULT TUNING selectTuning(0) let sequencerPatterns: [String: [Int]] = [ "Up Down": [0, 1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1], "Arp 1": [1, 0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 4, 5, 3, 4, 2, 3, 1, 2, 0, 1], "Arp 2": [0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 6, 7, 5, 6, 4, 5, 3, 4, 2, 3, 1]] let sequencerPatternPresets = sequencerPatterns.keys.sorted() var sequencerPattern = sequencerPatterns[sequencerPatternPresets[0]]! // SEQUENCER CALCULATION func nnCalc(_ counter: Int) -> MIDINoteNumber { // negative time if counter < 0 { return 0 } let npo = sequencerPattern.count var note: Int = counter % npo note = sequencerPattern[note] let rootNN: Int = 60 let nn = MIDINoteNumber(note + rootNN + transposition) return nn } // periodic function for arpeggio let sequencerFunction = AKPeriodicFunction(frequency: playRate) { // send note off for notes in the past let pastNN = nnCalc(performanceCounter - 2) osc.stop(noteNumber: pastNN) // send note on for notes in the present let presentNN = nnCalc(performanceCounter) let frequency = AKPolyphonicNode.tuningTable.frequency(forNoteNumber: presentNN) osc.play(noteNumber: presentNN, velocity: 127, frequency: frequency) performanceCounter += 1 } // Start Audio AudioKit.output = mixer AudioKit.start(withPeriodicFunctions: sequencerFunction) sequencerFunction.start() import AudioKitUI class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("Microtonal Morphing Oscillator") addView(AKPresetLoaderView(presets: presetArray) { preset in presetDictionary[preset]?() }) addView(AKPresetLoaderView(presets: sequencerPatternPresets) { preset in osc.reset() sequencerPattern = sequencerPatterns[preset]! }) addView(AKSlider(property: "MIDI Transposition", value: Double(transposition), range: -16 ... 16, format: "%.0f" ) { sliderValue in transposition = Int(sliderValue) osc.reset() }) addView(AKSlider(property: "OSC Morph Index", value: osc.index, range: 0 ... 3) { sliderValue in osc.index = sliderValue }) addView(AKSlider(property: "OSC Gain", value: generatorBooster.gain, range: 0 ... 4) { sliderValue in generatorBooster.gain = sliderValue }) addView(AKSlider(property: "FILTER Frequency Cutoff", value: filter.cutoffFrequency, range: 1 ... 12_000 ) { sliderValue in filter.cutoffFrequency = sliderValue }) addView(AKSlider(property: "FILTER Frequency Resonance", value: filter.resonance, range: 0 ... 4 ) { sliderValue in filter.resonance = sliderValue }) addView(AKSlider(property: "OSC Amp Attack", value: osc.attackDuration, range: 0 ... 2, format: "%0.3f s" ) { sliderValue in osc.attackDuration = sliderValue }) addView(AKSlider(property: "OSC Amp Decay", value: osc.decayDuration, range: 0 ... 2, format: "%0.3f s" ) { sliderValue in osc.decayDuration = sliderValue }) addView(AKSlider(property: "OSC Amp Sustain", value: osc.sustainLevel, range: 0 ... 2, format: "%0.3f s" ) { sliderValue in osc.sustainLevel = sliderValue }) addView(AKSlider(property: "OSC Amp Release", value: osc.releaseDuration, range: 0 ... 2, format: "%0.3f s" ) { sliderValue in osc.releaseDuration = sliderValue }) addView(AKSlider(property: "Detuning Offset", value: osc.detuningOffset, range: -1_200 ... 1_200, format: "%0.1f Cents" ) { sliderValue in osc.detuningOffset = sliderValue }) addView(AKSlider(property: "Detuning Multiplier", value: osc.detuningMultiplier, range: 0.5 ... 2.0, taper: log(3) / log(2) ) { sliderValue in osc.detuningMultiplier = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
e311c787baf48af4ac4d0ece198cfed2
35.035556
125
0.635792
false
false
false
false
BalestraPatrick/Tweetometer
refs/heads/master
Carthage/Checkouts/twitter-kit-ios/DemoApp/DemoApp/Authentication/AuthenticationViewController.swift
mit
2
// // AuthenticationViewController.swift // FabricSampleApp // // Created by Steven Hepting on 8/19/15. // Copyright (c) 2015 Twitter. All rights reserved. // import UIKit extension CGRect { func offset(offsetValue: Int) -> CGRect { return self.offsetBy(dx: 0, dy: CGFloat(offsetValue)) } } @objc protocol AuthenticationViewControllerDelegate { @objc func authenticationViewControllerDidTapHome(viewController: AuthenticationViewController) } class AuthenticationViewController: UIViewController { enum Section: Int { case users case addUser } // MARK: - Public Variables weak var delegate: AuthenticationViewControllerDelegate? // MARK: - Private Variables fileprivate lazy var collectionView: UICollectionView = { [unowned self] in let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical layout.sectionInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 10.0, right: 0.0) let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = .groupTableViewBackground collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.bounces = true collectionView.alwaysBounceVertical = true collectionView.contentInset = UIEdgeInsets(top: 10.0, left: 0.0, bottom: 10.0, right: 0.0) collectionView.register(TwitterSessionCollectionViewCell.self, forCellWithReuseIdentifier: AuthenticationViewController.cellIdentifier) collectionView.register(TwitterLoginCollectionViewCell.self, forCellWithReuseIdentifier: AuthenticationViewController.loginCellIdentifier) return collectionView }() fileprivate static let cellIdentifier = "authCell" fileprivate static let loginCellIdentifier = "loginCell" fileprivate var sessionStore: TWTRSessionStore // MARK: - Init required init() { self.sessionStore = TWTRTwitter.sharedInstance().sessionStore super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() title = "Authentication" setupCollectionView() self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Home", style: .plain, target: self, action: #selector(home)) } // MARK: - Actions func home() { delegate?.authenticationViewControllerDidTapHome(viewController: self) } // MARK: - Private Methods private func setupCollectionView() { view.addSubview(collectionView) collectionView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true collectionView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true collectionView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true collectionView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true } } // MARK: - UICollectionViewDataSource extension AuthenticationViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let section = Section(rawValue: indexPath.section) { switch section { case .users: return collectionView.dequeueReusableCell(withReuseIdentifier: AuthenticationViewController.cellIdentifier, for: indexPath) case .addUser: return collectionView.dequeueReusableCell(withReuseIdentifier: AuthenticationViewController.loginCellIdentifier, for: indexPath) } } else { return collectionView.dequeueReusableCell(withReuseIdentifier: AuthenticationViewController.cellIdentifier, for: indexPath) } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let section = Section(rawValue: section) else { return 0 } switch section { case .users: return sessionStore.existingUserSessions().count case .addUser: return 1 } } func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } } // MARK: - UICollectionViewDelegate extension AuthenticationViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let section = Section(rawValue: indexPath.section) else { return } switch section { case .users: if let cell = cell as? TwitterSessionCollectionViewCell, let session = sessionStore.existingUserSessions()[indexPath.row] as? TWTRSession { cell.delegate = self cell.configure(with: session) } case .addUser: if let cell = cell as? TwitterLoginCollectionViewCell { cell.delegate = self cell.configure() } } } } // MARK: - UICollectionViewDelegateFlowLayout extension AuthenticationViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { guard let section = Section(rawValue: indexPath.section) else { return .zero } switch section { case .users: return CGSize(width: collectionView.frame.width - 20.0, height: 60.0) case .addUser: return CGSize(width: collectionView.frame.width - 20.0, height: 48.0) } } } // MARK: - TwitterLoginCollectionViewCellDelegate extension AuthenticationViewController: TwitterLoginCollectionViewCellDelegate { func loginCollectionViewCellDidTapAddAccountButton(cell: TwitterLoginCollectionViewCell) { let viewController = LoginViewController() viewController.delegate = self viewController.modalPresentationStyle = .overCurrentContext present(viewController, animated: true, completion: nil) } } // MARK: - TwitterSessionCollectionViewCellDelegate extension AuthenticationViewController: TwitterSessionCollectionViewCellDelegate { func sessionCollectionViewCell(collectionViewCell: TwitterSessionCollectionViewCell, didTapLogoutFor session: TWTRSession) { TWTRTwitter.sharedInstance().sessionStore.logOutUserID(session.userID) collectionView.reloadData() } } // MARK: - LoginViewControllerDelegate extension AuthenticationViewController: LoginViewControllerDelegate { func loginViewControllerDidClearAccounts(viewController: LoginViewController) { collectionView.reloadData() } func loginViewController(viewController: LoginViewController, didAuthWith session: TWTRSession) { collectionView.reloadData() } }
c78ed7741978e681d41e2fa73665ff33
37.362162
160
0.720445
false
false
false
false
dhanvi/firefox-ios
refs/heads/master
Client/Frontend/Browser/BrowserLocationView.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import Shared import SnapKit protocol BrowserLocationViewDelegate { func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView) func browserLocationViewDidLongPressLocation(browserLocationView: BrowserLocationView) func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView) /// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied func browserLocationViewDidLongPressReaderMode(browserLocationView: BrowserLocationView) -> Bool func browserLocationViewLocationAccessibilityActions(browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]? } struct BrowserLocationViewUX { static let HostFontColor = UIColor.blackColor() static let BaseURLFontColor = UIColor.grayColor() static let BaseURLPitch = 0.75 static let HostPitch = 1.0 static let LocationContentInset = 8 } class BrowserLocationView: UIView { var delegate: BrowserLocationViewDelegate? var longPressRecognizer: UILongPressGestureRecognizer! var tapRecognizer: UITapGestureRecognizer! dynamic var baseURLFontColor: UIColor = BrowserLocationViewUX.BaseURLFontColor { didSet { updateTextWithURL() } } dynamic var hostFontColor: UIColor = BrowserLocationViewUX.HostFontColor { didSet { updateTextWithURL() } } var url: NSURL? { didSet { let wasHidden = lockImageView.hidden lockImageView.hidden = url?.scheme != "https" if wasHidden != lockImageView.hidden { UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } updateTextWithURL() setNeedsUpdateConstraints() } } var readerModeState: ReaderModeState { get { return readerModeButton.readerModeState } set (newReaderModeState) { if newReaderModeState != self.readerModeButton.readerModeState { let wasHidden = readerModeButton.hidden self.readerModeButton.readerModeState = newReaderModeState readerModeButton.hidden = (newReaderModeState == ReaderModeState.Unavailable) if wasHidden != readerModeButton.hidden { UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } UIView.animateWithDuration(0.1, animations: { () -> Void in if newReaderModeState == ReaderModeState.Unavailable { self.readerModeButton.alpha = 0.0 } else { self.readerModeButton.alpha = 1.0 } self.setNeedsUpdateConstraints() self.layoutIfNeeded() }) } } } lazy var placeholder: NSAttributedString = { let placeholderText = NSLocalizedString("Search or enter address", comment: "The text shown in the URL bar on about:home") return NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.grayColor()]) }() lazy var urlTextField: UITextField = { let urlTextField = DisplayTextField() self.longPressRecognizer.delegate = self urlTextField.addGestureRecognizer(self.longPressRecognizer) self.tapRecognizer.delegate = self urlTextField.addGestureRecognizer(self.tapRecognizer) // Prevent the field from compressing the toolbar buttons on the 4S in landscape. urlTextField.setContentCompressionResistancePriority(250, forAxis: UILayoutConstraintAxis.Horizontal) urlTextField.attributedPlaceholder = self.placeholder urlTextField.accessibilityIdentifier = "url" urlTextField.accessibilityActionsSource = self urlTextField.font = UIConstants.DefaultMediumFont return urlTextField }() private lazy var lockImageView: UIImageView = { let lockImageView = UIImageView(image: UIImage(named: "lock_verified.png")) lockImageView.hidden = true lockImageView.isAccessibilityElement = true lockImageView.contentMode = UIViewContentMode.Center lockImageView.accessibilityLabel = NSLocalizedString("Secure connection", comment: "Accessibility label for the lock icon, which is only present if the connection is secure") return lockImageView }() private lazy var readerModeButton: ReaderModeButton = { let readerModeButton = ReaderModeButton(frame: CGRectZero) readerModeButton.hidden = true readerModeButton.addTarget(self, action: "SELtapReaderModeButton", forControlEvents: .TouchUpInside) readerModeButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: "SELlongPressReaderModeButton:")) readerModeButton.isAccessibilityElement = true readerModeButton.accessibilityLabel = NSLocalizedString("Reader View", comment: "Accessibility label for the Reader View button") readerModeButton.accessibilityCustomActions = [UIAccessibilityCustomAction(name: NSLocalizedString("Add to Reading List", comment: "Accessibility label for action adding current page to reading list."), target: self, selector: "SELreaderModeCustomAction")] return readerModeButton }() override init(frame: CGRect) { super.init(frame: frame) longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "SELlongPressLocation:") tapRecognizer = UITapGestureRecognizer(target: self, action: "SELtapLocation:") self.backgroundColor = UIColor.whiteColor() addSubview(urlTextField) addSubview(lockImageView) addSubview(readerModeButton) lockImageView.snp_makeConstraints { make in make.leading.centerY.equalTo(self) make.width.equalTo(self.lockImageView.intrinsicContentSize().width + CGFloat(BrowserLocationViewUX.LocationContentInset * 2)) } readerModeButton.snp_makeConstraints { make in make.trailing.centerY.equalTo(self) make.width.equalTo(self.readerModeButton.intrinsicContentSize().width + CGFloat(BrowserLocationViewUX.LocationContentInset * 2)) } } override var accessibilityElements: [AnyObject]! { get { return [lockImageView, urlTextField, readerModeButton].filter { !$0.hidden } } set { super.accessibilityElements = newValue } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateConstraints() { urlTextField.snp_remakeConstraints { make in make.top.bottom.equalTo(self) if lockImageView.hidden { make.leading.equalTo(self).offset(BrowserLocationViewUX.LocationContentInset) } else { make.leading.equalTo(self.lockImageView.snp_trailing) } if readerModeButton.hidden { make.trailing.equalTo(self).offset(-BrowserLocationViewUX.LocationContentInset) } else { make.trailing.equalTo(self.readerModeButton.snp_leading) } } super.updateConstraints() } func SELtapReaderModeButton() { delegate?.browserLocationViewDidTapReaderMode(self) } func SELlongPressReaderModeButton(recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { delegate?.browserLocationViewDidLongPressReaderMode(self) } } func SELlongPressLocation(recognizer: UITapGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { delegate?.browserLocationViewDidLongPressLocation(self) } } func SELtapLocation(recognizer: UITapGestureRecognizer) { delegate?.browserLocationViewDidTapLocation(self) } func SELreaderModeCustomAction() -> Bool { return delegate?.browserLocationViewDidLongPressReaderMode(self) ?? false } private func updateTextWithURL() { if let httplessURL = url?.absoluteStringWithoutHTTPScheme(), let baseDomain = url?.baseDomain() { // Highlight the base domain of the current URL. let attributedString = NSMutableAttributedString(string: httplessURL) let nsRange = NSMakeRange(0, httplessURL.characters.count) attributedString.addAttribute(NSForegroundColorAttributeName, value: baseURLFontColor, range: nsRange) attributedString.colorSubstring(baseDomain, withColor: hostFontColor) attributedString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(double: BrowserLocationViewUX.BaseURLPitch), range: nsRange) attributedString.pitchSubstring(baseDomain, withPitch: BrowserLocationViewUX.HostPitch) urlTextField.attributedText = attributedString } else { // If we're unable to highlight the domain, just use the URL as is. urlTextField.text = url?.absoluteString } } } extension BrowserLocationView: UIGestureRecognizerDelegate { func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { // If the longPressRecognizer is active, fail all other recognizers to avoid conflicts. return gestureRecognizer == longPressRecognizer } } extension BrowserLocationView: AccessibilityActionsSource { func accessibilityCustomActionsForView(view: UIView) -> [UIAccessibilityCustomAction]? { if view === urlTextField { return delegate?.browserLocationViewLocationAccessibilityActions(self) } return nil } } private class ReaderModeButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) setImage(UIImage(named: "reader.png"), forState: UIControlState.Normal) setImage(UIImage(named: "reader_active.png"), forState: UIControlState.Selected) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var _readerModeState: ReaderModeState = ReaderModeState.Unavailable var readerModeState: ReaderModeState { get { return _readerModeState; } set (newReaderModeState) { _readerModeState = newReaderModeState switch _readerModeState { case .Available: self.enabled = true self.selected = false case .Unavailable: self.enabled = false self.selected = false case .Active: self.enabled = true self.selected = true } } } } private class DisplayTextField: UITextField { weak var accessibilityActionsSource: AccessibilityActionsSource? override var accessibilityCustomActions: [UIAccessibilityCustomAction]? { get { return accessibilityActionsSource?.accessibilityCustomActionsForView(self) } set { super.accessibilityCustomActions = newValue } } private override func canBecomeFirstResponder() -> Bool { return false } }
44edd6c5ba28bb76dc55a405a6bb9487
40.646853
264
0.691126
false
false
false
false
superk589/CGSSGuide
refs/heads/master
DereGuide/Controller/BaseFilterSortController.swift
mit
2
// // BaseFilterSortController.swift // DereGuide // // Created by zzk on 2017/1/12. // Copyright © 2017 zzk. All rights reserved. // import UIKit import SnapKit class BaseFilterSortController: BaseViewController, UITableViewDelegate, UITableViewDataSource { let toolbar = UIToolbar() let tableView = UITableView() override func viewDidLoad() { super.viewDidLoad() tableView.register(FilterTableViewCell.self, forCellReuseIdentifier: "FilterCell") tableView.register(SortTableViewCell.self, forCellReuseIdentifier: "SortCell") tableView.delegate = self tableView.dataSource = self tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 44, right: 0) tableView.tableFooterView = UIView(frame: .zero) tableView.estimatedRowHeight = 50 tableView.cellLayoutMarginsFollowReadableWidth = false view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.left.right.bottom.equalToSuperview() make.top.equalTo(topLayoutGuide.snp.bottom) } toolbar.tintColor = .parade view.addSubview(toolbar) toolbar.snp.makeConstraints { (make) in if #available(iOS 11.0, *) { make.left.right.equalToSuperview() make.bottom.equalTo(view.safeAreaLayoutGuide) } else { make.bottom.left.right.equalToSuperview() } make.height.equalTo(44) } let leftSpaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) leftSpaceItem.width = 0 let doneItem = UIBarButtonItem(title: NSLocalizedString("完成", comment: "导航栏按钮"), style: .done, target: self, action: #selector(doneAction)) let middleSpaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let resetItem = UIBarButtonItem(title: NSLocalizedString("重置", comment: "导航栏按钮"), style: .plain, target: self, action: #selector(resetAction)) let rightSpaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) rightSpaceItem.width = 0 toolbar.setItems([leftSpaceItem, resetItem, middleSpaceItem, doneItem, rightSpaceItem], animated: false) } @objc func doneAction() { } @objc func resetAction() { } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { [weak self] (context) in // since the size changes, update all table cells to fit the new size self?.tableView.beginUpdates() self?.tableView.endUpdates() }, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return UITableViewCell() } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return NSLocalizedString("筛选", comment: "") } else { return NSLocalizedString("排序", comment: "") } } }
3b2664b956f214cdacdd0d3ad588090d
34.634615
150
0.644091
false
false
false
false
manavgabhawala/swift
refs/heads/master
test/SILGen/implicitly_unwrapped_optional.swift
apache-2.0
1
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s func foo(f f: (() -> ())!) { var f: (() -> ())! = f f?() } // CHECK: sil hidden @{{.*}}foo{{.*}} : $@convention(thin) (@owned Optional<@callee_owned () -> ()>) -> () { // CHECK: bb0([[T0:%.*]] : $Optional<@callee_owned () -> ()>): // CHECK: [[F:%.*]] = alloc_box ${ var Optional<@callee_owned () -> ()> } // CHECK: [[PF:%.*]] = project_box [[F]] // CHECK: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK: [[T0_COPY:%.*]] = copy_value [[BORROWED_T0]] // CHECK: store [[T0_COPY]] to [init] [[PF]] // CHECK: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK: [[T1:%.*]] = select_enum_addr [[PF]] // CHECK: cond_br [[T1]], bb1, bb3 // If it does, project and load the value out of the implicitly unwrapped // optional... // CHECK: bb1: // CHECK-NEXT: [[FN0_ADDR:%.*]] = unchecked_take_enum_data_addr [[PF]] // CHECK-NEXT: [[FN0:%.*]] = load [copy] [[FN0_ADDR]] // .... then call it // CHECK: apply [[FN0]]() : $@callee_owned () -> () // CHECK: br bb2 // CHECK: bb2( // CHECK: destroy_value [[F]] // CHECK: destroy_value [[T0]] // CHECK: return // CHECK: bb3: // CHECK: enum $Optional<()>, #Optional.none!enumelt // CHECK: br bb2 // The rest of this is tested in optional.swift // } // end sil function '{{.*}}foo{{.*}}' func wrap<T>(x x: T) -> T! { return x } // CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional16wrap_then_unwrap{{[_0-9a-zA-Z]*}}F func wrap_then_unwrap<T>(x x: T) -> T { // CHECK: switch_enum_addr {{%.*}}, case #Optional.some!enumelt.1: [[OK:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL:bb[0-9]+]] // CHECK: [[FAIL]]: // CHECK: unreachable // CHECK: [[OK]]: return wrap(x: x)! } // CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional10tuple_bindSSSgSQySi_SStG1x_tF : $@convention(thin) (@owned Optional<(Int, String)>) -> @owned Optional<String> { func tuple_bind(x x: (Int, String)!) -> String? { return x?.1 // CHECK: cond_br {{%.*}}, [[NONNULL:bb[0-9]+]], [[NULL:bb[0-9]+]] // CHECK: [[NONNULL]]: // CHECK: [[STRING:%.*]] = tuple_extract {{%.*}} : $(Int, String), 1 // CHECK-NOT: destroy_value [[STRING]] } // CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional011tuple_bind_a1_B0SSSQySi_SStG1x_tF func tuple_bind_implicitly_unwrapped(x x: (Int, String)!) -> String { return x.1 } func return_any() -> AnyObject! { return nil } func bind_any() { let object : AnyObject? = return_any() } // CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional6sr3758yyF func sr3758() { // Verify that there are no additional reabstractions introduced. // CHECK: [[CLOSURE:%.+]] = function_ref @_T029implicitly_unwrapped_optional6sr3758yyFySQyypGcfU_ : $@convention(thin) (@in Optional<Any>) -> () // CHECK: [[F:%.+]] = thin_to_thick_function [[CLOSURE]] : $@convention(thin) (@in Optional<Any>) -> () to $@callee_owned (@in Optional<Any>) -> () // CHECK: [[BORROWED_F:%.*]] = begin_borrow [[F]] // CHECK: [[CALLEE:%.+]] = copy_value [[BORROWED_F]] : $@callee_owned (@in Optional<Any>) -> () // CHECK: = apply [[CALLEE]]({{%.+}}) : $@callee_owned (@in Optional<Any>) -> () // CHECK: end_borrow [[BORROWED_F]] from [[F]] // CHECK: destroy_value [[F]] let f: ((Any?) -> Void) = { (arg: Any!) in } f(nil) } // CHECK: end sil function '_T029implicitly_unwrapped_optional6sr3758yyF'
651a3469be3578a437080d68a23ecd19
43.324675
176
0.586288
false
false
false
false
kperryua/swift
refs/heads/master
test/IDE/complete_at_top_level.swift
apache-2.0
3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_1 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_2 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_3 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_4 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_5 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_6 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_KW_1 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_KW_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_INIT_1 > %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_INIT_1 < %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_INIT_1_NEGATIVE < %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_INIT_2 | %FileCheck %s -check-prefix=TOP_LEVEL_VAR_INIT_2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PLAIN_TOP_LEVEL_1 > %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL_NO_DUPLICATES < %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PLAIN_TOP_LEVEL_2 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PLAIN_TOP_LEVEL_2 | %FileCheck %s -check-prefix=NEGATIVE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_CLOSURE_1 | %FileCheck %s -check-prefix=TOP_LEVEL_CLOSURE_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_1 > %t.toplevel.1.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.1.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.1.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.1.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_2 > %t.toplevel.2.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.2.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.2.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.2.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_3 > %t.toplevel.3.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.3.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.3.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.3.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_4 > %t.toplevel.4.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.4.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.4.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.4.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_5 > %t.toplevel.5.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.5.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.5.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.5.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_5 > %t.toplevel.5.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.5.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.5.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.5.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_6 > %t.toplevel.6.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.6.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.6.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.6.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_1 > %t.toplevel-expr.1.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.1.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.1.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.1.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_2 > %t.toplevel-expr.2.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.2.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.2.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.2.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_3 > %t.toplevel-expr.3.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.3.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.3.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.3.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_4 > %t.toplevel-expr.4.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.4.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.4.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.4.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_2 > %t.toplevel-expr.2.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.2.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.2.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.2.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_1 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_2 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_3 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_4 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_5 > %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_STMT_5 < %t.toplevel.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_6 > %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_STMT_6 < %t.toplevel.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_7 > %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_STMT_7 < %t.toplevel.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_8 > %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt // RUN: %FileCheck %s -check-prefix=TOP_LEVEL_STMT_8 < %t.toplevel.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_9 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_10 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_AUTOCLOSURE_1 | %FileCheck %s -check-prefix=AUTOCLOSURE_STRING // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_SWITCH_CASE_1 | %FileCheck %s -check-prefix=TOP_LEVEL_SWITCH_CASE_1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_BEFORE_GUARD_NAME_1 | %FileCheck %s -check-prefix=TOP_LEVEL_BEFORE_GUARD_NAME // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_BEFORE_GUARD_NAME_2 | %FileCheck %s -check-prefix=TOP_LEVEL_BEFORE_GUARD_NAME // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_GUARD_1 | %FileCheck %s -check-prefix=TOP_LEVEL_GUARD // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_GUARD_2 | %FileCheck %s -check-prefix=TOP_LEVEL_GUARD // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRING_INTERP_1 | %FileCheck %s -check-prefix=STRING_INTERP // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRING_INTERP_2 | %FileCheck %s -check-prefix=STRING_INTERP // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRING_INTERP_3 | %FileCheck %s -check-prefix=STRING_INTERP // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRING_INTERP_4 | %FileCheck %s -check-prefix=STRING_INTERP // Test code completion in top-level code. // // This test is not meant to test that we can correctly form all kinds of // completion results in general; that should be tested elsewhere. struct FooStruct { var instanceVar = 0 func instanceFunc(_ a: Int) {} // Add more stuff as needed. } var fooObject : FooStruct func fooFunc1() {} func fooFunc2(_ a: Int, _ b: Double) {} func erroneous1(_ x: Undeclared) {} //===--- Test code completions of expressions that can be typechecked. // Although the parser can recover in most of these test cases, we resync it // anyway to ensure that there parser recovery does not interfere with code // completion. func resyncParser1() {} fooObject#^TYPE_CHECKED_EXPR_1^# // TYPE_CHECKED_EXPR_1: Begin completions // TYPE_CHECKED_EXPR_1-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}} // TYPE_CHECKED_EXPR_1-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}} // TYPE_CHECKED_EXPR_1-NEXT: BuiltinOperator/None: = {#FooStruct#}[#Void#]; // TYPE_CHECKED_EXPR_1-NEXT: End completions func resyncParser2() {} // Test that we can code complete after a top-level var decl. var _tmpVar1 : FooStruct fooObject#^TYPE_CHECKED_EXPR_2^# // TYPE_CHECKED_EXPR_2: Begin completions // TYPE_CHECKED_EXPR_2-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}} // TYPE_CHECKED_EXPR_2-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}} // TYPE_CHECKED_EXPR_2-NEXT: BuiltinOperator/None: = {#FooStruct#}[#Void#]; // TYPE_CHECKED_EXPR_2-NEXT: End completions func resyncParser3() {} fooObject#^TYPE_CHECKED_EXPR_3^#.bar // TYPE_CHECKED_EXPR_3: Begin completions // TYPE_CHECKED_EXPR_3-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}} // TYPE_CHECKED_EXPR_3-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}} // TYPE_CHECKED_EXPR_3-NEXT: BuiltinOperator/None: = {#FooStruct#}[#Void#]; // TYPE_CHECKED_EXPR_3-NEXT: End completions func resyncParser4() {} fooObject.#^TYPE_CHECKED_EXPR_4^# // TYPE_CHECKED_EXPR_4: Begin completions // TYPE_CHECKED_EXPR_4-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // TYPE_CHECKED_EXPR_4-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}} // TYPE_CHECKED_EXPR_4-NEXT: End completions func resyncParser5() {} fooObject.#^TYPE_CHECKED_EXPR_5^#.bar // TYPE_CHECKED_EXPR_5: Begin completions // TYPE_CHECKED_EXPR_5-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // TYPE_CHECKED_EXPR_5-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}} // TYPE_CHECKED_EXPR_5-NEXT: End completions func resyncParser6() {} fooObject.instanceFunc(#^TYPE_CHECKED_EXPR_6^# func resyncParser6() {} fooObject.is#^TYPE_CHECKED_EXPR_KW_1^# // TYPE_CHECKED_EXPR_KW_1: found code completion token // TYPE_CHECKED_EXPR_KW_1-NOT: Begin completions func resyncParser7() {} // We have an error in the initializer here, but the type is explicitly written // in the source. var fooObjectWithErrorInInit : FooStruct = unknown_var fooObjectWithErrorInInit.#^TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1^# // TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1: Begin completions // TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}} // TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1-NEXT: End completions func resyncParser6a() {} var topLevelVar1 = #^TOP_LEVEL_VAR_INIT_1^# // TOP_LEVEL_VAR_INIT_1: Begin completions // TOP_LEVEL_VAR_INIT_1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // TOP_LEVEL_VAR_INIT_1-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#]{{; name=.+$}} // TOP_LEVEL_VAR_INIT_1-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}} // TOP_LEVEL_VAR_INIT_1: End completions // Check that the variable itself does not show up. // TOP_LEVEL_VAR_INIT_1_NEGATIVE-NOT: topLevelVar1 func resyncParser7() {} var topLevelVar2 = FooStruct#^TOP_LEVEL_VAR_INIT_2^# // TOP_LEVEL_VAR_INIT_2: Begin completions // TOP_LEVEL_VAR_INIT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#self: FooStruct#})[#(Int) -> Void#]{{; name=.+$}} // TOP_LEVEL_VAR_INIT_2-NEXT: Decl[Constructor]/CurrNominal: ({#instanceVar: Int#})[#FooStruct#]{{; name=.+$}} // TOP_LEVEL_VAR_INIT_2-NEXT: Decl[Constructor]/CurrNominal: ()[#FooStruct#]{{; name=.+$}} // TOP_LEVEL_VAR_INIT_2-NEXT: End completions func resyncParser8() {} #^PLAIN_TOP_LEVEL_1^# // PLAIN_TOP_LEVEL: Begin completions // PLAIN_TOP_LEVEL-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // PLAIN_TOP_LEVEL-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}} // PLAIN_TOP_LEVEL: End completions // PLAIN_TOP_LEVEL_NO_DUPLICATES: Begin completions // PLAIN_TOP_LEVEL_NO_DUPLICATES-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#]{{; name=.+$}} // PLAIN_TOP_LEVEL_NO_DUPLICATES-DAG: Decl[FreeFunction]/CurrModule: fooFunc2({#(a): Int#}, {#(b): Double#})[#Void#]{{; name=.+$}} // PLAIN_TOP_LEVEL_NO_DUPLICATES-NOT: fooFunc1 // PLAIN_TOP_LEVEL_NO_DUPLICATES-NOT: fooFunc2 // PLAIN_TOP_LEVEL_NO_DUPLICATES: End completions func resyncParser9() {} // Test that we can code complete immediately after a decl with a syntax error. func _tmpFuncWithSyntaxError() { if return } #^PLAIN_TOP_LEVEL_2^# func resyncParser10() {} _ = { #^TOP_LEVEL_CLOSURE_1^# }() // TOP_LEVEL_CLOSURE_1: Begin completions // TOP_LEVEL_CLOSURE_1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // TOP_LEVEL_CLOSURE_1-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#]{{; name=.+$}} // TOP_LEVEL_CLOSURE_1-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}} // TOP_LEVEL_CLOSURE_1: End completions func resyncParser11() {} //===--- Test code completions of types. func resyncParserA1() {} var topLevelVarType1 : #^TOP_LEVEL_VAR_TYPE_1^# // TOP_LEVEL_VAR_TYPE_1: Begin completions // TOP_LEVEL_VAR_TYPE_1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // TOP_LEVEL_VAR_TYPE_1: End completions // TOP_LEVEL_VAR_TYPE_NEGATIVE_1-NOT: Decl[GlobalVar // TOP_LEVEL_VAR_TYPE_NEGATIVE_1-NOT: Decl[FreeFunc func resyncParserA1_1() {} var topLevelVarType2 : [#^TOP_LEVEL_VAR_TYPE_2^#] func resyncParserA1_2() {} var topLevelVarType3 : [#^TOP_LEVEL_VAR_TYPE_3^#: Int] func resyncParserA1_3() {} var topLevelVarType4 : [Int: #^TOP_LEVEL_VAR_TYPE_4^#] func resyncParserA1_4() {} if let topLevelVarType5 : [#^TOP_LEVEL_VAR_TYPE_5^#] {} func resyncParserA1_5() {} guard let topLevelVarType6 : [#^TOP_LEVEL_VAR_TYPE_6^#] else {} func resyncParserA1_6() {} _ = ("a" as #^TOP_LEVEL_EXPR_TYPE_1^#) func resyncParserA1_7() {} _ = ("a" as! #^TOP_LEVEL_EXPR_TYPE_2^#) func resyncParserA1_8() {} _ = ("a" as? #^TOP_LEVEL_EXPR_TYPE_3^#) func resyncParserA1_9() {} _ = ("a" is #^TOP_LEVEL_EXPR_TYPE_4^#) func resyncParserA2() {} //===--- Test code completion in statements. func resyncParserB1() {} if (true) { #^TOP_LEVEL_STMT_1^# } func resyncParserB2() {} while (true) { #^TOP_LEVEL_STMT_2^# } func resyncParserB3() {} repeat { #^TOP_LEVEL_STMT_3^# } while true func resyncParserB4() {} for ; ; { #^TOP_LEVEL_STMT_4^# } func resyncParserB5() {} for var i = 0; ; { #^TOP_LEVEL_STMT_5^# // TOP_LEVEL_STMT_5: Begin completions // TOP_LEVEL_STMT_5: Decl[LocalVar]/Local: i[#Int#]{{; name=.+$}} // TOP_LEVEL_STMT_5: End completions } func resyncParserB6() {} for i in [] { #^TOP_LEVEL_STMT_6^# // TOP_LEVEL_STMT_6: Begin completions // TOP_LEVEL_STMT_6: Decl[LocalVar]/Local: i[#Any#]{{; name=.+$}} // TOP_LEVEL_STMT_6: End completions } func resyncParserB7() {} for i in [1, 2, 3] { #^TOP_LEVEL_STMT_7^# // TOP_LEVEL_STMT_7: Begin completions // TOP_LEVEL_STMT_7: Decl[LocalVar]/Local: i[#Int#]{{; name=.+$}} // TOP_LEVEL_STMT_7: End completions } func resyncParserB8() {} for i in unknown_var { #^TOP_LEVEL_STMT_8^# // TOP_LEVEL_STMT_8: Begin completions // TOP_LEVEL_STMT_8: Decl[LocalVar]/Local: i[#<<error type>>#]{{; name=.+$}} // TOP_LEVEL_STMT_8: End completions } func resyncParserB9() {} switch (0, 42) { case (0, 0): #^TOP_LEVEL_STMT_9^# } func resyncParserB10() {} // rdar://20738314 if true { var z = #^TOP_LEVEL_STMT_10^# } else { assertionFailure("Shouldn't be here") } func resyncParserB11() {} // rdar://21346928 func optStr() -> String? { return nil } let x = (optStr() ?? "autoclosure").#^TOP_LEVEL_AUTOCLOSURE_1^# // AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: utf16[#String.UTF16View#] // AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: characters[#String.CharacterView#] // AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: utf8[#String.UTF8View#] func resyncParserB12() {} // rdar://21661308 switch 1 { case #^TOP_LEVEL_SWITCH_CASE_1^# } // TOP_LEVEL_SWITCH_CASE_1: Begin completions func resyncParserB13() {} #^TOP_LEVEL_BEFORE_GUARD_NAME_1^# // TOP_LEVEL_BEFORE_GUARD_NAME-NOT: name=guardedName guard let guardedName = 1 as Int? { #^TOP_LEVEL_BEFORE_GUARD_NAME_2^# } #^TOP_LEVEL_GUARD_1^# func interstitial() {} #^TOP_LEVEL_GUARD_2^# // TOP_LEVEL_GUARD: Decl[LocalVar]/Local: guardedName[#Int#]; name=guardedName func resyncParserB14() {} "\(#^STRING_INTERP_1^#)" "\(1) \(#^STRING_INTERP_2^#) \(2)" var stringInterp = "\(#^STRING_INTERP_3^#)" _ = "" + "\(#^STRING_INTERP_4^#)" + "" // STRING_INTERP: Begin completions // STRING_INTERP-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]; // STRING_INTERP-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#]; // STRING_INTERP-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#]; // STRING_INTERP: End completions func resyncParserC1() {} // //===--- DON'T ADD ANY TESTS AFTER THIS LINE. // // These declarations should not show up in top-level code completion results // because forward references are not allowed at the top level. struct StructAtEOF {} // NEGATIVE-NOT: StructAtEOF extension FooStruct { func instanceFuncAtEOF() {} // NEGATIVE-NOT: instanceFuncAtEOF } var varAtEOF : Int // NEGATIVE-NOT: varAtEOF
051e1d035e1d0640b0490c341c33a509
44.982495
198
0.707386
false
true
false
false
Killectro/GiphySearch
refs/heads/master
GiphySearch/GiphySearch/View Controllers/Trending/TrendingViewController.swift
mit
1
// // TrendingViewController.swift // GiphySearch // // Created by DJ Mitchell on 8/17/16. // Copyright © 2016 Killectro. All rights reserved. // import UIKit import RxCocoa import RxSwift import NSObject_Rx import Moya import Moya_ObjectMapper final class TrendingViewController: UIViewController { // MARK: - Public Properties var viewModel: TrendingDisplayable! // MARK: - Private Properties fileprivate let startLoadingOffset: CGFloat = 20.0 @IBOutlet fileprivate var noResultsView: UIView! @IBOutlet var sadFaceImage: UIImageView! { didSet { sadFaceImage.tintColor = UIColor(red: 146/255, green: 146/255, blue: 146/255, alpha: 1.0) } } @IBOutlet fileprivate var tableView: UITableView! @IBOutlet fileprivate var searchBar: UISearchBar! // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() setupBindings() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // SDWebImage automatically wipes mem cache when it receives a mem warning so do nothing here } } // MARK: - Setup private extension TrendingViewController { func setupBindings() { setupViewModel() setupKeyboard() } func setupViewModel() { let searchText = searchBar.rx.text.orEmpty .throttle(0.3, scheduler: MainScheduler.instance) .distinctUntilChanged() .shareReplay(1) let paginate = tableView.rx .contentOffset .filter { [weak self] offset in guard let `self` = self else { return false } return self.tableView.isNearBottom(threshold: self.startLoadingOffset) } .flatMap { _ in return Observable.just() } viewModel.setupObservables(paginate: paginate, searchText: searchText) // Bind our table view to our result GIFs once we set up our view model setupTableView() } func setupTableView() { // Bind gifs to table view cells viewModel.gifs .bindTo( tableView.rx.items(cellIdentifier: "gifCell", cellType: GifTableViewCell.self), curriedArgument: configureTableCell ) .addDisposableTo(rx_disposeBag) viewModel.gifs .map { gifs in gifs.count != 0 } .bindTo(noResultsView.rx.isHidden) .addDisposableTo(rx_disposeBag) } func setupKeyboard() { // Hide the keyboard when we're scrolling tableView.rx.contentOffset.subscribe(onNext: { [weak self] _ in guard let `self` = self else { return } if self.searchBar.isFirstResponder { self.searchBar.resignFirstResponder() } }) .addDisposableTo(rx_disposeBag) } func configureTableCell(_ row: Int, viewModel: GifDisplayable, cell: GifTableViewCell) { cell.viewModel = viewModel } }
37572b966c5d27a284b56aa049ef0856
27.875
101
0.630703
false
false
false
false
pixyzehn/MediumScrollFullScreen
refs/heads/master
MediumScrollFullScreen-Sample/MediumScrollFullScreen-Sample/WebViewController.swift
mit
1
// // ViewController.swift // MediumScrollFullScreen-Sample // // Created by pixyzehn on 2/24/15. // Copyright (c) 2015 pixyzehn. All rights reserved. // import UIKit class WebViewController: UIViewController { enum State { case Showing case Hiding } @IBOutlet weak var webView: UIWebView! var statement: State = .Hiding var scrollProxy: MediumScrollFullScreen? var scrollView: UIScrollView? var enableTap = false override func viewDidLoad() { super.viewDidLoad() scrollProxy = MediumScrollFullScreen(forwardTarget: webView) webView.scrollView.delegate = scrollProxy scrollProxy?.delegate = self as MediumScrollFullScreenDelegate webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://nshipster.com/swift-collection-protocols/")!)) let screenTap = UITapGestureRecognizer(target: self, action: "tapGesture:") screenTap.delegate = self webView.addGestureRecognizer(screenTap) // NOTE: Add temporary item navigationItem.hidesBackButton = true let menuColor = UIColor(red:0.2, green:0.2, blue:0.2, alpha:1) let backButton = UIBarButtonItem(image: UIImage(named: "back_arrow"), style: .Plain, target: self, action: "popView") backButton.tintColor = menuColor navigationItem.leftBarButtonItem = backButton let rightButton = UIButton(type: .Custom) rightButton.frame = CGRectMake(0, 0, 60, 60) rightButton.addTarget(self, action: "changeIcon:", forControlEvents: .TouchUpInside) rightButton.setImage(UIImage(named: "star_n"), forState: .Normal) rightButton.setImage(UIImage(named: "star_s"), forState: .Selected) navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton) let favButton = UIButton(type: .Custom) favButton.frame = CGRectMake(0, 0, 60, 60) favButton.addTarget(self, action: "changeIcon:", forControlEvents: .TouchUpInside) favButton.setImage(UIImage(named: "fav_n"), forState: .Normal) favButton.setImage(UIImage(named: "fav_s"), forState: .Selected) let toolItem: UIBarButtonItem = UIBarButtonItem(customView: favButton) let timeLabel = UILabel(frame: CGRectMake(0, 0, 100, 20)) timeLabel.text = "?? min left" timeLabel.textAlignment = .Center timeLabel.tintColor = menuColor let timeButton = UIBarButtonItem(customView: timeLabel as UIView) let actionButton = UIBarButtonItem(barButtonSystemItem: .Action, target: nil, action: nil) actionButton.tintColor = menuColor let gap = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil) fixedSpace.width = 20 toolbarItems = [toolItem, gap, timeButton, gap, actionButton, fixedSpace] } func changeIcon(sender: UIButton) { sender.selected = !sender.selected } func popView() { navigationController?.popViewControllerAnimated(true) } func tapGesture(sender: UITapGestureRecognizer) { if !enableTap { return } if statement == .Hiding { statement = .Showing showNavigationBar() showToolbar() } else { statement = .Hiding hideNavigationBar() hideToolbar() } } } extension WebViewController: UIGestureRecognizerDelegate { func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } extension WebViewController: MediumScrollFullScreenDelegate { func scrollFullScreen(fullScreenProxy: MediumScrollFullScreen, scrollViewDidScrollUp deltaY: CGFloat, userInteractionEnabled enabled: Bool) { enableTap = enabled ? false : true moveNavigationBar(deltaY: deltaY) moveToolbar(deltaY: -deltaY) } func scrollFullScreen(fullScreenProxy: MediumScrollFullScreen, scrollViewDidScrollDown deltaY: CGFloat, userInteractionEnabled enabled: Bool) { enableTap = enabled ? false : true if enabled { moveNavigationBar(deltaY: deltaY) hideToolbar() } else { moveNavigationBar(deltaY: -deltaY) moveToolbar(deltaY: deltaY) } } func scrollFullScreenScrollViewDidEndDraggingScrollUp(fullScreenProxy: MediumScrollFullScreen, userInteractionEnabled enabled: Bool) { statement = .Hiding hideNavigationBar() hideToolbar() } func scrollFullScreenScrollViewDidEndDraggingScrollDown(fullScreenProxy: MediumScrollFullScreen, userInteractionEnabled enabled: Bool) { if enabled { statement = .Showing showNavigationBar() hideToolbar() } else { statement = .Hiding hideNavigationBar() hideToolbar() } } }
8595786486985b9e317705fe3e079a8d
35.517483
147
0.658368
false
false
false
false
LeeShiYoung/LSYWeibo
refs/heads/master
LSYWeiBo/Profile/ProfileTableViewController.swift
artistic-2.0
1
// // ProfileTableViewController.swift // LSYWeiBo // // Created by 李世洋 on 16/5/1. // Copyright © 2016年 李世洋. All rights reserved. // import UIKit class ProfileTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() if !login { visitorView?.setupVisitorInfo(false, iconStr: "visitordiscover_image_profile", text: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人") } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
85c02c610d2fe359c5940e5cca73591b
31.087912
157
0.677055
false
false
false
false
ProcedureKit/ProcedureKit
refs/heads/development
Sources/TestingProcedureKit/TestableNetworkReachability.swift
mit
2
// // ProcedureKit // // Copyright © 2015-2018 ProcedureKit. All rights reserved. // import Foundation import SystemConfiguration import XCTest import ProcedureKit public class TestableNetworkReachability { typealias Reachability = String public var flags: SCNetworkReachabilityFlags { get { return stateLock.withCriticalScope { _flags } } set { stateLock.withCriticalScope { _flags = newValue } } } public var didStartNotifier: Bool { get { return stateLock.withCriticalScope { _didStartNotifier } } set { stateLock.withCriticalScope { _didStartNotifier = newValue } } } public var didStopNotifier: Bool { get { return stateLock.withCriticalScope { _didStopNotifier } } set { stateLock.withCriticalScope { _didStopNotifier = newValue } } } public var log: LogChannel { get { return stateLock.withCriticalScope { _log } } set { stateLock.withCriticalScope { _log = newValue } } } public weak var delegate: NetworkReachabilityDelegate? { get { return stateLock.withCriticalScope { _delegate } } set { stateLock.withCriticalScope { _delegate = newValue } } } private var stateLock = NSRecursiveLock() private var _flags: SCNetworkReachabilityFlags = .reachable { didSet { delegate?.didChangeReachability(flags: flags) } } private var _didStartNotifier = false private var _didStopNotifier = false private var _log: LogChannel = Log.Channel<Log>() private weak var _delegate: NetworkReachabilityDelegate? public init() { } } extension TestableNetworkReachability: NetworkReachability { public func startNotifier(onQueue queue: DispatchQueue) throws { log.message("Started Reachability Notifier") didStartNotifier = true delegate?.didChangeReachability(flags: flags) } public func stopNotifier() { log.message("Stopped Reachability Notifier") didStopNotifier = true } }
6392bf2d5654d098c9cb72b0c9349857
26.192771
72
0.61276
false
false
false
false
NoryCao/zhuishushenqi
refs/heads/master
zhuishushenqi/TXTReader/BookDetail/Models/BookDetail.swift
mit
1
// // BookDetail.swift // zhuishushenqi // // Created by Nory Cao on 16/10/4. // Copyright © 2016年 QS. All rights reserved. // import UIKit import HandyJSON import SQLite //let db = try? Connection("path/to/db.sqlite3") // //let users = Table("users") //let id = Expression<Int64>("id") //let name = Expression<String?>("name") //let email = Expression<String>("email") // //try? db?.run(users.create { t in // t.column(id, primaryKey: true) // t.column(name) // t.column(email, unique: true) //}) //// CREATE TABLE "users" ( //// "id" INTEGER PRIMARY KEY NOT NULL, //// "name" TEXT, //// "email" TEXT NOT NULL UNIQUE //// ) // //let insert = users.insert(name <- "Alice", email <- "alice@mac.com") //let rowid = try? db?.run(insert) //// INSERT INTO "users" ("name", "email") VALUES ('Alice', 'alice@mac.com') // //for user in try? db?.prepare(users) { // print("id: \(user[id]), name: \(user[name]), email: \(user[email])") // // id: 1, name: Optional("Alice"), email: alice@mac.com //} //// SELECT * FROM "users" // //let alice = users.filter(id == rowid) // //try? db.run(alice.update(email <- email.replace("mac.com", with: "me.com"))) //// UPDATE "users" SET "email" = replace("email", 'mac.com', 'me.com') //// WHERE ("id" = 1) // //try? db?.run(alice.delete()) //// DELETE FROM "users" WHERE ("id" = 1) // //try? db?.scalar(users.count) // 0 //// SELECT count(*) FROM "users" extension BookDetail:DBSaveProtocol { func db_save(){ let homePath = NSHomeDirectory() let dbPath = "\(homePath)/db.sqlite3" if let db = try? Connection(dbPath) { let detail = Table("BookDetail") let author = Expression<String>("author") let cover = Expression<String>("cover") let creater = Expression<String>("creater") let longIntro = Expression<String>("longIntro") let title = Expression<String>("title") let cat = Expression<String>("cat") let majorCate = Expression<String>("majorCate") let minorCate = Expression<String>("minorCate") let latelyFollower = Expression<String>("latelyFollower") let retentionRatio = Expression<String>("retentionRatio") let serializeWordCount = Expression<String>("serializeWordCount") let wordCount = Expression<String>("wordCount") let updated = Expression<String>("updated") let tags = Expression<String>("tags") let id = Expression<String>("_id") let postCount = Expression<Int>("postCount") let copyright = Expression<String>("copyright") let sourceIndex = Expression<Int>("sourceIndex") let record = Expression<String>("record") let chapter = Expression<Int>("chapter") let page = Expression<Int>("page") let resources = Expression<String>("resources") let chapters = Expression<String>("chapters") let chaptersInfo = Expression<String>("chaptersInfo") let isUpdated = Expression<Int>("isUpdated") let book = Expression<String>("book") let updateInfo = Expression<String>("updateInfo") _ = try? db.run(detail.create(temporary: false, ifNotExists: true, withoutRowid: true) { (t) in t.column(id, primaryKey: true) t.column(author) t.column(cover) t.column(creater) t.column(longIntro) t.column(title) t.column(cat) t.column(majorCate) t.column(minorCate) t.column(latelyFollower) t.column(retentionRatio) t.column(serializeWordCount) t.column(wordCount) t.column(updated) t.column(tags) t.column(postCount) t.column(copyright) t.column(sourceIndex) t.column(record) t.column(chapter) t.column(page) t.column(resources) t.column(chapters) t.column(chaptersInfo) t.column(isUpdated) t.column(book) t.column(updateInfo) }) } } } @objc(BookDetail) class BookDetail: NSObject,NSCoding ,HandyJSON{ var _id:String = "" var author:String = "" var cover:String = "" var creater:String = "" var longIntro:String = "" var title:String = "" var cat:String = "" var majorCate:String = "" var minorCate:String = "" var latelyFollower:String = "" var retentionRatio:String = "" var serializeWordCount:String = ""//每天更新字数 var wordCount:String = "" var updated:String = ""//更新时间 var tags:NSArray? var postCount:Int = 0 var copyright:String = "" var sourceIndex:Int = 1 //当前选择的源 // 阅读记录, var record:QSRecord? // 废弃 var chapter:Int = 0 //最后阅读的章节 var page:Int = 0 //最后阅读的页数 var resources:[ResourceModel]? var chapters:[NSDictionary]? // 新的代码完成后去掉 var chaptersInfo:[ZSChapterInfo]? // 代替chapters var isUpdated:Bool = false //是否存在更新,如果存在更新,进入书籍后修改状态 // book 一直存在,默认初始化,不保存任何章节 var book:QSBook! // 书架缓存状态 var bookCacheState:SwipeCellState = .none //更新信息 var updateInfo:BookShelf? required init?(coder aDecoder: NSCoder) { super.init() self._id = aDecoder.decodeObject(forKey: "_id") as? String ?? "" self.author = aDecoder.decodeObject(forKey: "author") as? String ?? "" self.cover = aDecoder.decodeObject(forKey: "cover") as? String ?? "" self.creater = aDecoder.decodeObject(forKey: "creater") as? String ?? "" self.longIntro = aDecoder.decodeObject(forKey: "longIntro") as? String ?? "" self.title = aDecoder.decodeObject(forKey: "title") as? String ?? "" self.cat = aDecoder.decodeObject(forKey: "cat") as? String ?? "" self.majorCate = aDecoder.decodeObject(forKey: "majorCate") as? String ?? "" self.minorCate = aDecoder.decodeObject(forKey: "minorCate") as? String ?? "" self.latelyFollower = aDecoder.decodeObject(forKey: "latelyFollower") as? String ?? "" self.retentionRatio = aDecoder.decodeObject(forKey: "retentionRatio") as? String ?? "" self.serializeWordCount = aDecoder.decodeObject(forKey: "serializeWordCount") as? String ?? "" self.wordCount = aDecoder.decodeObject(forKey: "wordCount") as? String ?? "" self.updated = aDecoder.decodeObject(forKey: "updated") as? String ?? "" self.tags = aDecoder.decodeObject(forKey: "tags") as? NSArray self.updateInfo = aDecoder.decodeObject(forKey: "updateInfo") as? BookShelf self.chapter = aDecoder.decodeInteger(forKey:"chapter") self.page = aDecoder.decodeInteger(forKey:"page") self.sourceIndex = aDecoder.decodeInteger(forKey:"sourceIndex") self.resources = aDecoder.decodeObject(forKey: "resources") as? [ResourceModel] self.chapters = aDecoder.decodeObject(forKey: "chapters") as? [NSDictionary] self.copyright = aDecoder.decodeObject(forKey: "copyright") as? String ?? "" self.postCount = aDecoder.decodeInteger(forKey: "postCount") self.isUpdated = aDecoder.decodeBool(forKey: "isUpdated") self.book = aDecoder.decodeObject(forKey: "book") as? QSBook self.record = aDecoder.decodeObject(forKey: "record") as? QSRecord self.chaptersInfo = aDecoder.decodeObject(forKey: "chaptersInfo") as? [ZSChapterInfo] self.bookCacheState = SwipeCellState.init(rawValue: aDecoder.decodeObject(forKey: "bookCacheState") as? String ?? "") ?? .none setupBook() } private func setupBook(){ if book == nil { book = QSBook() } } required override init() { super.init() setupBook() } func encode(with aCoder: NSCoder) { aCoder.encode(self._id, forKey: "_id") aCoder.encode(self.author, forKey: "author") aCoder.encode(self.cover, forKey: "cover") aCoder.encode(self.creater, forKey: "creater") aCoder.encode(self.longIntro, forKey: "longIntro") aCoder.encode(self.title, forKey: "title") aCoder.encode(self.cat, forKey: "cat") aCoder.encode(self.majorCate, forKey: "majorCate") aCoder.encode(self.minorCate, forKey: "minorCate") aCoder.encode(self.latelyFollower, forKey: "latelyFollower") aCoder.encode(self.retentionRatio, forKey: "retentionRatio") aCoder.encode(self.serializeWordCount, forKey: "serializeWordCount") aCoder.encode(self.wordCount, forKey: "wordCount") aCoder.encode(self.updated, forKey: "updated") aCoder.encode(self.tags, forKey: "tags") aCoder.encode(self.updateInfo, forKey: "updateInfo") aCoder.encode(self.chapter, forKey: "chapter") aCoder.encode(self.page, forKey: "page") aCoder.encode(self.sourceIndex, forKey: "sourceIndex") aCoder.encode(self.resources, forKey: "resources") aCoder.encode(self.chapters, forKey: "chapters") aCoder.encode(self.copyright, forKey: "copyright") aCoder.encode(self.postCount, forKey: "postCount") aCoder.encode(self.isUpdated, forKey: "isUpdated") aCoder.encode(self.book, forKey: "book") aCoder.encode(self.record, forKey: "record") aCoder.encode(self.chaptersInfo,forKey:"chaptersInfo") aCoder.encode(self.bookCacheState.rawValue, forKey: "bookCacheState") } }
ba9721717af92e0267e894fcbc73a953
39.157025
134
0.605269
false
false
false
false
HockeyWX/HockeySDK-iOSDemo-Swift
refs/heads/master
Classes/BITCrashReportsViewController.swift
mit
2
// // BITCrashReportsViewController.swift // HockeySDK-iOSDemo-Swift // // Created by Kevin Li on 18/10/2016. // import UIKit class BITCrashReportsViewController: UITableViewController { //MARK: - Private func triggerSignalCrash() { /* Trigger a crash */ abort() } func triggerExceptionCrash() { /* Trigger a crash */ let array = NSArray.init() array.object(at: 23) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows if section == 0 { return 2 } else { return 3 } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return NSLocalizedString("Test Crashes", comment: "") } else { return NSLocalizedString("Alerts", comment: "") } } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if section == 1 { return NSLocalizedString("Presented UI relevant for localization", comment: "") } return nil; } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "Cell" var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier) } // Configure the cell... if indexPath.section == 0 { if indexPath.row == 0 { cell!.textLabel?.text = NSLocalizedString("Signal", comment: ""); } else { cell!.textLabel?.text = NSLocalizedString("Exception", comment: ""); } } else { if (indexPath.row == 0) { cell!.textLabel?.text = NSLocalizedString("Anonymous", comment: ""); } else if (indexPath.row == 1) { cell!.textLabel?.text = NSLocalizedString("Anonymous 3 buttons", comment: ""); } else { cell!.textLabel?.text = NSLocalizedString("Non-anonymous", comment: ""); } } return cell! } //MARK: - Table view delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == 0 { if indexPath.row == 0 { triggerSignalCrash() } else { triggerExceptionCrash() } } else { let appName = "DemoApp" var alertDescription = String(format: BITHockeyLocalizedString("CrashDataFoundAnonymousDescription"), appName) if indexPath.row == 2 { alertDescription = String(format: BITHockeyLocalizedString("CrashDataFoundDescription"), appName) } let alert = UIAlertController(title:String(format:BITHockeyLocalizedString("CrashDataFoundTitle"), appName), message: alertDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: BITHockeyLocalizedString("CrashDontSendReport"), style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: BITHockeyLocalizedString("CrashSendReport"), style: .default, handler: nil)) if indexPath.row == 1 { alert.addAction(UIAlertAction(title: BITHockeyLocalizedString("CrashSendReportAlways"), style: .default, handler: nil)) } self.present(alert, animated: true, completion: nil) } } }
b5f8a9eab79fb746bcff4bd91ad9eb16
34.068966
171
0.592183
false
false
false
false
k-o-d-e-n/CGLayout
refs/heads/master
Example/CGLayoutPlayground.playground/Pages/LayoutWorkspacePull.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import UIKit import CGLayout import PlaygroundSupport extension UIView { convenience init(frame: CGRect, backgroundColor: UIColor) { self.init(frame: frame) self.backgroundColor = backgroundColor } } public extension UIView { func addSubviews<S: Sequence>(_ subviews: S) where S.Iterator.Element: UIView { subviews.map { $0.backgroundColor = $0.backgroundColor?.withAlphaComponent(0.5) return $0 }.forEach(addSubview) } } public extension CGRect { static func random(in source: CGRect) -> CGRect { let o = CGPoint(x: CGFloat(arc4random_uniform(UInt32(source.width))), y: CGFloat(arc4random_uniform(UInt32(source.height)))) let s = CGSize(width: CGFloat(arc4random_uniform(UInt32(source.width - o.x))), height: CGFloat(arc4random_uniform(UInt32(source.height - o.y)))) return CGRect(origin: o, size: s) } } func view(by index: Int, color: UIColor, frame: CGRect) -> UIView { let label = UILabel(frame: frame, backgroundColor: color) label.text = String(index) label.textAlignment = .center return label } let workspaceView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568)) workspaceView.backgroundColor = .lightGray PlaygroundPage.current.liveView = workspaceView let rect1 = view(by: 1, color: .red, frame: workspaceView.bounds.insetBy(dx: 100, dy: 200)) let inner = LayoutWorkspace.After.pull(axis: _RectAxis.horizontal, anchor: _RectAxisAnchor.leading) // cropped let rect2 = view(by: 2, color: .blue, frame: CGRect(origin: .zero, size: CGSize(width: 250, height: 100))) // cropped to zero let rect4 = view(by: 4, color: .yellow, frame: CGRect(x: 40, y: 400, width: 40, height: 40)) // pulled let rect6 = view(by: 6, color: .cyan, frame: CGRect(x: 120, y: 500, width: 40, height: 40)) let outer = LayoutWorkspace.Before.pull(axis: _RectAxis.horizontal, anchor: _RectAxisAnchor.leading) // cropped let rect3 = view(by: 3, color: .green, frame: CGRect(origin: CGPoint(x: 70, y: 200), size: CGSize(width: 50, height: 100))) // cropped to zero let rect5 = view(by: 5, color: .magenta, frame: CGRect(x: 120, y: 400, width: 40, height: 40)) // pulled let rect7 = view(by: 7, color: .brown, frame: CGRect(x: 10, y: 450, width: 40, height: 40)) /// comment for show initial state inner.formConstrain(sourceRect: &rect2.frame, by: rect1.frame) inner.formConstrain(sourceRect: &rect4.frame, by: rect1.frame) inner.formConstrain(sourceRect: &rect6.frame, by: rect1.frame) outer.formConstrain(sourceRect: &rect3.frame, by: rect1.frame) outer.formConstrain(sourceRect: &rect5.frame, by: rect1.frame) outer.formConstrain(sourceRect: &rect7.frame, by: rect1.frame) workspaceView.addSubviews([rect1, rect2, rect3, rect4, rect5, rect6, rect7])
6de254cf359d74a676941a3905de61de
37.933333
152
0.673288
false
false
false
false
joelbanzatto/MVCarouselCollectionView
refs/heads/master
MVCarouselCollectionViewDemo/Carousel/MVEmbeddedCarouselViewController.swift
mit
2
// MVEmbeddedCarouselViewController.swift // // Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import MVCarouselCollectionView class MVEmbeddedCarouselViewController: UIViewController, MVCarouselCollectionViewDelegate, MVFullScreenCarouselViewControllerDelegate { var imagePaths : [String] = [] var imageLoader: ((imageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) -> ())? @IBOutlet var collectionView : MVCarouselCollectionView! @IBOutlet var pageControl : MVCarouselPageControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.setTranslatesAutoresizingMaskIntoConstraints(false) self.pageControl.numberOfPages = imagePaths.count // Configure collection view self.collectionView.selectDelegate = self self.collectionView.imagePaths = imagePaths self.collectionView.commonImageLoader = self.imageLoader self.collectionView.maximumZoom = 2.0 self.collectionView.reloadData() } func addAsChildViewController(parentViewController : UIViewController, attachToView parentView: UIView) { parentViewController.addChildViewController(self) self.didMoveToParentViewController(parentViewController) parentView.addSubview(self.view) self.autoLayout(parentView) } func autoLayout(parentView: UIView) { self.matchLayoutAttribute(.Left, parentView:parentView) self.matchLayoutAttribute(.Right, parentView:parentView) self.matchLayoutAttribute(.Bottom, parentView:parentView) self.matchLayoutAttribute(.Top, parentView:parentView) } func matchLayoutAttribute(attribute : NSLayoutAttribute, parentView: UIView) { parentView.addConstraint( NSLayoutConstraint(item:self.view, attribute:attribute, relatedBy:NSLayoutRelation.Equal, toItem:parentView, attribute:attribute, multiplier:1.0, constant:0)) } // MARK: MVCarouselCollectionViewDelegate func carousel(carousel: MVCarouselCollectionView, didSelectCellAtIndexPath indexPath: NSIndexPath) { // Send indexPath.row as index to use self.performSegueWithIdentifier("FullScreenSegue", sender:indexPath); } func carousel(carousel: MVCarouselCollectionView, didScrollToCellAtIndex cellIndex : NSInteger) { self.pageControl.currentPage = cellIndex } // MARK: IBActions @IBAction func pageControlEventChanged(sender: UIPageControl) { self.collectionView.setCurrentPageIndex(sender.currentPage, animated: true) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "FullScreenSegue" { var nc = segue.destinationViewController as? UINavigationController var vc = nc?.viewControllers[0] as? MVFullScreenCarouselViewController if let vc = vc { vc.imageLoader = self.imageLoader vc.imagePaths = self.imagePaths vc.delegate = self vc.title = self.parentViewController?.navigationItem.title if let indexPath = sender as? NSIndexPath { vc.initialViewIndex = indexPath.row } } } } // MARK: FullScreenViewControllerDelegate func willCloseWithSelectedIndexPath(indexPath: NSIndexPath) { self.collectionView.resetZoom() self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition:UICollectionViewScrollPosition.CenteredHorizontally, animated:false) } }
ca46a819735e8617353da980b349d58c
40.504348
166
0.720302
false
false
false
false
JaSpa/swift
refs/heads/master
test/expr/postfix/dot/init_ref_delegation.swift
apache-2.0
26
// RUN: %target-typecheck-verify-swift // Tests for initializer delegation via self.init(...). // Initializer delegation: classes class C0 { convenience init() { self.init(value: 5) } init(value: Int) { /* ... */ } } class C1 { convenience init() { self.init(value: 5) } init(value: Int) { /* ... */ } init(value: Double) { /* ... */ } } // Initializer delegation: structs struct S0 { init() { self.init(value: 5) } init(value: Int) { /* ... */ } } struct S1 { init() { self.init(value: 5) } init(value: Int) { /* ... */ } init(value: Double) { /* ... */ } } // Initializer delegation: enum enum E0 { case A case B init() { self.init(value: 5) } init(value: Int) { /* ... */ } } enum E1 { case A case B init() { self.init(value: 5) } init(value: Int) { /* ... */ } init(value: Double) { /* ... */ } } // Ill-formed initializer delegation: no matching constructor class Z0 { init() { // expected-error {{designated initializer for 'Z0' cannot delegate (with 'self.init'); did you mean this to be a convenience initializer?}} {{3-3=convenience }} // expected-note @+2 {{delegation occurs here}} self.init(5, 5) // expected-error{{cannot invoke 'Z0.init' with an argument list of type '(Int, Int)'}} // expected-note @-1 {{overloads for 'Z0.init' exist with these partially matching parameter lists: (), (value: Int), (value: Double)}} } init(value: Int) { /* ... */ } init(value: Double) { /* ... */ } } struct Z1 { init() { self.init(5, 5) // expected-error{{cannot invoke 'Z1.init' with an argument list of type '(Int, Int)'}} // expected-note @-1 {{overloads for 'Z1.init' exist with these partially matching parameter lists: (), (value: Int), (value: Double)}} } init(value: Int) { /* ... */ } init(value: Double) { /* ... */ } } enum Z2 { case A case B init() { self.init(5, 5) // expected-error{{cannot invoke 'Z2.init' with an argument list of type '(Int, Int)'}} // expected-note @-1 {{overloads for 'Z2.init' exist with these partially matching parameter lists: (), (value: Int), (value: Double)}} } init(value: Int) { /* ... */ } init(value: Double) { /* ... */ } } // Ill-formed initialization: wrong context. class Z3 { func f() { self.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{10-10=type(of: }} {{14-14=)}} } init() { } } // 'init' is a static-ish member. class Z4 { init() {} // expected-note{{selected non-required initializer}} convenience init(other: Z4) { other.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{11-11=type(of: }} {{15-15=)}} type(of: other).init() // expected-error{{must use a 'required' initializer}} expected-warning{{unused}} } } class Z5 : Z4 { override init() { } convenience init(other: Z5) { other.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{11-11=type(of: }} {{15-15=)}} } } // Ill-formed initialization: failure to call initializer. class Z6 { convenience init() { var _ : () -> Z6 = self.init // expected-error{{partial application of 'self.init' initializer delegation is not allowed}} } init(other: Z6) { } } // Ill-formed initialization: both superclass and delegating. class Z7Base { } class Z7 : Z7Base { override init() { } init(b: Bool) { if b { super.init() } // expected-note{{previous chaining call is here}} else { self.init() } // expected-error{{initializer cannot both delegate ('self.init') and chain to a }} } } struct RDar16603812 { var i = 42 init() {} func foo() { self.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{12-12=type(of: }} {{16-16=)}} type(of: self).init() // expected-warning{{result of 'RDar16603812' initializer is unused}} } } class RDar16666631 { var i: Int var d: Double var s: String init(i: Int, d: Double, s: String) { self.i = i self.d = d self.s = s } convenience init(i: Int, s: String) { self.init(i: i, d: 0.1, s: s) } } let rdar16666631 = RDar16666631(i: 5, d: 6) // expected-error {{incorrect argument label in call (have 'i:d:', expected 'i:s:')}} struct S { init() { let _ = S.init() self.init() let _ = self.init // expected-error{{partial application of 'self.init' initializer delegation is not allowed}} } } class C { convenience init() { // expected-note 11 {{selected non-required initializer 'init()'}} self.init() let _: C = self.init() // expected-error{{cannot convert value of type '()' to specified type 'C'}} let _: () -> C = self.init // expected-error{{partial application of 'self.init' initializer delegation is not allowed}} } init(x: Int) {} // expected-note 11 {{selected non-required initializer 'init(x:)'}} required init(required: Double) {} } class D: C { override init(x: Int) { super.init(x: x) let _: C = super.init() // expected-error{{cannot convert value of type '()' to specified type 'C'}} let _: () -> C = super.init // expected-error{{partial application of 'super.init' initializer chain is not allowed}} } func foo() { self.init(x: 0) // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{10-10=type(of: }} {{14-14=)}} } func bar() { super.init(x: 0) // expected-error{{'super.init' cannot be called outside of an initializer}} } class func zim() -> Self { return self.init(required: 0) } class func zang() -> C { return super.init(required: 0) } required init(required: Double) {} } func init_tests() { var s = S.self var s1 = s.init() var ss1 = S.init() var c: C.Type = D.self var c1 = c.init(required: 0) var c2 = c.init(x: 0) // expected-error{{'required' initializer}} var c3 = c.init() // expected-error{{'required' initializer}} var c1a = c.init(required: 0) var c2a = c.init(x: 0) // expected-error{{'required' initializer}} var c3a = c.init() // expected-error{{'required' initializer}} var cf1: (Double) -> C = c.init var cf2: (Int) -> C = c.init // expected-error{{'required' initializer}} var cf3: () -> C = c.init // expected-error{{'required' initializer}} var cs1 = C.init(required: 0) var cs2 = C.init(x: 0) var cs3 = C.init() var csf1: (Double) -> C = C.init var csf2: (Int) -> C = C.init var csf3: () -> C = C.init var cs1a = C(required: 0) var cs2a = C(x: 0) var cs3a = C() var y = x.init() // expected-error{{use of unresolved identifier 'x'}} } protocol P { init(proto: String) } func foo<T: C>(_ x: T, y: T.Type) where T: P { var c1 = type(of: x).init(required: 0) var c2 = type(of: x).init(x: 0) // expected-error{{'required' initializer}} var c3 = type(of: x).init() // expected-error{{'required' initializer}} var c4 = type(of: x).init(proto: "") var cf1: (Double) -> T = type(of: x).init var cf2: (Int) -> T = type(of: x).init // expected-error{{'required' initializer}} var cf3: () -> T = type(of: x).init // expected-error{{'required' initializer}} var cf4: (String) -> T = type(of: x).init var c1a = type(of: x).init(required: 0) var c2a = type(of: x).init(x: 0) // expected-error{{'required' initializer}} var c3a = type(of: x).init() // expected-error{{'required' initializer}} var c4a = type(of: x).init(proto: "") var ci1 = x.init(required: 0) // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{15-15=type(of: }} {{19-19=)}} var ci2 = x.init(x: 0) // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{15-15=type(of: }} {{19-19=)}} var ci3 = x.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{15-15=type(of: }} {{19-19=)}} var ci4 = x.init(proto: "") // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{15-15=type(of: }} {{19-19=)}} var ci1a = x(required: 0) // expected-error{{cannot call value of non-function type 'T'}} var ci2a = x(x: 0) // expected-error{{cannot call value of non-function type 'T'}} var ci3a = x() // expected-error{{cannot call value of non-function type 'T'}}{{15-17=}} var ci4a = x(proto: "") // expected-error{{cannot call value of non-function type 'T'}} var cm1 = y.init(required: 0) var cm2 = y.init(x: 0) // expected-error{{'required' initializer}} var cm3 = y.init() // expected-error{{'required' initializer}} var cm4 = y.init(proto: "") var cm1a = y.init(required: 0) var cm2a = y.init(x: 0) // expected-error{{'required' initializer}} var cm3a = y.init() // expected-error{{'required' initializer}} var cm4a = y.init(proto: "") var cs1 = T.init(required: 0) var cs2 = T.init(x: 0) // expected-error{{'required' initializer}} var cs3 = T.init() // expected-error{{'required' initializer}} var cs4 = T.init(proto: "") var cs5 = T.init(notfound: "") // expected-error{{argument labels '(notfound:)' do not match any available overloads}} // expected-note @-1 {{overloads for 'T.Type.init' exist with these partially matching parameter lists: (x: Int), (required: Double), (proto: String)}} var csf1: (Double) -> T = T.init var csf2: (Int) -> T = T.init // expected-error{{'required' initializer}} var csf3: () -> T = T.init // expected-error{{'required' initializer}} var csf4: (String) -> T = T.init var cs1a = T(required: 0) var cs2a = T(x: 0) // expected-error{{'required' initializer}} var cs3a = T() // expected-error{{'required' initializer}} var cs4a = T(proto: "") } class TestOverloadSets { convenience init() { self.init(5, 5) // expected-error{{cannot invoke 'TestOverloadSets.init' with an argument list of type '(Int, Int)'}} // expected-note @-1 {{overloads for 'TestOverloadSets.init' exist with these partially matching parameter lists: (), (a: Z0), (value: Int), (value: Double)}} } convenience init(a : Z0) { self.init(42 as Int8) // expected-error{{argument labels '(_:)' do not match any available overloads}} // expected-note @-1 {{overloads for 'TestOverloadSets.init' exist with these partially matching parameter lists: (a: Z0), (value: Int), (value: Double)}} } init(value: Int) { /* ... */ } init(value: Double) { /* ... */ } } class TestNestedExpr { init() {} init?(fail: Bool) {} init(error: Bool) throws {} convenience init(a: Int) { let x: () = self.init() // expected-error {{initializer delegation ('self.init') cannot be nested in another statement}} // expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}} } convenience init(b: Int) { func use(_ x: ()) {} use(self.init()) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}} } convenience init(c: Int) { _ = ((), self.init()) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}} } convenience init(d: Int) { let x: () = self.init(fail: true)! // expected-error {{initializer delegation ('self.init') cannot be nested in another statement}} // expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}} } convenience init(e: Int) { func use(_ x: ()) {} use(self.init(fail: true)!) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}} } convenience init(f: Int) { _ = ((), self.init(fail: true)!) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}} } convenience init(g: Int) { let x: () = try! self.init(error: true) // expected-error {{initializer delegation ('self.init') cannot be nested in another statement}} // expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}} } convenience init(h: Int) { func use(_ x: ()) {} use(try! self.init(error: true)) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}} } convenience init(i: Int) { _ = ((), try! self.init(error: true)) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}} } } class TestNestedExprSub : TestNestedExpr { init(a: Int) { let x: () = super.init() // expected-error {{initializer chaining ('super.init') cannot be nested in another statement}} // expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}} } init(b: Int) { func use(_ x: ()) {} use(super.init()) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}} } init(c: Int) { _ = ((), super.init()) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}} } init(d: Int) { let x: () = super.init(fail: true)! // expected-error {{initializer chaining ('super.init') cannot be nested in another statement}} // expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}} } init(e: Int) { func use(_ x: ()) {} use(super.init(fail: true)!) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}} } init(f: Int) { _ = ((), super.init(fail: true)!) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}} } init(g: Int) { let x: () = try! super.init(error: true) // expected-error {{initializer chaining ('super.init') cannot be nested in another statement}} // expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}} } init(h: Int) { func use(_ x: ()) {} use(try! super.init(error: true)) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}} } init(i: Int) { _ = ((), try! super.init(error: true)) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}} } } class TestOptionalTry { init() throws {} convenience init(a: Int) { // expected-note {{propagate the failure with 'init?'}} {{19-19=?}} try? self.init() // expected-error {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-1 {{force potentially-failing result with 'try!'}} {{5-9=try!}} } init?(fail: Bool) throws {} convenience init(failA: Int) { // expected-note {{propagate the failure with 'init?'}} {{19-19=?}} try? self.init(fail: true)! // expected-error {{a non-failable initializer cannot use 'try?' to delegate to another initializer}} // expected-note@-1 {{force potentially-failing result with 'try!'}} {{5-9=try!}} } convenience init(failB: Int) { // expected-note {{propagate the failure with 'init?'}} {{19-19=?}} try! self.init(fail: true) // expected-error {{a non-failable initializer cannot delegate to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1 {{force potentially-failing result with '!'}} {{31-31=!}} } convenience init(failC: Int) { try! self.init(fail: true)! // okay } convenience init?(failD: Int) { try? self.init(fail: true) // okay } convenience init?(failE: Int) { try! self.init(fail: true) // okay } convenience init?(failF: Int) { try! self.init(fail: true)! // okay } convenience init?(failG: Int) { try? self.init(fail: true) // okay } } class TestOptionalTrySub : TestOptionalTry { init(a: Int) { // expected-note {{propagate the failure with 'init?'}} {{7-7=?}} try? super.init() // expected-error {{a non-failable initializer cannot use 'try?' to chain to another initializer}} // expected-note@-1 {{force potentially-failing result with 'try!'}} {{5-9=try!}} } }
cfc2c00f15bbcb4573ec6ceee5636ef4
34.074786
189
0.624368
false
false
false
false
AbidHussainCom/HackingWithSwift
refs/heads/master
project11/Project11/GameScene.swift
unlicense
20
// // GameScene.swift // Project11 // // Created by Hudzilla on 22/11/2014. // Copyright (c) 2014 Hudzilla. All rights reserved. // import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { var scoreLabel: SKLabelNode! var score: Int = 0 { didSet { scoreLabel.text = "Score: \(score)" } } var editLabel: SKLabelNode! var editingMode: Bool = false { didSet { if editingMode { editLabel.text = "Done" } else { editLabel.text = "Edit" } } } override func didMoveToView(view: SKView) { let background = SKSpriteNode(imageNamed: "background.jpg") background.position = CGPoint(x: 512, y: 384) background.blendMode = .Replace background.zPosition = -1 addChild(background) physicsBody = SKPhysicsBody(edgeLoopFromRect:CGRect(x: 0, y: 0, width: 1024, height: 768)) physicsWorld.contactDelegate = self makeSlotAt(CGPoint(x: 128, y: 0), isGood: true) makeSlotAt(CGPoint(x: 384, y: 0), isGood: false) makeSlotAt(CGPoint(x: 640, y: 0), isGood: true) makeSlotAt(CGPoint(x: 896, y:0), isGood: false) makeBouncerAt(CGPoint(x: 0, y: 0)) makeBouncerAt(CGPoint(x: 256, y: 0)) makeBouncerAt(CGPoint(x: 512, y: 0)) makeBouncerAt(CGPoint(x: 768, y: 0)) makeBouncerAt(CGPoint(x: 1024, y: 0)) scoreLabel = SKLabelNode(fontNamed: "Chalkduster") scoreLabel.text = "Score: 0" scoreLabel.horizontalAlignmentMode = .Right scoreLabel.position = CGPoint(x: 980, y: 700) addChild(scoreLabel) editLabel = SKLabelNode(fontNamed: "Chalkduster") editLabel.text = "Edit" editLabel.position = CGPoint(x: 80, y: 700) addChild(editLabel) } func makeBouncerAt(position: CGPoint) { let bouncer = SKSpriteNode(imageNamed: "bouncer") bouncer.position = position bouncer.physicsBody = SKPhysicsBody(circleOfRadius: bouncer.size.width / 2.0) bouncer.physicsBody!.dynamic = false addChild(bouncer) } func makeSlotAt(position: CGPoint, isGood: Bool) { var slotBase: SKSpriteNode var slotGlow: SKSpriteNode if isGood { slotBase = SKSpriteNode(imageNamed: "slotBaseGood") slotGlow = SKSpriteNode(imageNamed: "slotGlowGood") slotBase.name = "good" } else { slotBase = SKSpriteNode(imageNamed: "slotBaseBad") slotGlow = SKSpriteNode(imageNamed: "slotGlowBad") slotBase.name = "bad" } slotBase.position = position slotGlow.position = position slotBase.physicsBody = SKPhysicsBody(rectangleOfSize: slotBase.size) slotBase.physicsBody!.contactTestBitMask = slotBase.physicsBody!.collisionBitMask slotBase.physicsBody!.dynamic = false addChild(slotBase) addChild(slotGlow) let spin = SKAction.rotateByAngle(CGFloat(M_PI_2), duration: 10) let spinForever = SKAction.repeatActionForever(spin) slotGlow.runAction(spinForever) } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { if let touch = touches.first as? UITouch { let location = touch.locationInNode(self) let objects = nodesAtPoint(location) as! [SKNode] if contains(objects, editLabel) { editingMode = !editingMode } else { if editingMode { let size = CGSize(width: RandomInt(min: 16, max: 128), height: 16) let box = SKSpriteNode(color: RandomColor(), size: size) box.zRotation = RandomCGFloat(min: 0, max: 3) box.position = location box.physicsBody = SKPhysicsBody(rectangleOfSize: box.size) box.physicsBody!.dynamic = false addChild(box) } else { var ball: SKSpriteNode switch RandomInt(min: 0, max: 3) { case 0: ball = SKSpriteNode(imageNamed: "ballRed") break case 1: ball = SKSpriteNode(imageNamed: "ballBlue") break case 2: ball = SKSpriteNode(imageNamed: "ballGreen") break case 3: ball = SKSpriteNode(imageNamed: "ballYellow") break default: return } ball.name = "ball" ball.position = CGPoint(x: location.x, y: 700) addChild(ball) ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width / 2.0) ball.physicsBody!.contactTestBitMask = ball.physicsBody!.collisionBitMask ball.physicsBody!.restitution = 0.4 } } } } func didBeginContact(contact: SKPhysicsContact) { if contact.bodyA.node!.name == "ball" { collisionBetweenBall(contact.bodyA.node!, object: contact.bodyB.node!) } else if contact.bodyB.node!.name == "ball" { collisionBetweenBall(contact.bodyB.node!, object: contact.bodyA.node!) } } func collisionBetweenBall(ball: SKNode, object: SKNode) { if object.name == "good" { destroyBall(ball) ++score } else if object.name == "bad" { destroyBall(ball) --score } } func destroyBall(ball: SKNode) { if let myParticlePath = NSBundle.mainBundle().pathForResource("FireParticles", ofType: "sks") { let fireParticles = NSKeyedUnarchiver.unarchiveObjectWithFile(myParticlePath) as! SKEmitterNode fireParticles.position = ball.position addChild(fireParticles) } ball.removeFromParent() } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
ebf072598a2c2cb3ddb133cbd7806263
25.889474
98
0.693286
false
false
false
false
fleurdeswift/code-editor
refs/heads/master
CodeEditorCore/Controller+Navigation.swift
mit
1
// // Controller+Navigation.swift // CodeEditorCore // // Copyright © 2015 Fleur de Swift. All rights reserved. // import Foundation public extension Controller { private func moveCursors(block: (inout position: Position, context: ModificationContext) -> Bool, extendsSelection: Bool) -> Bool { do { return try document.modify({ (context: ModificationContext) -> Bool in return self.moveCursors(block, extendsSelection: extendsSelection, context: context); }).result; } catch { return false; } } private func moveCursors(block: (inout position: Position, context: ModificationContext) -> Bool, extendsSelection: Bool, context: ModificationContext) -> Bool { var modified = false; for cursor in cursors { if cursor.type != .Edit { continue; } modified |= moveCursor(block, cursor: cursor, extendsSelection: extendsSelection, context: context); } return modified; } private func moveCursor(block: (inout position: Position, context: ModificationContext) -> Bool, cursor: Cursor, extendsSelection: Bool, context: ModificationContext) -> Bool { if block(position: &cursor.range.end, context: context) { if !extendsSelection { cursor.range.start = cursor.range.end; } onCursorMoved(cursor); return true; } return false; } public func normalize(inout position: Position, context: ReadContext) -> Bool { if position.line >= document.lines.count { position = document.endPosition(context); return true; } else if position.line < 0 { position = document.beginPosition; return true; } let line = document.lines[position.line]; let length = line.length; if position.column > length { position.column = length; return true; } else if position.column < 0 { assert(false); position.column = 0; return true; } return false; } public func moveBackward(inout position: Position, context: ModificationContext) -> Bool { if (normalize(&position, context: context)) { return true; } if position.column == 0 { if position.line == 0 { return false; } position.line--; position.column = document.lines[position.line].length; } else { position.column--; } return true; } public func moveBackward(inout position: Position, characterIterator: (ch: Character) -> Bool, context: ModificationContext) -> Bool { if (normalize(&position, context: context)) { return true; } while true { let ch = document.lines[position.line].charAt(position.column); if characterIterator(ch: ch) { break; } if position.column == 0 { if position.line == 0 { return false; } position.line--; position.column = document.lines[position.line].length; } else { position.column--; } } return true; } public func moveCursorBackward(cursor: Cursor, extendsSelection: Bool, context: ModificationContext) -> Bool { return moveCursor(moveBackward, cursor: cursor, extendsSelection: extendsSelection, context: context); } public func moveCursorsBackward(extendsSelection: Bool, context: ModificationContext) -> Bool { return moveCursors(moveBackward, extendsSelection: extendsSelection, context: context); } public func moveCursorsBackward(extendsSelection: Bool) -> Bool { return moveCursors(moveBackward, extendsSelection: extendsSelection); } public func moveForward(inout position: Position, context: ModificationContext) -> Bool { if (normalize(&position, context: context)) { return true; } let line = document.lines[position.line]; if position.column < line.length { position.column++; return true; } if (document.lines.count - 1) == position.line { return false; } position.line++; position.column = 0; return true; } public func moveForward(inout position: Position, characterIterator: (ch: Character) -> Bool, context: ModificationContext) -> Bool { if (normalize(&position, context: context)) { return true; } while true { let ch = document.lines[position.line].charAt(position.column); if characterIterator(ch: ch) { break; } let line = document.lines[position.line]; if position.column < line.length { position.column++; continue; } if (document.lines.count - 1) == position.line { return false; } position.line++; position.column = 0; } return true; } public func moveCursorForward(cursor: Cursor, extendsSelection: Bool, context: ModificationContext) -> Bool { return moveCursor(moveForward, cursor: cursor, extendsSelection: extendsSelection, context: context); } public func moveCursorsForward(extendsSelection: Bool, context: ModificationContext) -> Bool { return moveCursors(moveForward, extendsSelection: extendsSelection, context: context); } public func moveCursorsForward(extendsSelection: Bool) -> Bool { return moveCursors(moveForward, extendsSelection: extendsSelection); } public func moveToEndOfLine(inout position: Position, context: ModificationContext) -> Bool { if (normalize(&position, context: context)) { return true; } let line = document.lines[position.line]; if position.column != line.length { position.column = line.length; return true; } return true; } public func moveCursorToEndOfLine(cursor: Cursor, extendsSelection: Bool, context: ModificationContext) -> Bool { return moveCursor(moveToEndOfLine, cursor: cursor, extendsSelection: extendsSelection, context: context); } public func moveCursorsToEndOfLine(extendsSelection: Bool, context: ModificationContext) -> Bool { return moveCursors(moveToEndOfLine, extendsSelection: extendsSelection, context: context); } public func moveCursorsToEndOfLine(extendsSelection: Bool) -> Bool { return moveCursors(moveToEndOfLine, extendsSelection: extendsSelection); } public func moveToStartOfLine(inout position: Position, context: ModificationContext) -> Bool { if (normalize(&position, context: context)) { return true; } if position.column != 0 { position.column = 0; return true; } return true; } public func moveCursorToStartOfLine(cursor: Cursor, extendsSelection: Bool, context: ModificationContext) -> Bool { return moveCursor(moveToStartOfLine, cursor: cursor, extendsSelection: extendsSelection, context: context); } public func moveCursorsToStartOfLine(extendsSelection: Bool, context: ModificationContext) -> Bool { return moveCursors(moveToStartOfLine, extendsSelection: extendsSelection, context: context); } public func moveCursorsToStartOfLine(extendsSelection: Bool) -> Bool { return moveCursors(moveToStartOfLine, extendsSelection: extendsSelection); } }
c2fd5a72fd4e2900cae8a27de0c70a4b
31.907631
180
0.583964
false
false
false
false
phatblat/realm-cocoa
refs/heads/master
examples/ios/swift/Migration/Examples/Example_v0.swift
apache-2.0
2
//////////////////////////////////////////////////////////////////////////// // // Copyright 2021 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #if SCHEMA_VERSION_0 import Foundation import RealmSwift // MARK: - Schema let schemaVersion = 0 class Person: Object { @Persisted var firstName = "" @Persisted var lastName = "" @Persisted var age = 0 convenience init(firstName: String, lastName: String, age: Int) { self.init() self.firstName = firstName self.lastName = lastName self.age = age } } // MARK: - Migration // Migration block to migrate from *any* previous version to this version. let migrationBlock: MigrationBlock = { _, _ in } // This block checks if the migration led to the expected result. // All older versions should have been migrated to the below stated `exampleData`. let migrationCheck: (Realm) -> Void = { realm in let persons = realm.objects(Person.self) assert(persons.count == 3) assert(persons[0].firstName == "John") assert(persons[0].lastName == "Doe") assert(persons[0].age == 42) assert(persons[1].firstName == "Jane") assert(persons[1].lastName == "Doe") assert(persons[1].age == 43) assert(persons[2].firstName == "John") assert(persons[2].lastName == "Smith") assert(persons[2].age == 44) } // MARK: - Example data // Example data for this schema version. let exampleData: (Realm) -> Void = { realm in let person1 = Person(firstName: "John", lastName: "Doe", age: 42) let person2 = Person(firstName: "Jane", lastName: "Doe", age: 43) let person3 = Person(firstName: "John", lastName: "Smith", age: 44) realm.add([person1, person2, person3]) } #endif
97cf785607c8c72004080d10f84dce6f
31.478873
82
0.633998
false
false
false
false
mpclarkson/vapor
refs/heads/master
Tests/Vapor/HTTPStreamTests.swift
mit
1
// // JeevesTests.swift // Vapor // // Created by Logan Wright on 3/12/16. // Copyright © 2016 Tanner Nelson. All rights reserved. // import Foundation import XCTest @testable import Vapor class HTTPStreamTests: XCTestCase { static var allTests: [(String, HTTPStreamTests -> () throws -> Void)] { return [ ("testStream", testStream) ] } func testStream() throws { let stream = TestHTTPStream.makeStream() //MARK: Create Request let content = "{\"hello\": \"world\"}" var data = "POST /json HTTP/1.1\r\n" data += "Accept-Encoding: gzip, deflate\r\n" data += "Accept: */*\r\n" data += "Accept-Language: en-us\r\n" data += "Cookie: 1=1\r\n" data += "Cookie: 2=2\r\n" data += "Content-Type: application/json\r\n" data += "Content-Length: \(content.characters.count)\r\n" data += "\r\n" data += content //MARK: Send Request try stream.send(data) //MARK: Read Request var request: Request do { request = try stream.receive() } catch { XCTFail("Error receiving from stream: \(error)") return } request.parseData() //MARK: Verify Request XCTAssert(request.method == Request.Method.post, "Incorrect method \(request.method)") XCTAssert(request.uri.path == "/json", "Incorrect path \(request.uri.path)") XCTAssert(request.version.major == 1 && request.version.minor == 1, "Incorrect version") XCTAssert(request.headers["cookie"].count == 2, "Incorrect cookies count") XCTAssert(request.cookies["1"] == "1" && request.cookies["2"] == "2", "Cookies not parsed") XCTAssert(request.data["hello"]?.string == "world") //MARK: Create Response var response = Response(status: .enhanceYourCalm, headers: [ "Test": ["123", "456"], "Content-Type": "text/plain" ], body: { stream in try stream.send("Hello, world") }) response.cookies["key"] = "val" //MARK: Send Response try stream.send(response, keepAlive: true) //MARK: Read Response do { let data = try stream.receive(max: Int.max) print(data) let expected = "HTTP/1.1 420 Enhance Your Calm\r\nConnection: keep-alive\r\nContent-Type: text/plain\r\nSet-Cookie: key=val\r\nTest: 123\r\nTest: 456\r\nTransfer-Encoding: chunked\r\n\r\nHello, world" //MARK: Verify Response XCTAssert(data == expected.data) } catch { XCTFail("Could not parse response string \(error)") } } }
d232d204a8234298c45305a250a2acc2
29.943182
212
0.566287
false
true
false
false
OrRon/NexmiiHack
refs/heads/develop
Carthage/Checkouts/LayoutKit/LayoutKit/Views/ReloadableViewLayoutAdapter+UICollectionView.swift
apache-2.0
5
// Copyright 2016 LinkedIn Corp. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import UIKit // MARK: - UICollectionViewDelegateFlowLayout extension ReloadableViewLayoutAdapter: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return currentArrangement[indexPath.section].items[indexPath.item].frame.size } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return currentArrangement[section].header?.frame.size ?? .zero } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return currentArrangement[section].footer?.frame.size ?? .zero } } // MARK: - UICollectionViewDataSource extension ReloadableViewLayoutAdapter: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return currentArrangement[section].items.count } public func numberOfSections(in collectionView: UICollectionView) -> Int { return currentArrangement.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = currentArrangement[indexPath.section].items[indexPath.item] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) item.makeViews(in: cell.contentView) return cell } public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: reuseIdentifier, for: indexPath) let arrangement: LayoutArrangement? switch kind { case UICollectionElementKindSectionHeader: arrangement = currentArrangement[indexPath.section].header case UICollectionElementKindSectionFooter: arrangement = currentArrangement[indexPath.section].footer default: arrangement = nil assertionFailure("unknown supplementary view kind \(kind)") } arrangement?.makeViews(in: view) return view } }
0a6e09de74b08dd05dd71e2f1a8e8861
47.354839
177
0.753836
false
false
false
false
OmarBizreh/IOSTrainingApp
refs/heads/master
IOSTrainingApp/ViewController.swift
mit
1
// // ViewController.swift // IOSTrainingApp // // Created by Omar Bizreh on 2/6/16. // Copyright © 2016 Omar Bizreh. All rights reserved. // import UIKit import KYDrawerController class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var lblTitle: UILabel! @IBOutlet var tableView: UITableView! @IBOutlet var viewHeader: UIView! private let cellIdentifier = "reuseCell" private let headersArray: [String] = ["Controls", "General"] private var drawerView: KYDrawerController? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //self.viewHeader.backgroundColor = UIColor(patternImage: UIImage(named: "header_image.jpg")!) self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier) self.drawerView = (UIApplication.sharedApplication().windows[0].rootViewController as! KYDrawerController) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 3 }else{ return 2 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier) if indexPath.section == 0 { cell?.textLabel?.text = "Hello World" } else{ cell?.textLabel?.text = "Hello World" } return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.drawerView?.setDrawerState(.Closed, animated: true) } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.headersArray[section] } }
b30b20fb19b49c1be94eec77530c0e63
31.470588
114
0.667572
false
false
false
false
linebounce/HLT-Challenge
refs/heads/master
HLTChallenge/FlickrPhotoCommentCollection.swift
mit
1
// // FlickrPhotoCommentCollection.swift // HLTChallenge // // Created by Key Hoffman on 10/25/16. // Copyright © 2016 Key Hoffman. All rights reserved. // import Foundation // MARK: - FlickrPhotoCommentCollection struct FlickrPhotoCommentCollection: FlickrCollection { let elements: Set<FlickrPhotoComment> } // MARK: - EmptyInitializable Conformance extension FlickrPhotoCommentCollection { init() { elements = .empty } init(from array: [FlickrPhotoComment]) { elements = Set(array) } } // MARK: - FlickrCollection Conformance extension FlickrPhotoCommentCollection { static let urlQueryParameters = urlGeneralQueryParameters + [ FlickrConstants.Parameters.Keys.CommentCollection.method: FlickrConstants.Parameters.Values.CommentCollection.method ] static func create(from dict: JSONDictionary) -> Result<FlickrPhotoCommentCollection> { guard let commentsDict = dict[FlickrConstants.Response.Keys.CommentCollection.commentDictionary] >>- _JSONDictionary, let status = dict[FlickrConstants.Response.Keys.General.status] >>- JSONString, status == FlickrConstants.Response.Values.Status.success else { return Result(CreationError.Flickr.comment) } guard let commentsArray = commentsDict[FlickrConstants.Response.Keys.CommentCollection.commentArray] >>- JSONArray else { return Result.init <| .empty } return commentsArray.map(FlickrPhotoComment.create).inverted <^> FlickrPhotoCommentCollection.init } }
d59927f6384ee96637f0f6275e0e64df
35.348837
160
0.726168
false
false
false
false
DianQK/LearnRxSwift
refs/heads/master
LearnRxSwift/RxNetwork/ObjectMapper/UserModel.swift
mit
1
// // UserModel.swift // LearnRxSwift // // Created by DianQK on 16/2/22. // Copyright © 2016年 DianQK. All rights reserved. // import ObjectMapper import RxDataSources struct UserListModel { var users: [UserModel]! } struct UserModel { var name: String! var age: String! } extension UserListModel: Mappable { init?(_ map: Map) { } mutating func mapping(map: Map) { users <- map["users"] } } extension UserListModel: Hashable { var hashValue: Int { return users.description.hashValue } } extension UserListModel: IdentifiableType { var identity: Int { return hashValue } } func ==(lhs: UserListModel, rhs: UserListModel) -> Bool { return lhs.hashValue == rhs.hashValue } extension UserModel: Mappable { init?(_ map: Map) { } mutating func mapping(map: Map) { name <- map["name"] age <- map["age"] } } extension UserModel: Hashable { var hashValue: Int { return name.hashValue } } extension UserModel: IdentifiableType { var identity: Int { return hashValue } } func ==(lhs: UserModel, rhs: UserModel) -> Bool { return lhs.name == rhs.name }
54a14b705a8a1b007bd530c4814c371e
16.602941
57
0.62291
false
false
false
false
google/JacquardSDKiOS
refs/heads/main
Example/JacquardSDK/IMUDataCollectionView/IMUSessionDetailsViewController.swift
apache-2.0
1
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import JacquardSDK import UIKit final class IMUSessionDetailsViewController: UIViewController { struct IMUSampleCellModel: Hashable { let sample: IMUSample static func == (lhs: IMUSampleCellModel, rhs: IMUSampleCellModel) -> Bool { return lhs.sample.timestamp == rhs.sample.timestamp } func hash(into hasher: inout Hasher) { sample.timestamp.hash(into: &hasher) } } // Session to show the samples. var selectedSession: IMUSessionData! @IBOutlet private weak var sessionName: UILabel! @IBOutlet private weak var samplesTableView: UITableView! private var samplesDiffableDataSource: UITableViewDiffableDataSource<Int, IMUSampleCellModel>? private lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.timeStyle = DateFormatter.Style.medium formatter.dateStyle = DateFormatter.Style.medium formatter.timeZone = .current return formatter }() override func viewDidLoad() { super.viewDidLoad() if let timestamp = TimeInterval(selectedSession.metadata.sessionID) { let date = Date(timeIntervalSinceReferenceDate: timestamp) sessionName.text = dateFormatter.string(from: date) } else { sessionName.text = selectedSession.metadata.sessionID } configureSessionTableView() updateDataSource() } private func configureSessionTableView() { let nib = UINib(nibName: IMUSessionDetailTableViewCell.reuseIdentifier, bundle: nil) samplesTableView.register( nib, forCellReuseIdentifier: IMUSessionDetailTableViewCell.reuseIdentifier) samplesTableView.dataSource = samplesDiffableDataSource samplesTableView.delegate = self samplesTableView.rowHeight = 64.0 samplesDiffableDataSource = UITableViewDiffableDataSource<Int, IMUSampleCellModel>( tableView: samplesTableView, cellProvider: { (tableView, indexPath, sampleModel) -> UITableViewCell? in let cell = tableView.dequeueReusableCell( withIdentifier: IMUSessionDetailTableViewCell.reuseIdentifier, for: indexPath ) guard let sampleCell = cell as? IMUSessionDetailTableViewCell else { assertionFailure("Cell can not be casted to IMUSessionTableViewCell.") return cell } sampleCell.configureCell(model: sampleModel.sample) return sampleCell }) } func updateDataSource() { let samples = selectedSession.samples.map { IMUSampleCellModel(sample: $0) } var snapshot = NSDiffableDataSourceSnapshot<Int, IMUSampleCellModel>() snapshot.appendSections([0]) snapshot.appendItems(samples, toSection: 0) self.samplesDiffableDataSource?.apply(snapshot) } } extension IMUSessionDetailsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = JacquardSectionHeader( frame: CGRect(x: 0.0, y: 0.0, width: samplesTableView.frame.width, height: 40.0)) headerView.title = "DATA: (\(selectedSession.samples.count) samples)" return headerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40.0 } }
ba100040a6499cfd6ec86f70537dd300
34.277778
96
0.734383
false
false
false
false
luizlopezm/ios-Luis-Trucking
refs/heads/master
Pods/SwiftForms/SwiftForms/cells/FormSliderCell.swift
mit
1
// // FormSliderCell.swift // SwiftFormsApplication // // Created by Miguel Angel Ortuno Ortuno on 23/5/15. // Copyright (c) 2015 Miguel Angel Ortuno Ortuno. All rights reserved. // public class FormSliderCell: FormTitleCell { // MARK: Cell views public let sliderView = UISlider() // MARK: FormBaseCell public override func configure() { super.configure() selectionStyle = .None titleLabel.translatesAutoresizingMaskIntoConstraints = false sliderView.translatesAutoresizingMaskIntoConstraints = false titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) contentView.addSubview(titleLabel) contentView.addSubview(sliderView) titleLabel.setContentHuggingPriority(500, forAxis: .Horizontal) contentView.addConstraint(NSLayoutConstraint(item: sliderView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) sliderView.addTarget(self, action: #selector(FormSliderCell.valueChanged(_:)), forControlEvents: .ValueChanged) } public override func update() { super.update() if let maximumValue = rowDescriptor.configuration[FormRowDescriptor.Configuration.MaximumValue] as? Float { sliderView.maximumValue = maximumValue } if let minimumValue = rowDescriptor.configuration[FormRowDescriptor.Configuration.MinimumValue] as? Float { sliderView.minimumValue = minimumValue } if let continuous = rowDescriptor.configuration[FormRowDescriptor.Configuration.Continuous] as? Bool { sliderView.continuous = continuous } titleLabel.text = rowDescriptor.title if rowDescriptor.value != nil { sliderView.value = rowDescriptor.value as! Float } else { sliderView.value = sliderView.minimumValue rowDescriptor.value = sliderView.minimumValue } } public override func constraintsViews() -> [String : UIView] { return ["titleLabel" : titleLabel, "sliderView" : sliderView] } public override func defaultVisualConstraints() -> [String] { var constraints: [String] = [] constraints.append("V:|[titleLabel]|") constraints.append("H:|-16-[titleLabel]-16-[sliderView]-16-|") return constraints } // MARK: Actions internal func valueChanged(_: UISlider) { rowDescriptor.value = sliderView.value } }
d3a0714def13ff8e8725be177dd4a901
32.074074
185
0.640538
false
true
false
false
mikeckennedy/DevWeek2015
refs/heads/master
swift/ttt/ttt/ViewController.swift
cc0-1.0
1
// // ViewController.swift // ttt // // Created by Michael Kennedy on 3/25/15. // Copyright (c) 2015 DevelopMentor. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var button11: UIButton! @IBOutlet weak var button12: UIButton! @IBOutlet weak var button13: UIButton! @IBOutlet weak var button21: UIButton! @IBOutlet weak var button22: UIButton! @IBOutlet weak var button23: UIButton! @IBOutlet weak var button31: UIButton! @IBOutlet weak var button32: UIButton! @IBOutlet weak var button33: UIButton! @IBOutlet weak var labelOutcome: UILabel! var buttons : [[UIButton!]] = [] var game = Game() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. labelOutcome.text = "" // button11.removeConstraints(button11.constraints()) // button11.setTranslatesAutoresizingMaskIntoConstraints(true) // // button11.frame = CGRect(x: 0, y: 0, width: 200, height: 200 //) var row1 = [button11, button12, button13] var row2 = [button21, button22, button23] var row3 = [button31, button32, button33] buttons.append(row1) buttons.append(row2) buttons.append(row3) syncGameToButtons() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func buttonPlayClicked(sender: UIButton) { if game.hasWinner { return } let (r, c) = getIndexForButton(sender) var currentPlayer = game.currentPlayerName if game.play(r, col: c) { game.swapPlayers() } syncGameToButtons() if game.hasWinner { labelOutcome.text = "We have a winner! " + currentPlayer } } func getIndexForButton(btn : UIButton!) -> (Int, Int) { for (idx_r, row) in enumerate(buttons) { for (idx_c, b) in enumerate(row) { if b == btn { return (idx_r, idx_c) } } } return (-1, -1) } func syncGameToButtons() { for row in buttons { for b in row { let (r, c) = getIndexForButton(b) if let text = game.getCellText(r,c: c) { b.setTitle(text, forState: .Normal) } else { b.setTitle("___", forState: .Normal) } } } } }
ec4a7ec5d9f3cbe5d61b8069c8318c46
24.906542
80
0.539683
false
false
false
false
zhixingxi/JJA_Swift
refs/heads/master
JJA_Swift/Pods/TimedSilver/Sources/UIKit/UIButton+TSTouchArea.swift
mit
1
// // UIButton+TSTouchArea.swift // TimedSilver // Source: https://github.com/hilen/TimedSilver // // Created by Hilen on 9/22/16. // Copyright © 2016 Hilen. All rights reserved. // import UIKit private var ts_touchAreaEdgeInsets: UIEdgeInsets = .zero extension UIButton { /// Increase your button touch area. /// If your button frame is (0,0,40,40). Then call button.ts_touchInsets = UIEdgeInsetsMake(-30, -30, -30, -30), it will Increase the touch area public var ts_touchInsets: UIEdgeInsets { get { if let value = objc_getAssociatedObject(self, &ts_touchAreaEdgeInsets) as? NSValue { var edgeInsets: UIEdgeInsets = .zero value.getValue(&edgeInsets) return edgeInsets } else { return .zero } } set(newValue) { var newValueCopy = newValue let objCType = NSValue(uiEdgeInsets: .zero).objCType let value = NSValue(&newValueCopy, withObjCType: objCType) objc_setAssociatedObject(self, &ts_touchAreaEdgeInsets, value, .OBJC_ASSOCIATION_RETAIN) } } open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { if UIEdgeInsetsEqualToEdgeInsets(self.ts_touchInsets, .zero) || !self.isEnabled || self.isHidden { return super.point(inside: point, with: event) } let relativeFrame = self.bounds let hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.ts_touchInsets) return hitFrame.contains(point) } }
b199ebbe1b8ea6b102fbf0953a0cc774
32.666667
148
0.619431
false
false
false
false
ZhaoBingDong/EasySwifty
refs/heads/master
EasySwifty/Classes/EasyDataHelper.swift
apache-2.0
1
// // EasyDataHelper.swift // MiaoTuProject // // Created by dzb on 2019/7/4. // Copyright © 2019 大兵布莱恩特. All rights reserved. // import Foundation //import SwiftyJSON // //protocol MTJSONCodable : class { // init(fromJson json: JSON!) //} // //class EasyDataHelper<T :MTJSONCodable> { // let num : Int = 10 // typealias EasyDataResponse = (data : [T],indexPaths : [IndexPath]?, noData : Bool) // // class func loadMoreData(_ jsonData : [JSON], startPage : Int,currentPage : Int, source : [T]) -> EasyDataResponse { // var temp : [T] = [T]() // var dataArray = [T](source) // var location = source.count // let isRefresh : Bool = (startPage == currentPage) // var indexPaths : [IndexPath]? = !isRefresh ? [IndexPath]() : nil // for i in 0..<jsonData.count { // let dict = jsonData[i] // let object = T(fromJson: dict) // temp.append(object) // if (!isRefresh) { // let indexPath = IndexPath(row: location,section: 0) // indexPaths?.append(indexPath) // location += 1 // } // } // if isRefresh { // dataArray = temp // } else { // dataArray.append(contentsOf: temp) // } // let nodata : Bool = (temp.count < 10) // return (dataArray,indexPaths,nodata) // } // // static func loadMoreData(_ jsonData : [JSON], page : Int, source : [T]) -> EasyDataResponse { // return loadMoreData(jsonData, startPage: 1, currentPage: page, source: source) // } // //} //
8bdc3a13c6a270f1cfcfa3d90e8204ba
31.14
122
0.54636
false
false
false
false
KBryan/SwiftFoundation
refs/heads/develop
Source/FileManager.swift
mit
1
// // FileManager.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 6/29/15. // Copyright © 2015 PureSwift. All rights reserved. // public typealias FileSystemAttributes = statfs public typealias FileAttributes = stat /// Class for interacting with the file system. public final class FileManager { // MARK: - Determining Access to Files /// Determines whether a file descriptor exists at the specified path. Can be regular file, directory, socket, etc. public static func itemExists(atPath path: String) -> Bool { return (stat(path, nil) == 0) } /// Determines whether a file exists at the specified path. public static func fileExists(atPath path: String) -> Bool { var inodeInfo = stat() guard stat(path, &inodeInfo) == 0 else { return false } guard (inodeInfo.st_mode & S_IFMT) == S_IFREG else { return false } return true } /// Determines whether a directory exists at the specified path. public static func directoryExists(atPath path: String) -> Bool { var inodeInfo = stat() guard stat(path, &inodeInfo) == 0 else { return false } guard (inodeInfo.st_mode & S_IFMT) == S_IFDIR else { return false } return true } // MARK: - Managing the Current Directory /// Attempts to change the current directory public static func changeCurrentDirectory(newCurrentDirectory: String) throws { guard chdir(newCurrentDirectory) == 0 else { throw POSIXError.fromErrorNumber! } } /// Gets the current directory public static var currentDirectory: String { let stringBufferSize = Int(PATH_MAX) let path = UnsafeMutablePointer<CChar>.alloc(stringBufferSize) defer { path.dealloc(stringBufferSize) } getcwd(path, stringBufferSize - 1) return String.fromCString(path)! } // MARK: - Creating and Deleting Items public static func createFile(atPath path: String, contents: Data? = nil, attributes: FileAttributes = FileAttributes()) throws { } public static func createDirectory(atPath path: String, withIntermediateDirectories createIntermediates: Bool = false, attributes: FileAttributes = FileAttributes()) throws { if createIntermediates { fatalError("Not Implemented") } guard mkdir(path, attributes.st_mode) == 0 else { throw POSIXError.fromErrorNumber! } } public static func removeItem(atPath path: String) throws { guard remove(path) == 0 else { throw POSIXError.fromErrorNumber! } } // MARK: - Creating Symbolic and Hard Links public static func createSymbolicLink(atPath path: String, withDestinationPath destinationPath: String) throws { } public static func linkItemAtPath(path: String, toPath destinationPath: String) throws { } public static func destinationOfSymbolicLink(atPath path: String) throws -> String { fatalError() } // MARK: - Moving and Copying Items public static func copyItem(atPath sourcePath: String, toPath destinationPath: String) throws { } public static func moveItem(atPath sourcePath: String, toPath destinationPath: String) throws { } // MARK: - Getting and Setting Attributes public static func attributesOfItem(atPath path: String) throws -> FileAttributes { return try FileAttributes(path: path) } public static func setAttributes(attributes: FileAttributes, ofItemAtPath path: String) throws { // let originalAttributes = try self.attributesOfItem(atPath: path) } public static func attributesOfFileSystem(forPath path: String) throws -> FileSystemAttributes { return try FileSystemAttributes(path: path) } // MARK: - Getting and Comparing File Contents public static func contents(atPath path: String) -> Data? { guard self.fileExists(atPath: path) else { return nil } return [] } }
ec62a48ed1c7515508e763dae1ac4898
27
178
0.599647
false
false
false
false
stripe/stripe-ios
refs/heads/master
StripeIdentity/StripeIdentity/Source/NativeComponents/Views/Selfie/SelfieCaptureView.swift
mit
1
// // SelfieCaptureView.swift // StripeIdentity // // Created by Mel Ludowise on 4/27/22. // Copyright © 2022 Stripe, Inc. All rights reserved. // @_spi(STP) import StripeUICore import UIKit /// Displays either an instructional camera scanning view or an error message final class SelfieCaptureView: UIView { struct Styling { // Used for errorView and vertical insets of scanningView static let contentInsets = IdentityFlowView.Style.defaultContentViewInsets } enum ViewModel { case scan(SelfieScanningView.ViewModel) case error(ErrorView.ViewModel) } private let scanningView = SelfieScanningView() private let errorView = ErrorView() private lazy var stackView: UIStackView = { let stackView = UIStackView() stackView.axis = .vertical stackView.alignment = .center stackView.distribution = .fill return stackView }() // MARK: - Init init() { super.init(frame: .zero) installViews() installConstraints() } required init?( coder: NSCoder ) { fatalError("init(coder:) has not been implemented") } // MARK: Configure func configure(with viewModel: ViewModel, analyticsClient: IdentityAnalyticsClient?) { switch viewModel { case .scan(let scanningViewModel): scanningView.configure( with: scanningViewModel, analyticsClient: analyticsClient ) scanningView.isHidden = false errorView.isHidden = true case .error(let errorViewModel): errorView.configure(with: errorViewModel) scanningView.isHidden = true errorView.isHidden = false } } } // MARK: - Private Helpers extension SelfieCaptureView { fileprivate func installViews() { // Add top/bottom content insets to stackView addAndPinSubview( stackView, insets: .init( top: Styling.contentInsets.top, leading: 0, bottom: Styling.contentInsets.bottom, trailing: 0 ) ) stackView.addArrangedSubview(scanningView) stackView.addArrangedSubview(errorView) } fileprivate func installConstraints() { // Add the horizontal contentInset to errorView (scanningView has horizontal insets built in already) NSLayoutConstraint.activate([ widthAnchor.constraint( equalTo: errorView.widthAnchor, constant: Styling.contentInsets.leading + Styling.contentInsets.trailing ), scanningView.widthAnchor.constraint(equalTo: widthAnchor), ]) } }
acca3ada13a9a490ef1892049d46b871
27.183673
109
0.623099
false
false
false
false
hirohisa/RxSwift
refs/heads/master
RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchCell.swift
mit
3
// // WikipediaSearchCell.swift // Example // // Created by Krunoslav Zaher on 3/28/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif public class WikipediaSearchCell: UITableViewCell { @IBOutlet var titleOutlet: UILabel! @IBOutlet var URLOutlet: UILabel! @IBOutlet var imagesOutlet: UICollectionView! var disposeBag: DisposeBag! let imageService = DefaultImageService.sharedImageService public override func awakeFromNib() { super.awakeFromNib() self.imagesOutlet.registerNib(UINib(nibName: "WikipediaImageCell", bundle: nil), forCellWithReuseIdentifier: "ImageCell") } var viewModel: SearchResultViewModel! { didSet { let $ = viewModel.$ let disposeBag = DisposeBag() self.titleOutlet.rx_subscribeTextTo(viewModel?.title ?? just("")) >- disposeBag.addDisposable self.URLOutlet.text = viewModel.searchResult.URL.absoluteString ?? "" viewModel.imageURLs >- self.imagesOutlet.rx_subscribeItemsToWithCellIdentifier("ImageCell") { [unowned self] (_, URL, cell: CollectionViewImageCell) in let loadingPlaceholder: UIImage? = nil cell.image = self.imageService.imageFromURL(URL) >- map { $0 as UIImage? } >- catch(nil) >- startWith(loadingPlaceholder) } >- disposeBag.addDisposable self.disposeBag = disposeBag } } public override func prepareForReuse() { super.prepareForReuse() self.disposeBag = nil } deinit { } }
a6b6f8b76cbb16c5cbd06c590a3cf8bb
28.03125
147
0.595046
false
false
false
false
open-swift/S4
refs/heads/master
Tests/S4Tests/XcTest.swift
mit
2
import Foundation import XCTest extension XCTestCase { class func series(tasks asyncTasks: [((Void) -> Void) -> Void], completion: @escaping (Void) -> Void) { var index = 0 func _series(_ current: (((Void) -> Void) -> Void)) { current { index += 1 index < asyncTasks.count ? _series(asyncTasks[index]) : completion() } } _series(asyncTasks[index]) } #if swift(>=3.0) func waitForExpectations(delay sec: TimeInterval = 1, withDescription: String, callback: ((Void) -> Void) -> Void) { let expectation = self.expectation(description: withDescription) let done = { expectation.fulfill() } callback(done) self.waitForExpectations(timeout: sec) { XCTAssertNil($0, "Timeout of \(Int(sec)) exceeded") } } #else func waitForExpectations(delay sec: NSTimeInterval = 1, withDescription: String, callback: ((Void) -> Void) -> Void) { let expectation = self.expectationWithDescription(withDescription) let done = { expectation.fulfill() } callback(done) waitForExpectationsWithTimeout(sec) { XCTAssertNil($0, "Timeout of \(Int(sec)) exceeded") } } #endif }
9a975bf4ffd5a065f57f448a14fddf2e
28.888889
122
0.560595
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
refs/heads/master
04-App Architecture/Swift 3/4-4-Presentation/PresentingDemo4/PresentingDemo/ViewController.swift
mit
2
// // ViewController.swift // PresentingDemo // // Created by Nicholas Outram on 14/01/2016. // Copyright © 2016 Plymouth University. All rights reserved. // import UIKit class ViewController: UIViewController, ModalViewController1Protocol { @IBOutlet weak var resultLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? ModalViewController1 { vc.delegate = self switch (segue.identifier) { case "DEMO1"?: vc.titleText = "DEMO 1" case "DEMO2"?: vc.titleText = "DEMO 2" default: break } //end switch } //end if } @IBAction func doDemo2(_ sender: AnyObject) { self.performSegue(withIdentifier: "DEMO2", sender: self) } @IBAction func doDemo3(_ sender: AnyObject) { let sb = UIStoryboard(name: "ModalStoryboard", bundle: nil) if let vc = sb.instantiateViewController(withIdentifier: "DEMO3") as? ModalViewController1{ vc.delegate = self vc.titleText = "DEMO 3" self.present(vc, animated: true, completion: { }) } } @IBAction func doDemo4(_ sender: AnyObject) { let vc = ModalViewController1(nibName: "Demo4", bundle: nil) vc.delegate = self vc.titleText = "DEMO 4" self.present(vc, animated: true, completion: { }) } //Call back func dismissWithStringData(_ str: String) { self.dismiss(animated: true) { self.resultLabel.text = str } } }
f704c169f015a727136ef601c08c075c
25.727273
99
0.562196
false
false
false
false
tavon321/GluberLabConceptTest
refs/heads/master
GluberLabConceptTest/GluberLabConceptTest/Layer+Customization.swift
mit
1
// // Layer+Customization.swift // GluberLabConceptTest // // Created by Gustavo Mario Londoño Correa on 4/20/17. // Copyright © 2017 Gustavo Mario Londoño Correa. All rights reserved. // import Foundation import UIKit extension UIView { // MARK: - Corners @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } // MARK: - Rounded @IBInspectable var rounded: Bool { get { return layer.masksToBounds } set { if newValue { layer.cornerRadius = layer.frame.midX / 10 layer.masksToBounds = true } } } // MARK: - Shadows @IBInspectable var shadowRadius: Double { get { return Double(self.layer.shadowRadius) } set { self.layer.shadowRadius = CGFloat(newValue) } } // The opacity of the shadow. Defaults to 0. Specifying a value outside the [0,1] range will give undefined results. Animatable. @IBInspectable var shadowOpacity: Float { get { return self.layer.shadowOpacity } set { self.layer.shadowOpacity = newValue } } // The shadow offset. Defaults to (0, -3). Animatable. @IBInspectable var shadowOffset: CGSize { get { return self.layer.shadowOffset } set { self.layer.shadowOffset = newValue } } // The color of the shadow. Defaults to opaque black. Colors created from patterns are currently NOT supported. Animatable. @IBInspectable var shadowColor: UIColor? { get { return UIColor(cgColor: self.layer.shadowColor ?? UIColor.clear.cgColor) } set { self.layer.shadowColor = newValue?.cgColor } } // Off - Will show shadow | On - Won't show shadow. @IBInspectable var masksToBounds: Bool { get { return self.layer.masksToBounds } set { self.layer.masksToBounds = newValue } } }
bd381804c7ccacdbed7bea3a42f396db
25.831325
132
0.563089
false
false
false
false
danielcwj16/ConnectedAlarmApp
refs/heads/master
Pods/SwiftAddressBook/Pod/Classes/SwiftAddressBookWrapper.swift
mit
2
//SwiftAddressBook - A strong-typed Swift Wrapper for ABAddressBook //Copyright (C) 2014 Socialbit GmbH // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. import UIKit import AddressBook @available(iOS, deprecated: 9.0) //MARK: global address book variable (automatically lazy) public let swiftAddressBook : SwiftAddressBook! = SwiftAddressBook() public var accessError : CFError? //MARK: Address Book open class SwiftAddressBook { open var internalAddressBook : ABAddressBook! //fileprivate lazy var addressBookObserver = SwiftAddressBookObserver() public init?() { var err : Unmanaged<CFError>? = nil let abUnmanaged : Unmanaged<ABAddressBook>? = ABAddressBookCreateWithOptions(nil, &err) //assign error or internalAddressBook, according to outcome if err == nil { internalAddressBook = abUnmanaged?.takeRetainedValue() } else { accessError = err?.takeRetainedValue() return nil } } open class func authorizationStatus() -> ABAuthorizationStatus { return ABAddressBookGetAuthorizationStatus() } open class func requestAccessWithCompletion( _ completion : @escaping (Bool, CFError?) -> Void ) { ABAddressBookRequestAccessWithCompletion(nil, completion) } open func hasUnsavedChanges() -> Bool { return ABAddressBookHasUnsavedChanges(internalAddressBook) } open func save() -> CFError? { return errorIfNoSuccess { ABAddressBookSave(self.internalAddressBook, $0)} } open func revert() { ABAddressBookRevert(internalAddressBook) } open func addRecord(_ record : SwiftAddressBookRecord) -> CFError? { return errorIfNoSuccess { ABAddressBookAddRecord(self.internalAddressBook, record.internalRecord, $0) } } open func removeRecord(_ record : SwiftAddressBookRecord) -> CFError? { return errorIfNoSuccess { ABAddressBookRemoveRecord(self.internalAddressBook, record.internalRecord, $0) } } //MARK: person records open var personCount : Int { return ABAddressBookGetPersonCount(internalAddressBook) } open func personWithRecordId(_ recordId : Int32) -> SwiftAddressBookPerson? { return SwiftAddressBookPerson(record: ABAddressBookGetPersonWithRecordID(internalAddressBook, recordId)?.takeUnretainedValue()) } open var allPeople : [SwiftAddressBookPerson]? { return convertRecordsToPersons(ABAddressBookCopyArrayOfAllPeople(internalAddressBook).takeRetainedValue()) } // open func registerExternalChangeCallback(_ callback: @escaping () -> Void) { // addressBookObserver.startObserveChanges { (addressBook) -> Void in // callback() // } // } // // open func unregisterExternalChangeCallback(_ callback: () -> Void) { // addressBookObserver.stopObserveChanges() // callback() // } open var allPeopleExcludingLinkedContacts : [SwiftAddressBookPerson]? { if let all = allPeople { let filtered : NSMutableArray = NSMutableArray(array: all) for person in all { if !(NSArray(array: filtered) as! [SwiftAddressBookPerson]).contains(where: { (p : SwiftAddressBookPerson) -> Bool in return p.recordID == person.recordID }) { //already filtered out this contact continue } //throw out duplicates let allFiltered : [SwiftAddressBookPerson] = NSArray(array: filtered) as! [SwiftAddressBookPerson] for possibleDuplicate in allFiltered { if let linked = person.allLinkedPeople { if possibleDuplicate.recordID != person.recordID && linked.contains(where: { (p : SwiftAddressBookPerson) -> Bool in return p.recordID == possibleDuplicate.recordID }) { (filtered as NSMutableArray).remove(possibleDuplicate) } } } } return NSArray(array: filtered) as? [SwiftAddressBookPerson] } return nil } open func allPeopleInSource(_ source : SwiftAddressBookSource) -> [SwiftAddressBookPerson]? { return convertRecordsToPersons(ABAddressBookCopyArrayOfAllPeopleInSource(internalAddressBook, source.internalRecord).takeRetainedValue()) } open func allPeopleInSourceWithSortOrdering(_ source : SwiftAddressBookSource, ordering : SwiftAddressBookOrdering) -> [SwiftAddressBookPerson]? { return convertRecordsToPersons(ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(internalAddressBook, source.internalRecord, ordering.abPersonSortOrderingValue).takeRetainedValue()) } open func peopleWithName(_ name : String) -> [SwiftAddressBookPerson]? { return convertRecordsToPersons(ABAddressBookCopyPeopleWithName(internalAddressBook, (name as CFString)).takeRetainedValue()) } //MARK: group records open func groupWithRecordId(_ recordId : Int32) -> SwiftAddressBookGroup? { return SwiftAddressBookGroup(record: ABAddressBookGetGroupWithRecordID(internalAddressBook, recordId)?.takeUnretainedValue()) } open var groupCount : Int { return ABAddressBookGetGroupCount(internalAddressBook) } open var arrayOfAllGroups : [SwiftAddressBookGroup]? { return convertRecordsToGroups(ABAddressBookCopyArrayOfAllGroups(internalAddressBook).takeRetainedValue()) } open func allGroupsInSource(_ source : SwiftAddressBookSource) -> [SwiftAddressBookGroup]? { return convertRecordsToGroups(ABAddressBookCopyArrayOfAllGroupsInSource(internalAddressBook, source.internalRecord).takeRetainedValue()) } //MARK: sources open var defaultSource : SwiftAddressBookSource? { return SwiftAddressBookSource(record: ABAddressBookCopyDefaultSource(internalAddressBook)?.takeRetainedValue()) } open func sourceWithRecordId(_ sourceId : Int32) -> SwiftAddressBookSource? { return SwiftAddressBookSource(record: ABAddressBookGetSourceWithRecordID(internalAddressBook, sourceId)?.takeUnretainedValue()) } open var allSources : [SwiftAddressBookSource]? { return convertRecordsToSources(ABAddressBookCopyArrayOfAllSources(internalAddressBook).takeRetainedValue()) } }
9393ca8fb30007d13d7366614a935a4d
35.808989
197
0.7384
false
false
false
false
ArnavChawla/InteliChat
refs/heads/master
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/DocumentSnapshot.swift
mit
1
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** DocumentSnapshot. */ public struct DocumentSnapshot: Decodable { public enum Step: String { case htmlInput = "html_input" case htmlOutput = "html_output" case jsonOutput = "json_output" case jsonNormalizationsOutput = "json_normalizations_output" case enrichmentsOutput = "enrichments_output" case normalizationsOutput = "normalizations_output" } public var step: String? public var snapshot: [String: JSON]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case step = "step" case snapshot = "snapshot" } }
e0c3594e20c2880fafca6bca5818ea8f
30.731707
82
0.700231
false
false
false
false
choofie/MusicTinder
refs/heads/master
MusicTinder/Classes/BusinessLogic/Services/Chart/ChartService.swift
mit
1
// // ChartService.swift // MusicTinder // // Created by Mate Lorincz on 05/11/16. // Copyright © 2016 MateLorincz. All rights reserved. // import Foundation protocol GetTopArtistDelegate : class { func getTopArtistsFinishedWithResult(_ result: [Artist]) func getTopArtistsFinishedWithError(_ error: String) } let DefaultTimeoutInterval = 20.0 class ChartService { fileprivate weak var getTopArtistDelegate: GetTopArtistDelegate? required init(getTopArtistDelegate : GetTopArtistDelegate) { self.getTopArtistDelegate = getTopArtistDelegate } func getTopArtists() { guard let urlString = URLProvider.topArtistsURL() else { getTopArtistDelegate?.getTopArtistsFinishedWithError("Error with urlString") return } guard let url = URL(string: urlString.appendResultFormat(.JSON)) else { return } var request = URLRequest(url: url) request.httpMethod = "GET" request.timeoutInterval = DefaultTimeoutInterval let session = URLSession.shared let task = session.dataTask(with: request) { (data, response, error) -> Void in if let _ = error { self.loadGetTopArtistsCachedResponse() } else { guard let data = data else { self.loadGetTopArtistsCachedResponse() return } do { let jsonResult = try JSONSerialization.jsonObject(with: data, options:.allowFragments) let artists = self.processResultData(jsonResult as AnyObject) if artists.isEmpty { self.loadGetTopArtistsCachedResponse() } else { self.getTopArtistDelegate?.getTopArtistsFinishedWithResult(self.processResultData(jsonResult as AnyObject)) } } catch _ as NSError { self.loadGetTopArtistsCachedResponse() } } } task.resume() } } private extension ChartService { func loadGetTopArtistsCachedResponse() { if let path = Bundle.main.path(forResource: "topArtists", ofType: "json") { do { let jsonData = try Data(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions.mappedIfSafe) let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options:.allowFragments) getTopArtistDelegate?.getTopArtistsFinishedWithResult(processResultData(jsonResult as AnyObject)) } catch let error as NSError { getTopArtistDelegate?.getTopArtistsFinishedWithError(error.localizedDescription) } } else { getTopArtistDelegate?.getTopArtistsFinishedWithError("Invalid filename/path") } } func processResultData(_ resultData: AnyObject) -> [Artist] { var result: [Artist] = [] if let artistsDictionary = resultData["artists"] as? [String : AnyObject] { if let artistArray = artistsDictionary["artist"] as? [AnyObject] { for artistData in artistArray { if let artistData = artistData as? [String : AnyObject] { if let name = artistData["name"] as? String, let mbid = artistData["mbid"] as? String, let images = artistData["image"] as? [[String : String]] { if let imageURL = images[images.count - 2]["#text"], imageURL.isEmpty == false { result.append(Artist(name: name , mbid: mbid , info: "no info", genre: "no genre", imageURL: URL(string:imageURL)!)) } } } } } } return result } }
5879230352a4960cc6cb078445fefbcc
35.526786
169
0.556588
false
false
false
false
MadAppGang/SmartLog
refs/heads/master
Pods/CoreStore/Sources/CSDataStack.swift
mit
2
// // CSDataStack.swift // CoreStore // // Copyright © 2016 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. // import Foundation import CoreData // MARK: - CSDataStack /** The `CSDataStack` serves as the Objective-C bridging type for `DataStack`. - SeeAlso: `DataStack` */ @objc public final class CSDataStack: NSObject, CoreStoreObjectiveCType { /** Initializes a `CSDataStack` with default settings. CoreStore searches for <CFBundleName>.xcdatamodeld from the main `NSBundle` and loads an `NSManagedObjectModel` from it. An assertion is raised if the model could not be found. */ @objc public convenience override init() { self.init(DataStack()) } /** Initializes a `CSDataStack` from the model with the specified `modelName` in the specified `bundle`. - parameter xcodeModelName: the name of the (.xcdatamodeld) model file. If not specified, the application name (CFBundleName) will be used if it exists, or "CoreData" if it the bundle name was not set. - parameter bundle: an optional bundle to load models from. If not specified, the main bundle will be used. - parameter versionChain: the version strings that indicate the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack. */ @objc public convenience init(xcodeModelName: XcodeDataModelFileName?, bundle: Bundle?, versionChain: [String]?) { self.init( DataStack( xcodeModelName: xcodeModelName ?? DataStack.applicationName, bundle: bundle ?? Bundle.main, migrationChain: versionChain.flatMap { MigrationChain($0) } ?? nil ) ) } /** Returns the stack's model version. The version string is the same as the name of the version-specific .xcdatamodeld file. */ @objc public var modelVersion: String { return self.bridgeToSwift.modelVersion } /** Returns the entity name-to-class type mapping from the `CSDataStack`'s model. */ @objc public func entityTypesByNameForType(_ type: NSManagedObject.Type) -> [EntityName: NSManagedObject.Type] { return self.bridgeToSwift.entityTypesByName(for: type) } /** Returns the `NSEntityDescription` for the specified `NSManagedObject` subclass from stack's model. */ @objc public func entityDescriptionForClass(_ type: NSManagedObject.Type) -> NSEntityDescription? { return self.bridgeToSwift.entityDescription(for: type) } /** Creates an `CSInMemoryStore` with default parameters and adds it to the stack. This method blocks until completion. ``` CSSQLiteStore *storage = [dataStack addInMemoryStorageAndWaitAndReturnError:&error]; ``` - parameter error: the `NSError` pointer that indicates the reason in case of an failure - returns: the `CSInMemoryStore` added to the stack */ @objc @discardableResult public func addInMemoryStorageAndWaitAndReturnError(_ error: NSErrorPointer) -> CSInMemoryStore? { return bridge(error) { try self.bridgeToSwift.addStorageAndWait(InMemoryStore()) } } /** Creates an `CSSQLiteStore` with default parameters and adds it to the stack. This method blocks until completion. ``` CSSQLiteStore *storage = [dataStack addSQLiteStorageAndWaitAndReturnError:&error]; ``` - parameter error: the `NSError` pointer that indicates the reason in case of an failure - returns: the `CSSQLiteStore` added to the stack */ @objc @discardableResult public func addSQLiteStorageAndWaitAndReturnError(_ error: NSErrorPointer) -> CSSQLiteStore? { return bridge(error) { try self.bridgeToSwift.addStorageAndWait(SQLiteStore()) } } /** Adds a `CSInMemoryStore` to the stack and blocks until completion. ``` NSError *error; CSInMemoryStore *storage = [dataStack addStorageAndWait: [[CSInMemoryStore alloc] initWithConfiguration: @"Config1"] error: &error]; ``` - parameter storage: the `CSInMemoryStore` - parameter error: the `NSError` pointer that indicates the reason in case of an failure - returns: the `CSInMemoryStore` added to the stack */ @objc @discardableResult public func addInMemoryStorageAndWait(_ storage: CSInMemoryStore, error: NSErrorPointer) -> CSInMemoryStore? { return bridge(error) { try self.bridgeToSwift.addStorageAndWait(storage.bridgeToSwift) } } /** Adds a `CSSQLiteStore` to the stack and blocks until completion. ``` NSError *error; CSSQLiteStore *storage = [dataStack addStorageAndWait: [[CSSQLiteStore alloc] initWithConfiguration: @"Config1"] error: &error]; ``` - parameter storage: the `CSSQLiteStore` - parameter error: the `NSError` pointer that indicates the reason in case of an failure - returns: the `CSSQLiteStore` added to the stack */ @objc @discardableResult public func addSQLiteStorageAndWait(_ storage: CSSQLiteStore, error: NSErrorPointer) -> CSSQLiteStore? { return bridge(error) { try self.bridgeToSwift.addStorageAndWait(storage.bridgeToSwift) } } // MARK: NSObject public override var hash: Int { return ObjectIdentifier(self.bridgeToSwift).hashValue } public override func isEqual(_ object: Any?) -> Bool { guard let object = object as? CSDataStack else { return false } return self.bridgeToSwift == object.bridgeToSwift } public override var description: String { return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)" } // MARK: CoreStoreObjectiveCType public let bridgeToSwift: DataStack public init(_ swiftValue: DataStack) { self.bridgeToSwift = swiftValue super.init() } // MARK: Deprecated @available(*, deprecated, message: "Use the -[initWithXcodeModelName:bundle:versionChain:] initializer.") @objc public convenience init(modelName: XcodeDataModelFileName?, bundle: Bundle?, versionChain: [String]?) { self.init( DataStack( xcodeModelName: modelName ?? DataStack.applicationName, bundle: bundle ?? Bundle.main, migrationChain: versionChain.flatMap { MigrationChain($0) } ?? nil ) ) } @available(*, deprecated, message: "Use the -[initWithModelName:bundle:versionChain:] initializer.") @objc public convenience init(model: NSManagedObjectModel, versionChain: [String]?) { self.init( DataStack( model: model, migrationChain: versionChain.flatMap { MigrationChain($0) } ?? nil ) ) } @available(*, deprecated, message: "Use the -[initWithModelName:bundle:versionTree:] initializer.") @objc public convenience init(model: NSManagedObjectModel, versionTree: [String]?) { self.init( DataStack( model: model, migrationChain: versionTree.flatMap { MigrationChain($0) } ?? nil ) ) } @available(*, deprecated, message: "Use the new -entityTypesByNameForType: method passing `[NSManagedObject class]` as argument.") @objc public var entityClassesByName: [EntityName: NSManagedObject.Type] { return self.bridgeToSwift.entityTypesByName } @available(*, deprecated, message: "Use the new -entityTypesByNameForType: method passing `[NSManagedObject class]` as argument.") @objc public func entityClassWithName(_ name: EntityName) -> NSManagedObject.Type? { return self.bridgeToSwift.entityTypesByName[name] } } // MARK: - DataStack extension DataStack: CoreStoreSwiftType { // MARK: CoreStoreSwiftType public var bridgeToObjectiveC: CSDataStack { return CSDataStack(self) } }
70cfde90f1b12e22d8dfef24000352c3
33.744526
232
0.652626
false
true
false
false
Dwarven/ShadowsocksX-NG
refs/heads/develop
MoyaRefreshToken/Pods/RxSwift/RxSwift/Observables/Just.swift
apache-2.0
4
// // Just.swift // RxSwift // // Created by Krunoslav Zaher on 8/30/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Returns an observable sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting observable sequence. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: E) -> Observable<E> { return Just(element: element) } /** Returns an observable sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting observable sequence. - parameter scheduler: Scheduler to send the single element on. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: E, scheduler: ImmediateSchedulerType) -> Observable<E> { return JustScheduled(element: element, scheduler: scheduler) } } final private class JustScheduledSink<O: ObserverType>: Sink<O> { typealias Parent = JustScheduled<O.E> private let _parent: Parent init(parent: Parent, observer: O, cancel: Cancelable) { self._parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let scheduler = self._parent._scheduler return scheduler.schedule(self._parent._element) { element in self.forwardOn(.next(element)) return scheduler.schedule(()) { _ in self.forwardOn(.completed) self.dispose() return Disposables.create() } } } } final private class JustScheduled<Element>: Producer<Element> { fileprivate let _scheduler: ImmediateSchedulerType fileprivate let _element: Element init(element: Element, scheduler: ImmediateSchedulerType) { self._scheduler = scheduler self._element = element } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { let sink = JustScheduledSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } } final private class Just<Element>: Producer<Element> { private let _element: Element init(element: Element) { self._element = element } override func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element { observer.on(.next(self._element)) observer.on(.completed) return Disposables.create() } }
704b4acbf6c3503f591f7799383b2c56
32.390805
139
0.662306
false
false
false
false
BrandonMA/SwifterUI
refs/heads/master
Floral/Pods/Kingfisher/Sources/Networking/ImageDataProcessor.swift
apache-2.0
9
// // ImageDataProcessor.swift // Kingfisher // // Created by Wei Wang on 2018/10/11. // // Copyright (c) 2019 Wei Wang <onevcat@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation private let sharedProcessingQueue: CallbackQueue = .dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process")) // Handles image processing work on an own process queue. class ImageDataProcessor { let data: Data let callbacks: [SessionDataTask.TaskCallback] let queue: CallbackQueue // Note: We have an optimization choice there, to reduce queue dispatch by checking callback // queue settings in each option... let onImageProcessed = Delegate<(Result<Image, KingfisherError>, SessionDataTask.TaskCallback), Void>() init(data: Data, callbacks: [SessionDataTask.TaskCallback], processingQueue: CallbackQueue?) { self.data = data self.callbacks = callbacks self.queue = processingQueue ?? sharedProcessingQueue } func process() { queue.execute(doProcess) } private func doProcess() { var processedImages = [String: Image]() for callback in callbacks { let processor = callback.options.processor var image = processedImages[processor.identifier] if image == nil { image = processor.process(item: .data(data), options: callback.options) processedImages[processor.identifier] = image } let result: Result<Image, KingfisherError> if let image = image { var finalImage = image if let imageModifier = callback.options.imageModifier { finalImage = imageModifier.modify(image) } if callback.options.backgroundDecode { finalImage = finalImage.kf.decoded } result = .success(finalImage) } else { let error = KingfisherError.processorError( reason: .processingFailed(processor: processor, item: .data(data))) result = .failure(error) } onImageProcessed.call((result, callback)) } } }
98bbcddc5844d34075e116aaa7f2146b
40.1
107
0.665754
false
false
false
false
Speicher210/wingu-sdk-ios-demoapp
refs/heads/master
Example/Pods/RSBarcodes_Swift/Source/RSCode93Generator.swift
apache-2.0
2
// // RSCode93Generator.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/11/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit // http://www.barcodeisland.com/code93.phtml open class RSCode93Generator: RSAbstractCodeGenerator, RSCheckDigitGenerator { let CODE93_ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*" let CODE93_PLACEHOLDER_STRING = "abcd"; let CODE93_CHARACTER_ENCODINGS = [ "100010100", "101001000", "101000100", "101000010", "100101000", "100100100", "100100010", "101010000", "100010010", "100001010", "110101000", "110100100", "110100010", "110010100", "110010010", "110001010", "101101000", "101100100", "101100010", "100110100", "100011010", "101011000", "101001100", "101000110", "100101100", "100010110", "110110100", "110110010", "110101100", "110100110", "110010110", "110011010", "101101100", "101100110", "100110110", "100111010", "100101110", "111010100", "111010010", "111001010", "101101110", "101110110", "110101110", "100100110", "111011010", "111010110", "100110010", "101011110" ] func encodeCharacterString(_ characterString:String) -> String { return CODE93_CHARACTER_ENCODINGS[CODE93_ALPHABET_STRING.location(characterString)] } override open func isValid(_ contents: String) -> Bool { if contents.length() > 0 && contents == contents.uppercased() { for i in 0..<contents.length() { if CODE93_ALPHABET_STRING.location(contents[i]) == NSNotFound { return false } if CODE93_PLACEHOLDER_STRING.location(contents[i]) != NSNotFound { return false } } return true } return false } override open func initiator() -> String { return self.encodeCharacterString("*") } override open func terminator() -> String { // With the termination bar: 1 return self.encodeCharacterString("*") + "1" } override open func barcode(_ contents: String) -> String { var barcode = "" for character in contents.characters { barcode += self.encodeCharacterString(String(character)) } let checkDigits = self.checkDigit(contents) for character in checkDigits.characters { barcode += self.encodeCharacterString(String(character)) } return barcode } // MARK: RSCheckDigitGenerator open func checkDigit(_ contents: String) -> String { // Weighted sum += value * weight // The first character var sum = 0 for i in 0..<contents.length() { if let character = contents[contents.length() - i - 1] { let characterValue = CODE93_ALPHABET_STRING.location(character) sum += characterValue * (i % 20 + 1) } } var checkDigits = "" checkDigits += CODE93_ALPHABET_STRING[sum % 47] // The second character sum = 0 let newContents = contents + checkDigits for i in 0..<newContents.length() { if let character = newContents[newContents.length() - i - 1] { let characterValue = CODE93_ALPHABET_STRING.location(character) sum += characterValue * (i % 15 + 1) } } checkDigits += CODE93_ALPHABET_STRING[sum % 47] return checkDigits } }
7513479416c1dc86f001faa053ee6ba6
27.231884
91
0.536961
false
false
false
false
JaSpa/swift
refs/heads/master
stdlib/public/SDK/AppKit/NSError.swift
apache-2.0
8
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import AppKit extension CocoaError.Code { public static var textReadInapplicableDocumentType: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } public static var textWriteInapplicableDocumentType: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } public static var serviceApplicationNotFound: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } public static var serviceApplicationLaunchFailed: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } public static var serviceRequestTimedOut: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } public static var serviceInvalidPasteboardData: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } public static var serviceMalformedServiceDictionary: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } public static var serviceMiscellaneous: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } public static var sharingServiceNotConfigured: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } } // Names deprecated late in Swift 3 extension CocoaError.Code { @available(*, deprecated, renamed: "textReadInapplicableDocumentType") public static var textReadInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") public static var textWriteInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } @available(*, deprecated, renamed: "serviceApplicationNotFound") public static var serviceApplicationNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") public static var serviceApplicationLaunchFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } @available(*, deprecated, renamed: "serviceRequestTimedOut") public static var serviceRequestTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } @available(*, deprecated, renamed: "serviceInvalidPasteboardData") public static var serviceInvalidPasteboardDataError: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") public static var serviceMalformedServiceDictionaryError: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } @available(*, deprecated, renamed: "serviceMiscellaneous") public static var serviceMiscellaneousError: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } @available(*, deprecated, renamed: "sharingServiceNotConfigured") public static var sharingServiceNotConfiguredError: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } } extension CocoaError { public static var textReadInapplicableDocumentType: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } public static var textWriteInapplicableDocumentType: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } public static var serviceApplicationNotFound: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } public static var serviceApplicationLaunchFailed: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } public static var serviceRequestTimedOut: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } public static var serviceInvalidPasteboardData: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } public static var serviceMalformedServiceDictionary: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } public static var serviceMiscellaneous: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } public static var sharingServiceNotConfigured: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } } // Names deprecated late in Swift 3 extension CocoaError { @available(*, deprecated, renamed: "textReadInapplicableDocumentType") public static var textReadInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") public static var textWriteInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } @available(*, deprecated, renamed: "serviceApplicationNotFound") public static var serviceApplicationNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") public static var serviceApplicationLaunchFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } @available(*, deprecated, renamed: "serviceRequestTimedOut") public static var serviceRequestTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } @available(*, deprecated, renamed: "serviceInvalidPasteboardData") public static var serviceInvalidPasteboardDataError: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") public static var serviceMalformedServiceDictionaryError: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } @available(*, deprecated, renamed: "serviceMiscellaneous") public static var serviceMiscellaneousError: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } @available(*, deprecated, renamed: "sharingServiceNotConfigured") public static var sharingServiceNotConfiguredError: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } } extension CocoaError { public var isServiceError: Bool { return code.rawValue >= 66560 && code.rawValue <= 66817 } public var isSharingServiceError: Bool { return code.rawValue >= 67072 && code.rawValue <= 67327 } public var isTextReadWriteError: Bool { return code.rawValue >= 65792 && code.rawValue <= 66303 } } extension CocoaError { @available(*, deprecated, renamed: "textReadInapplicableDocumentType") public static var TextReadInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") public static var TextWriteInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } @available(*, deprecated, renamed: "serviceApplicationNotFound") public static var ServiceApplicationNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") public static var ServiceApplicationLaunchFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } @available(*, deprecated, renamed: "serviceRequestTimedOut") public static var ServiceRequestTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } @available(*, deprecated, renamed: "serviceInvalidPasteboardData") public static var ServiceInvalidPasteboardDataError: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") public static var ServiceMalformedServiceDictionaryError: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } @available(*, deprecated, renamed: "serviceMiscellaneous") public static var ServiceMiscellaneousError: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } @available(*, deprecated, renamed: "sharingServiceNotConfigured") public static var SharingServiceNotConfiguredError: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } } extension CocoaError.Code { @available(*, deprecated, renamed: "textReadInapplicableDocumentType") public static var TextReadInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 65806) } @available(*, deprecated, renamed: "textWriteInapplicableDocumentType") public static var TextWriteInapplicableDocumentTypeError: CocoaError.Code { return CocoaError.Code(rawValue: 66062) } @available(*, deprecated, renamed: "serviceApplicationNotFound") public static var ServiceApplicationNotFoundError: CocoaError.Code { return CocoaError.Code(rawValue: 66560) } @available(*, deprecated, renamed: "serviceApplicationLaunchFailed") public static var ServiceApplicationLaunchFailedError: CocoaError.Code { return CocoaError.Code(rawValue: 66561) } @available(*, deprecated, renamed: "serviceRequestTimedOut") public static var ServiceRequestTimedOutError: CocoaError.Code { return CocoaError.Code(rawValue: 66562) } @available(*, deprecated, renamed: "serviceInvalidPasteboardData") public static var ServiceInvalidPasteboardDataError: CocoaError.Code { return CocoaError.Code(rawValue: 66563) } @available(*, deprecated, renamed: "serviceMalformedServiceDictionary") public static var ServiceMalformedServiceDictionaryError: CocoaError.Code { return CocoaError.Code(rawValue: 66564) } @available(*, deprecated, renamed: "serviceMiscellaneous") public static var ServiceMiscellaneousError: CocoaError.Code { return CocoaError.Code(rawValue: 66800) } @available(*, deprecated, renamed: "sharingServiceNotConfigured") public static var SharingServiceNotConfiguredError: CocoaError.Code { return CocoaError.Code(rawValue: 67072) } }
32778c06aca2a372c3f322d246bfb16b
40.172131
80
0.763787
false
false
false
false
p-rothen/PRViews
refs/heads/master
PRViews/RoundedButton.swift
mit
1
// // RoundedButton.swift // Doctor Cloud // // Created by Pedro on 14-12-16. // Copyright © 2016 IQS. All rights reserved. // import UIKit public class RoundedButton : UIButton { public override init(frame: CGRect) { super.init(frame: frame) self.setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } func setup() { self.layer.cornerRadius = 3 //Default font if let fontName = self.titleLabel?.font.fontName where fontName == ".SFUIText" { self.titleLabel?.font = UIFont.boldSystemFontOfSize(15) } self.layer.shadowOpacity = 0.4; self.layer.shadowRadius = 1; self.layer.shadowColor = UIColor.blackColor().CGColor; self.layer.shadowOffset = CGSizeMake(0.5, 0.5); self.layer.masksToBounds = false } }
015a9f9d7fd5e3f57c303bf292785848
24.971429
88
0.608361
false
false
false
false
Limon-O-O/Lego
refs/heads/master
Frameworks/LegoProvider/LegoProvider/Observable+LegoProvider.swift
mit
1
// // Observable+LegoProvider.swift // Pods // // Created by Limon on 17/03/2017. // // import Foundation import RxSwift import Moya import Decodable extension Observable { public func mapObject<T: Decodable>(type: T.Type) -> Observable<T> { return map { representor in guard let response = (representor as? Moya.Response) ?? (representor as? Moya.ProgressResponse)?.response else { throw ProviderError.noRepresentor } try response.validStatusCode() let mapedJSON = try response.mapJSON() guard let json = mapedJSON as? [String: Any] else { throw ProviderError.jsonSerializationFailed } guard let object = type.decoding(json: json) else { throw ProviderError.generationObjectFailed } return object } } public func mapObjects<T: Decodable>(type: T.Type) -> Observable<[T]> { return map { representor in guard let response = (representor as? Moya.Response) ?? (representor as? Moya.ProgressResponse)?.response else { throw ProviderError.noRepresentor } try response.validStatusCode() let mapedJSON = try response.mapJSON() guard let jsons = mapedJSON as? [[String: Any]] else { throw ProviderError.jsonSerializationFailed } return jsons.flatMap { type.decoding(json: $0) } } } } extension Moya.Response { func validStatusCode() throws { guard !((200...209) ~= statusCode) else { return } if let json = try mapJSON() as? [String: Any] { print("Got error message: \(json)") // json 的`错误信息和错误码`的 key,需自行修改,与服务器对应即可 if let errorCode = json["error_code"] as? Int, let message = json["error_msg"] as? String { throw ProviderError(code: errorCode, failureReason: message) } } throw ProviderError.notSuccessfulHTTP } }
c5b74af3e41db017671d0837a17e9e83
26.065789
124
0.586291
false
false
false
false
vexy/Fridge
refs/heads/main
Sources/Fridge/Grabber.swift
mit
1
// // Grabber.swift // Fridge // Copyright (c) 2016-2022 Veljko Tekelerović /* MIT License 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 @available(macOS 12.0, *) @available(iOS 15.0, *) final internal class Grabber { func grab<D: Decodable>(from url: URL) async throws -> D { guard let rawData = try? await URLSession.shared.data(from: url).0 else { throw FridgeErrors.grabFailed } guard let decodedObject = try? JSONDecoder().decode(D.self, from: rawData) else { throw FridgeErrors.decodingFailed } // return decoded object return decodedObject } func grab<D: Decodable>(using urlRequest: URLRequest) async throws -> D { guard let rawData = try? await URLSession.shared.data(for: urlRequest).0 else { throw FridgeErrors.grabFailed } guard let decodedObject = try? JSONDecoder().decode(D.self, from: rawData) else { throw FridgeErrors.grabFailed } // return decoded object return decodedObject } //MARK: - func push<E: Encodable, D: Decodable>(object: E, urlString: String) async throws -> D { do { var request = try constructURLRequest(from: urlString) request.httpBody = try serializeObject(object) //execute request and wait for response let responseRawData = try await URLSession.shared.data(for: request).0 //first tuple item contains Data // try to decode returned data into given return type return try deserializeData(responseRawData) } catch let e { throw e //just rethrow the same error further } } func push<E: Encodable, D: Decodable>(object: E, urlRequest: URLRequest) async throws -> D { do { var request = urlRequest request.httpBody = try serializeObject(object) //execute request and wait for response let responseRawData = try await URLSession.shared.data(for: request).0 //first tuple item contains Data // try to decode returned data into given return type return try deserializeData(responseRawData) } catch let e { throw e //just rethrow the same error further } } } //MARK: - Private helpers @available(macOS 12.0, *) @available(iOS 15.0, *) extension Grabber { /// Constructs a JSON based `URLRequest` from given url `String` private func constructURLRequest(from string: String) throws -> URLRequest { guard let urlObject = URL(string: string) else { throw FridgeErrors.decodingFailed } var request = URLRequest(url: urlObject) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("Fridge.grab", forHTTPHeaderField: "User-Agent") return request } /// Serialize given object and attach it to request body private func serializeObject<E: Encodable>(_ objectToSerialize: E) throws -> Data { guard let serializedObject = try? JSONEncoder().encode(objectToSerialize.self) else { throw FridgeErrors.decodingFailed } return serializedObject } /// Tries to decode given data into given `Decodable` object private func deserializeData<D: Decodable>(_ rawData: Data) throws -> D { guard let decodedObject = try? JSONDecoder().decode(D.self, from: rawData) else { throw FridgeErrors.decodingFailed } return decodedObject } }
59039d861dad08b4829eabcbf81274d9
39.5
116
0.661132
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/DebugInfo/closure-args.swift
apache-2.0
4
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s import Swift func main() -> Void { // I am line 6. var random_string = "b" var random_int = 5 var out_only = 2013 var backward_ptr = // CHECK: define internal {{.*}} i1 @_T04mainAAyyFSbSS_SStcfU_( // CHECK: %[[RANDOM_STR_ADDR:.*]] = alloca %TSS*, align {{(4|8)}} // CHECK-NEXT: call void @llvm.dbg.declare(metadata %TSS** %[[RANDOM_STR_ADDR]], metadata !{{.*}}, metadata !DIExpression()), !dbg // CHECK: store %TSS* %{{.*}}, %TSS** %[[RANDOM_STR_ADDR]], align {{(4|8)}} // CHECK-DAG: !DILocalVariable(name: "lhs",{{.*}} line: [[@LINE+5]], // CHECK-DAG: !DILocalVariable(name: "rhs",{{.*}} line: [[@LINE+4]], // CHECK-DAG: !DILocalVariable(name: "random_string",{{.*}} line: 8, // CHECK-DAG: !DILocalVariable(name: "random_int",{{.*}} line: 9, // CHECK-DAG: !DILocalVariable(name: "out_only",{{.*}} line: 10, { (lhs : String, rhs : String) -> Bool in if rhs == random_string || rhs.unicodeScalars.count == random_int { // Ensure the two local_vars are in different lexical scopes. // CHECK-DAG: !DILocalVariable(name: "local_var", scope: ![[THENSCOPE:[0-9]+]],{{.*}} line: [[@LINE+2]], // CHECK-DAG: ![[THENSCOPE]] = distinct !DILexicalBlock({{.*}} line: [[@LINE-3]] var local_var : Int64 = 10 print("I have an int here \(local_var).\n", terminator: "") return false } else { // CHECK-DAG: !DILocalVariable(name: "local_var", scope: ![[ELSESCOPE:[0-9]+]],{{.*}} line: [[@LINE+2]] // CHECK-DAG: ![[ELSESCOPE]] = distinct !DILexicalBlock({{.*}} line: [[@LINE-2]], var local_var : String = "g" print("I have another string here \(local_var).\n", terminator: "") // Assign to all the captured variables to inhibit capture promotion. random_string = "c" random_int = -1 out_only = 333 return rhs < lhs } } var bool = backward_ptr("a" , "b") } main()
f1191957e4b5da469210bb15faded1e8
42.156863
134
0.51204
false
false
false
false
prine/ROGoogleTranslate
refs/heads/master
Source/ROGoogleTranslate.swift
mit
1
// // ROGoogleTranslate.swift // ROGoogleTranslate // // Created by Robin Oster on 20/10/16. // Copyright © 2016 prine.ch. All rights reserved. // import Foundation public struct ROGoogleTranslateParams { public init() { } public init(source:String, target:String, text:String) { self.source = source self.target = target self.text = text } public var source = "de" public var target = "en" public var text = "Ich glaube, du hast den Text zum Übersetzen vergessen" } /// Offers easier access to the Google Translate API open class ROGoogleTranslate { /// Store here the Google Translate API Key public var apiKey = "" /// /// Initial constructor /// public init() { } /// /// Translate a phrase from one language into another /// /// - parameter params: ROGoogleTranslate Struct contains all the needed parameters to translate with the Google Translate API /// - parameter callback: The translated string will be returned in the callback /// open func translate(params:ROGoogleTranslateParams, callback:@escaping (_ translatedText:String) -> ()) { guard apiKey != "" else { print("Warning: You should set the api key before calling the translate method.") return } if let urlEncodedText = params.text.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { if let url = URL(string: "https://translation.googleapis.com/language/translate/v2?key=\(self.apiKey)&q=\(urlEncodedText)&source=\(params.source)&target=\(params.target)&format=text") { let httprequest = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in guard error == nil else { print("Something went wrong: \(error?.localizedDescription)") return } if let httpResponse = response as? HTTPURLResponse { guard httpResponse.statusCode == 200 else { if let data = data { print("Response [\(httpResponse.statusCode)] - \(data)") } return } do { // Pyramid of optional json retrieving. I know with SwiftyJSON it would be easier, but I didn't want to add an external library if let data = data { if let json = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary { if let jsonData = json["data"] as? [String : Any] { if let translations = jsonData["translations"] as? [NSDictionary] { if let translation = translations.first as? [String : Any] { if let translatedText = translation["translatedText"] as? String { callback(translatedText) } } } } } } } catch { print("Serialization failed: \(error.localizedDescription)") } } }) httprequest.resume() } } } }
973a8d6efdd734a2840447e90f2a5c3d
38.25
197
0.477707
false
false
false
false
webim/webim-client-sdk-ios
refs/heads/master
Example/WebimClientLibrary/Models/UIAlertHandler.swift
mit
1
// // UIAlertHandler.swift // WebimClientLibrary_Tests // // Created by Nikita Lazarev-Zubov on 13.02.18. // Copyright © 2018 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import WebimClientLibrary final class UIAlertHandler { // MARK: - Properties private weak var delegate: UIViewController? private var alertController: UIAlertController! // MARK: - Initializer init(delegate: UIViewController) { self.delegate = delegate } // MARK: - Methods func showDialog( withMessage message: String, title: String?, buttonTitle: String = "OK".localized, buttonStyle: UIAlertAction.Style = .cancel, action: (() -> Void)? = nil ) { alertController = UIAlertController( title: title, message: message, preferredStyle: .alert ) let alertAction = UIAlertAction( title: buttonTitle, style: buttonStyle, handler: { _ in action?() }) alertController.addAction(alertAction) if buttonStyle != .cancel { let alertActionOther = UIAlertAction( title: "Cancel".localized, style: .cancel) alertController.addAction(alertActionOther) } delegate?.present(alertController, animated: true) } func showDepartmentListDialog( withDepartmentList departmentList: [Department], action: @escaping (String) -> Void, senderButton: UIView?, cancelAction: (() -> Void)? ) { alertController = UIAlertController( title: "Contact topic".localized, message: nil, preferredStyle: .actionSheet ) for department in departmentList { let departmentAction = UIAlertAction( title: department.getName(), style: .default, handler: { _ in action(department.getKey()) } ) alertController.addAction(departmentAction) } let alertAction = UIAlertAction( title: "Cancel".localized, style: .cancel, handler: { _ in cancelAction?() }) alertController.addAction(alertAction) if let popoverController = alertController.popoverPresentationController { if senderButton == nil { fatalError("No source view for presenting alert popover") } popoverController.sourceView = senderButton } delegate?.present(alertController, animated: true) } func showSendFailureDialog( withMessage message: String, title: String, action: (() -> Void)? = nil ) { showDialog( withMessage: message, title: title, buttonTitle: "OK".localized, action: action ) } func showChatClosedDialog() { showDialog( withMessage: "Chat finished.".localized, title: nil, buttonTitle: "OK".localized ) } func showCreatingSessionFailureDialog(withMessage message: String) { showDialog( withMessage: message, title: "Session creation failed".localized, buttonTitle: "OK".localized ) } func showFileLoadingFailureDialog(withError error: Error) { showDialog( withMessage: error.localizedDescription, title: "LoadError".localized, buttonTitle: "OK".localized ) } func showFileSavingFailureDialog(withError error: Error) { let action = getGoToSettingsAction() showDialog( withMessage: "SaveFileErrorMessage".localized, title: "Save error".localized, buttonTitle: "Go to Settings".localized, buttonStyle: .default, action: action ) } func showImageSavingFailureDialog(withError error: NSError) { let action = getGoToSettingsAction() showDialog( withMessage: "SaveErrorMessage".localized, title: "SaveError".localized, buttonTitle: "Go to Settings".localized, buttonStyle: .default, action: action ) } func showImageSavingSuccessDialog() { showDialog( withMessage: "The image has been saved to your photos".localized, title: "Saved!".localized, buttonTitle: "OK".localized ) } func showNoCurrentOperatorDialog() { showDialog( withMessage: "There is no current agent to rate".localized, title: "No agents available".localized, buttonTitle: "OK".localized ) } func showSettingsAlertDialog(withMessage message: String) { showDialog( withMessage: message, title: "InvalidSettings".localized, buttonTitle: "OK".localized ) } func showOperatorInfo(withMessage message: String) { showDialog( withMessage: message, title: "Operator Info".localized, buttonTitle: "OK".localized ) } func showAlertForAccountName() { showDialog( withMessage: "Alert account name".localized, title: "Account".localized, buttonTitle: "OK".localized ) } // MARK: - Private methods private func getGoToSettingsAction() -> (() -> Void) { return { guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (_) in }) } } } private func dismiss() { let time = DispatchTime.now() + 1 DispatchQueue.main.asyncAfter(deadline: time) { self.alertController.dismiss(animated: true, completion: nil) } } }
6f431f61fa1c9a632217025bcf681255
30.353191
91
0.584555
false
false
false
false
CodaFi/swift
refs/heads/main
test/SILGen/didset_oldvalue_not_accessed_silgen.swift
apache-2.0
12
// RUN: %target-swift-emit-silgen %s | %FileCheck %s // Make sure we do not call the getter to get the oldValue and pass it to didSet // when the didSet does not reference the oldValue in its body. class Foo<T> { var value: T { // CHECK-LABEL: sil private [ossa] @$s35didset_oldvalue_not_accessed_silgen3FooC5valuexvW : $@convention(method) <T> (@guaranteed Foo<T>) -> () // CHECK: debug_value %0 : $Foo<T>, let, name "self", argno {{[0-9]+}} // CHECK-NOT: debug_value_addr %0 : $*T, let, name "oldValue", argno {{[0-9]+}} didSet { print("didSet called!") } } init(value: T) { self.value = value } } let foo = Foo(value: "Hello") // Foo.value.setter // // CHECK-LABEL: sil hidden [ossa] @$s35didset_oldvalue_not_accessed_silgen3FooC5valuexvs : $@convention(method) <T> (@in T, @guaranteed Foo<T>) -> () // CHECK: debug_value_addr [[VALUE:%.*]] : $*T, let, name "value", argno {{[0-9+]}} // CHECK-NEXT: debug_value [[SELF:%.*]] : $Foo<T>, let, name "self", argno {{[0-9+]}} // CHECK-NEXT: [[ALLOC_STACK:%.*]] = alloc_stack $T // CHECK-NEXT: copy_addr [[VALUE]] to [initialization] [[ALLOC_STACK]] : $*T // CHECK-NEXT: [[REF_ADDR:%.*]] = ref_element_addr [[SELF]] : $Foo<T>, #Foo.value // CHECK-NEXT: [[BEGIN_ACCESS:%.*]] = begin_access [modify] [dynamic] [[REF_ADDR]] : $*T // CHECK-NEXT: copy_addr [take] [[ALLOC_STACK]] to [[BEGIN_ACCESS]] : $*T // CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*T // CHECK-NEXT: dealloc_stack [[ALLOC_STACK]] : $*T // CHECK: [[DIDSET:%.*]] = function_ref @$s35didset_oldvalue_not_accessed_silgen3FooC5valuexvW : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> () // CHECK-NEXT: [[RESULT:%.*]] = apply [[DIDSET]]<T>([[SELF]]) : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> () // Foo.value.modify // // CHECK-LABEL: sil hidden [ossa] @$s35didset_oldvalue_not_accessed_silgen3FooC5valuexvM : $@yield_once @convention(method) <T> (@guaranteed Foo<T>) -> @yields @inout T // CHECK: debug_value [[SELF:%.*]] : $Foo<T>, let, name "self", argno {{[0-9+]}} // CHECK-NEXT: [[REF_ADDR:%.*]] = ref_element_addr [[SELF]] : $Foo<T>, #Foo.value // CHECK-NEXT: [[BEGIN_ACCESS:%.*]] = begin_access [modify] [dynamic] [[REF_ADDR]] : $*T // CHECK-NEXT: yield [[BEGIN_ACCESS]] : $*T, resume bb1, unwind bb2 // CHECK: bb1: // CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*T // CHECK-NEXT: // function_ref Foo.value.didset // CHECK-NEXT: [[DIDSET:%.*]] = function_ref @$s35didset_oldvalue_not_accessed_silgen3FooC5valuexvW : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> () // CHECK-NEXT: [[RESULT:%.*]] = apply [[DIDSET]]<T>([[SELF]]) : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> () // CHECK: bb2: // CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*T // CHECK-NEXT: unwind foo.value = "World"
7d40edb8ea2c4c25da7a82a53567596f
51.490566
168
0.615385
false
false
false
false
cameronklein/BigScreenGifs
refs/heads/master
BigScreenGifs/BigScreenGifs/GifCollectionViewCell.swift
mit
1
// // GifCollectionViewCell.swift // BigScreenGifs // // Created by Cameron Klein on 9/19/15. // Copyright © 2015 Cameron Klein. All rights reserved. // import UIKit import AVKit let cellPopAnimationDuration : NSTimeInterval = 0.2 let cellPopAnimationScale : CGFloat = 1.15 class GifCollectionViewCell: UICollectionViewCell { // MARK: - Constants let popTransform = CGAffineTransformMakeScale(cellPopAnimationScale, cellPopAnimationScale) let player = AVPlayer() let playerLayer = AVPlayerLayer() // MARK - Variables var playerItem : AVPlayerItem! var gif : Gif! { willSet { NSNotificationCenter.defaultCenter().removeObserver(self, name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem) } didSet { self.playerItem = AVPlayerItem(asset: gif.asset) self.player.replaceCurrentItemWithPlayerItem(self.playerItem) NSNotificationCenter.defaultCenter().addObserver(self, selector: "itemDidEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem) } } // MARK: - Initializers override init(frame: CGRect) { super.init(frame: frame) playerLayer.player = player playerLayer.videoGravity = AVLayerVideoGravityResizeAspect contentView.layer.addSublayer(playerLayer) self.layer.shadowColor = UIColor.blackColor().CGColor self.layer.shadowOffset = CGSizeMake(0, 0) self.layer.shadowRadius = 10 self.layer.shadowOpacity = 0.5 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Methods override func layoutSubviews() { super.layoutSubviews() playerLayer.frame = contentView.bounds } // MARK: - Animation Methods func pop() { self.transform = self.popTransform self.layer.shadowOpacity = 0.5 self.layer.shadowOffset = CGSizeMake(0, 10) } func unpop() { self.transform = CGAffineTransformIdentity self.layer.shadowOpacity = 0.0 self.layer.shadowOffset = CGSizeMake(0, 0) } // MARK: - Notification Handlers func itemDidEnd(sender: NSNotification) { playerItem.seekToTime(kCMTimeZero) player.play() } }
2cd7c45b504a515f07a3f2e40fbaaf03
27.139535
137
0.646694
false
false
false
false
LeoFangQ/CMSwiftUIKit
refs/heads/master
CMSwiftUIKit/Pods/EZSwiftExtensions/Sources/UIViewExtensions.swift
mit
1
// // UIViewExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit // MARK: Custom UIView Initilizers extension UIView { /// EZSwiftExtensions public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) { self.init(frame: CGRect(x: x, y: y, width: w, height: h)) } /// EZSwiftExtensions, puts padding around the view public convenience init(superView: UIView, padding: CGFloat) { self.init(frame: CGRect(x: superView.x + padding, y: superView.y + padding, width: superView.w - padding*2, height: superView.h - padding*2)) } /// EZSwiftExtensions - Copies size of superview public convenience init(superView: UIView) { self.init(frame: CGRect(origin: CGPoint.zero, size: superView.size)) } } // MARK: Frame Extensions extension UIView { /// EZSwiftExtensions, add multiple subviews public func addSubviews(_ views: [UIView]) { views.forEach { eachView in self.addSubview(eachView) } } //TODO: Add pics to readme /// EZSwiftExtensions, resizes this view so it fits the largest subview public func resizeToFitSubviews() { var width: CGFloat = 0 var height: CGFloat = 0 for someView in self.subviews { let aView = someView let newWidth = aView.x + aView.w let newHeight = aView.y + aView.h width = max(width, newWidth) height = max(height, newHeight) } frame = CGRect(x: x, y: y, width: width, height: height) } /// EZSwiftExtensions, resizes this view so it fits the largest subview public func resizeToFitSubviews(_ tagsToIgnore: [Int]) { var width: CGFloat = 0 var height: CGFloat = 0 for someView in self.subviews { let aView = someView if !tagsToIgnore.contains(someView.tag) { let newWidth = aView.x + aView.w let newHeight = aView.y + aView.h width = max(width, newWidth) height = max(height, newHeight) } } frame = CGRect(x: x, y: y, width: width, height: height) } /// EZSwiftExtensions public func resizeToFitWidth() { let currentHeight = self.h self.sizeToFit() self.h = currentHeight } /// EZSwiftExtensions public func resizeToFitHeight() { let currentWidth = self.w self.sizeToFit() self.w = currentWidth } /// EZSwiftExtensions public var x: CGFloat { get { return self.frame.origin.x } set(value) { self.frame = CGRect(x: value, y: self.y, width: self.w, height: self.h) } } /// EZSwiftExtensions public var y: CGFloat { get { return self.frame.origin.y } set(value) { self.frame = CGRect(x: self.x, y: value, width: self.w, height: self.h) } } /// EZSwiftExtensions public var w: CGFloat { get { return self.frame.size.width } set(value) { self.frame = CGRect(x: self.x, y: self.y, width: value, height: self.h) } } /// EZSwiftExtensions public var h: CGFloat { get { return self.frame.size.height } set(value) { self.frame = CGRect(x: self.x, y: self.y, width: self.w, height: value) } } /// EZSwiftExtensions public var left: CGFloat { get { return self.x } set(value) { self.x = value } } /// EZSwiftExtensions public var right: CGFloat { get { return self.x + self.w } set(value) { self.x = value - self.w } } /// EZSwiftExtensions public var top: CGFloat { get { return self.y } set(value) { self.y = value } } /// EZSwiftExtensions public var bottom: CGFloat { get { return self.y + self.h } set(value) { self.y = value - self.h } } /// EZSwiftExtensions public var origin: CGPoint { get { return self.frame.origin } set(value) { self.frame = CGRect(origin: value, size: self.frame.size) } } /// EZSwiftExtensions public var centerX: CGFloat { get { return self.center.x } set(value) { self.center.x = value } } /// EZSwiftExtensions public var centerY: CGFloat { get { return self.center.y } set(value) { self.center.y = value } } /// EZSwiftExtensions public var size: CGSize { get { return self.frame.size } set(value) { self.frame = CGRect(origin: self.frame.origin, size: value) } } /// EZSwiftExtensions public func leftOffset(_ offset: CGFloat) -> CGFloat { return self.left - offset } /// EZSwiftExtensions public func rightOffset(_ offset: CGFloat) -> CGFloat { return self.right + offset } /// EZSwiftExtensions public func topOffset(_ offset: CGFloat) -> CGFloat { return self.top - offset } /// EZSwiftExtensions public func bottomOffset(_ offset: CGFloat) -> CGFloat { return self.bottom + offset } //TODO: Add to readme /// EZSwiftExtensions public func alignRight(_ offset: CGFloat) -> CGFloat { return self.w - offset } /// EZSwiftExtensions public func reorderSubViews(_ reorder: Bool = false, tagsToIgnore: [Int] = []) -> CGFloat { var currentHeight: CGFloat = 0 for someView in subviews { if !tagsToIgnore.contains(someView.tag) && !(someView ).isHidden { if reorder { let aView = someView aView.frame = CGRect(x: aView.frame.origin.x, y: currentHeight, width: aView.frame.width, height: aView.frame.height) } currentHeight += someView.frame.height } } return currentHeight } public func removeSubviews() { for subview in subviews { subview.removeFromSuperview() } } /// EZSE: Centers view in superview horizontally public func centerXInSuperView() { guard let parentView = superview else { assertionFailure("EZSwiftExtensions Error: The view \(self) doesn't have a superview") return } self.x = parentView.w/2 - self.w/2 } /// EZSE: Centers view in superview vertically public func centerYInSuperView() { guard let parentView = superview else { assertionFailure("EZSwiftExtensions Error: The view \(self) doesn't have a superview") return } self.y = parentView.h/2 - self.h/2 } /// EZSE: Centers view in superview horizontally & vertically public func centerInSuperView() { self.centerXInSuperView() self.centerYInSuperView() } } // MARK: Transform Extensions extension UIView { /// EZSwiftExtensions public func setRotationX(_ x: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DRotate(transform, x.degreesToRadians(), 1.0, 0.0, 0.0) self.layer.transform = transform } /// EZSwiftExtensions public func setRotationY(_ y: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DRotate(transform, y.degreesToRadians(), 0.0, 1.0, 0.0) self.layer.transform = transform } /// EZSwiftExtensions public func setRotationZ(_ z: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DRotate(transform, z.degreesToRadians(), 0.0, 0.0, 1.0) self.layer.transform = transform } /// EZSwiftExtensions public func setRotation(x: CGFloat, y: CGFloat, z: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DRotate(transform, x.degreesToRadians(), 1.0, 0.0, 0.0) transform = CATransform3DRotate(transform, y.degreesToRadians(), 0.0, 1.0, 0.0) transform = CATransform3DRotate(transform, z.degreesToRadians(), 0.0, 0.0, 1.0) self.layer.transform = transform } /// EZSwiftExtensions public func setScale(x: CGFloat, y: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DScale(transform, x, y, 1) self.layer.transform = transform } } // MARK: Layer Extensions extension UIView { /// EZSwiftExtensions public func setCornerRadius(radius: CGFloat) { self.layer.cornerRadius = radius self.layer.masksToBounds = true } //TODO: add this to readme /// EZSwiftExtensions public func addShadow(offset: CGSize, radius: CGFloat, color: UIColor, opacity: Float, cornerRadius: CGFloat? = nil) { self.layer.shadowOffset = offset self.layer.shadowRadius = radius self.layer.shadowOpacity = opacity self.layer.shadowColor = color.cgColor if let r = cornerRadius { self.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: r).cgPath } } /// EZSwiftExtensions public func addBorder(width: CGFloat, color: UIColor) { layer.borderWidth = width layer.borderColor = color.cgColor layer.masksToBounds = true } /// EZSwiftExtensions public func addBorderTop(size: CGFloat, color: UIColor) { addBorderUtility(x: 0, y: 0, width: frame.width, height: size, color: color) } //TODO: add to readme /// EZSwiftExtensions public func addBorderTopWithPadding(size: CGFloat, color: UIColor, padding: CGFloat) { addBorderUtility(x: padding, y: 0, width: frame.width - padding*2, height: size, color: color) } /// EZSwiftExtensions public func addBorderBottom(size: CGFloat, color: UIColor) { addBorderUtility(x: 0, y: frame.height - size, width: frame.width, height: size, color: color) } /// EZSwiftExtensions public func addBorderLeft(size: CGFloat, color: UIColor) { addBorderUtility(x: 0, y: 0, width: size, height: frame.height, color: color) } /// EZSwiftExtensions public func addBorderRight(size: CGFloat, color: UIColor) { addBorderUtility(x: frame.width - size, y: 0, width: size, height: frame.height, color: color) } /// EZSwiftExtensions fileprivate func addBorderUtility(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) { let border = CALayer() border.backgroundColor = color.cgColor border.frame = CGRect(x: x, y: y, width: width, height: height) layer.addSublayer(border) } //TODO: add this to readme /// EZSwiftExtensions public func drawCircle(fillColor: UIColor, strokeColor: UIColor, strokeWidth: CGFloat) { let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.w, height: self.w), cornerRadius: self.w/2) let shapeLayer = CAShapeLayer() shapeLayer.path = path.cgPath shapeLayer.fillColor = fillColor.cgColor shapeLayer.strokeColor = strokeColor.cgColor shapeLayer.lineWidth = strokeWidth self.layer.addSublayer(shapeLayer) } //TODO: add this to readme /// EZSwiftExtensions public func drawStroke(width: CGFloat, color: UIColor) { let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.w, height: self.w), cornerRadius: self.w/2) let shapeLayer = CAShapeLayer () shapeLayer.path = path.cgPath shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = color.cgColor shapeLayer.lineWidth = width self.layer.addSublayer(shapeLayer) } } private let UIViewAnimationDuration: TimeInterval = 1 private let UIViewAnimationSpringDamping: CGFloat = 0.5 private let UIViewAnimationSpringVelocity: CGFloat = 0.5 //TODO: add this to readme // MARK: Animation Extensions extension UIView { /// EZSwiftExtensions public func spring(animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) { spring(duration: UIViewAnimationDuration, animations: animations, completion: completion) } /// EZSwiftExtensions public func spring(duration: TimeInterval, animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) { UIView.animate( withDuration: UIViewAnimationDuration, delay: 0, usingSpringWithDamping: UIViewAnimationSpringDamping, initialSpringVelocity: UIViewAnimationSpringVelocity, options: UIViewAnimationOptions.allowAnimatedContent, animations: animations, completion: completion ) } /// EZSwiftExtensions public func animate(duration: TimeInterval, animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) { UIView.animate(withDuration: duration, animations: animations, completion: completion) } /// EZSwiftExtensions public func animate(animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) { animate(duration: UIViewAnimationDuration, animations: animations, completion: completion) } /// EZSwiftExtensions public func pop() { setScale(x: 1.1, y: 1.1) spring(duration: 0.2, animations: { [unowned self] () -> Void in self.setScale(x: 1, y: 1) }) } /// EZSwiftExtensions public func popBig() { setScale(x: 1.25, y: 1.25) spring(duration: 0.2, animations: { [unowned self] () -> Void in self.setScale(x: 1, y: 1) }) } //EZSE: Reverse pop, good for button animations public func reversePop() { setScale(x: 0.9, y: 0.9) UIView.animate(withDuration: 0.05, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: { [weak self] Void in self?.setScale(x: 1, y: 1) }) { (bool) in } } } //TODO: add this to readme // MARK: Render Extensions extension UIView { /// EZSwiftExtensions public func toImage () -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0) drawHierarchy(in: bounds, afterScreenUpdates: false) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } } // MARK: Gesture Extensions extension UIView { /// http://stackoverflow.com/questions/4660371/how-to-add-a-touch-event-to-a-uiview/32182866#32182866 /// EZSwiftExtensions public func addTapGesture(tapNumber: Int = 1, target: AnyObject, action: Selector) { let tap = UITapGestureRecognizer(target: target, action: action) tap.numberOfTapsRequired = tapNumber addGestureRecognizer(tap) isUserInteractionEnabled = true } /// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak public func addTapGesture(tapNumber: Int = 1, action: ((UITapGestureRecognizer) -> ())?) { let tap = BlockTap(tapCount: tapNumber, fingerCount: 1, action: action) addGestureRecognizer(tap) isUserInteractionEnabled = true } /// EZSwiftExtensions public func addSwipeGesture(direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, target: AnyObject, action: Selector) { let swipe = UISwipeGestureRecognizer(target: target, action: action) swipe.direction = direction #if os(iOS) swipe.numberOfTouchesRequired = numberOfTouches #endif addGestureRecognizer(swipe) isUserInteractionEnabled = true } /// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak public func addSwipeGesture(direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, action: ((UISwipeGestureRecognizer) -> ())?) { let swipe = BlockSwipe(direction: direction, fingerCount: numberOfTouches, action: action) addGestureRecognizer(swipe) isUserInteractionEnabled = true } /// EZSwiftExtensions public func addPanGesture(target: AnyObject, action: Selector) { let pan = UIPanGestureRecognizer(target: target, action: action) addGestureRecognizer(pan) isUserInteractionEnabled = true } /// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak public func addPanGesture(action: ((UIPanGestureRecognizer) -> ())?) { let pan = BlockPan(action: action) addGestureRecognizer(pan) isUserInteractionEnabled = true } #if os(iOS) /// EZSwiftExtensions public func addPinchGesture(target: AnyObject, action: Selector) { let pinch = UIPinchGestureRecognizer(target: target, action: action) addGestureRecognizer(pinch) isUserInteractionEnabled = true } #endif #if os(iOS) /// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak public func addPinchGesture(action: ((UIPinchGestureRecognizer) -> ())?) { let pinch = BlockPinch(action: action) addGestureRecognizer(pinch) isUserInteractionEnabled = true } #endif /// EZSwiftExtensions public func addLongPressGesture(target: AnyObject, action: Selector) { let longPress = UILongPressGestureRecognizer(target: target, action: action) addGestureRecognizer(longPress) isUserInteractionEnabled = true } /// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak public func addLongPressGesture(action: ((UILongPressGestureRecognizer) -> ())?) { let longPress = BlockLongPress(action: action) addGestureRecognizer(longPress) isUserInteractionEnabled = true } } //TODO: add to readme extension UIView { /// EZSwiftExtensions [UIRectCorner.TopLeft, UIRectCorner.TopRight] public func roundCorners(_ corners: UIRectCorner, radius: CGFloat) { let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath self.layer.mask = mask } /// EZSwiftExtensions public func roundView() { self.layer.cornerRadius = min(self.frame.size.height, self.frame.size.width) / 2 } } extension UIView { ///EZSE: Shakes the view for as many number of times as given in the argument. public func shakeViewForTimes(_ times: Int) { let anim = CAKeyframeAnimation(keyPath: "transform") anim.values = [ NSValue(caTransform3D: CATransform3DMakeTranslation(-5, 0, 0 )), NSValue(caTransform3D: CATransform3DMakeTranslation( 5, 0, 0 )) ] anim.autoreverses = true anim.repeatCount = Float(times) anim.duration = 7/100 self.layer.add(anim, forKey: nil) } } extension UIView { ///EZSE: Loops until it finds the top root view. //TODO: Add to readme func rootView() -> UIView { guard let parentView = superview else { return self } return parentView.rootView() } } //MARK: Fade Extensions private let UIViewDefaultFadeDuration: TimeInterval = 0.4 extension UIView { ///EZSE: Fade in with duration, delay and completion block. public func fadeIn(_ duration: TimeInterval? = UIViewDefaultFadeDuration, delay _delay: TimeInterval? = 0.0, completion: ((Bool) -> Void)? = nil) { UIView.animate(withDuration: duration ?? UIViewDefaultFadeDuration, delay: _delay ?? 0.0, options: UIViewAnimationOptions(rawValue: UInt(0)), animations: { self.alpha = 1.0 }, completion:completion) } /// EZSwiftExtensions public func fadeOut(_ duration: TimeInterval? = UIViewDefaultFadeDuration, delay _delay: TimeInterval? = 0.0, completion: ((Bool) -> Void)? = nil) { UIView.animate(withDuration: duration ?? UIViewDefaultFadeDuration, delay: _delay ?? 0.0, options: UIViewAnimationOptions(rawValue: UInt(0)), animations: { self.alpha = 0.0 }, completion:completion) } /// Fade to specific value with duration, delay and completion block. public func fadeTo(_ value: CGFloat, duration _duration: TimeInterval? = UIViewDefaultFadeDuration, delay _delay: TimeInterval? = 0.0, completion: ((Bool) -> Void)? = nil) { UIView.animate(withDuration: _duration ?? UIViewDefaultFadeDuration, delay: _delay ?? UIViewDefaultFadeDuration, options: UIViewAnimationOptions(rawValue: UInt(0)), animations: { self.alpha = value }, completion:completion) } }
541f58fe726c2384d154d8da7a575005
33.432
186
0.631041
false
false
false
false
xdliu002/TongjiAppleClubDeviceManagement
refs/heads/master
TAC-DM/BorrowRecord.swift
mit
1
// // BorrowRecord.swift // TAC-DM // // Created by Shepard Wang on 15/8/27. // Copyright (c) 2015 TAC. All rights reserved. // import UIKit import Foundation class BorrowRecord: NSObject { var recordId: Int = 0 var borrowerName: String = "" var tele: String = "" var itemId: Int = 0 var itemName: String = "" var itemDescription: String = "" var borrowDate: NSDate var returnDate: NSDate var number: Int = 0 override init(){ borrowDate = NSDate() returnDate = NSDate() } }
150f7369c44b456d47462f71cf39f597
18.642857
48
0.605455
false
false
false
false
fgengine/quickly
refs/heads/master
Quickly/Extensions/Date.swift
mit
1
// // Quickly // public extension Date { func isEqual(calendar: Calendar, date: Date, component: Calendar.Component) -> Bool { return calendar.isDate(self, equalTo: date, toGranularity: component) } func format(_ format: String, calendar: Calendar = Calendar.current, locale: Locale = Locale.current) -> String { let formatter = DateFormatter() formatter.calendar = calendar formatter.locale = locale formatter.dateFormat = format return formatter.string(from: self) } }
0d77c9ccbe4385de55ebcb1b57675229
27.842105
117
0.65146
false
false
false
false
rob-brown/SwiftRedux
refs/heads/master
Source/DiffNotifier.swift
mit
1
// // DiffNotifier.swift // SwiftRedux // // Created by Robert Brown on 11/6/15. // Copyright © 2015 Robert Brown. All rights reserved. // import Foundation public class DiffNotifier<T: Equatable> { public typealias Listener = (T)->() public typealias Unsubscriber = ()->() public var currentState: T { didSet { if currentState != oldValue { listeners.forEach { $0.1(currentState) } } } } private var listeners = [String:Listener]() public init(_ initialState: T) { currentState = initialState } public func subscribe(listener: Listener) -> Unsubscriber { let key = NSUUID().UUIDString listeners[key] = listener listener(currentState) return { self.listeners.removeValueForKey(key) } } } public class DiffListNotifier<T: Equatable> { public typealias Listener = ([T])->() public typealias Unsubscriber = ()->() public var currentState: [T] { didSet { if currentState != oldValue { listeners.forEach { $0.1(currentState) } } } } private var listeners = [String:Listener]() public init(_ initialState: [T]) { currentState = initialState } public func subscribe(listener: Listener) -> Unsubscriber { let key = NSUUID().UUIDString listeners[key] = listener listener(currentState) return { self.listeners.removeValueForKey(key) } } }
da50c2b40fc04da959a079ea60590f7c
24.047619
63
0.569708
false
false
false
false
silence0201/Swift-Study
refs/heads/master
Learn/05.控制语句/switch中使用where语句.playground/section-1.swift
mit
1
var student = (id:"1002", name:"李四", age:32, ChineseScore:90, EnglishScore:91) var desc: String switch student { case (_, _, let age, 90...100, 90...100) where age > 20: desc = "优" case (_, _, _, 80..<90, 80..<90): desc = "良" case (_, _, _, 60..<80, 60..<80): desc = "中" case (_, _, _, 60..<80, 90...100), (_, _, _, 90...100, 60..<80): desc = "偏科" case (_, _, _, 0..<80, 90...100), (_, _, _, 90...100, 0..<80): desc = "严重偏科" default: desc = "无" } print("说明:\(desc)")
046b5af598d00308785be14587431c80
20.608696
78
0.460765
false
false
false
false
epv44/TwitchAPIWrapper
refs/heads/master
Example/Tests/Request Tests/AllStreamTagRequestTests.swift
mit
1
// // AllStreamTagRequestTests.swift // TwitchAPIWrapper_Tests // // Created by Eric Vennaro on 6/9/21. // Copyright © 2021 CocoaPods. All rights reserved. // import XCTest @testable import TwitchAPIWrapper class AllStreamTagRequestTests: XCTestCase { override func setUpWithError() throws { TwitchAuthorizationManager.sharedInstance.clientID = "1" TwitchAuthorizationManager.sharedInstance.credentials = Credentials(accessToken: "XXX", scopes: ["user", "read"]) super.setUp() } func testBuildRequest_withRequiredParams_shouldSucceed() throws { let request = AllStreamTagRequest() XCTAssertEqual( request.url!.absoluteString, expectedURL: "https://api.twitch.tv/helix/tags/streams") XCTAssertEqual(request.data, Data()) XCTAssertEqual(request.headers, ["Client-Id": "1", "Authorization": "Bearer XXX"]) } func testBuildRequest_withOptionalParams_shouldSucceed() throws { let request = AllStreamTagRequest(after: "1", first: "2", tagIDs: ["3"]) XCTAssertEqual( request.url!.absoluteString, expectedURL: "https://api.twitch.tv/helix/tags/streams?after=1&first=2&tag_id=3") XCTAssertEqual(request.data, Data()) XCTAssertEqual(request.headers, ["Client-Id": "1", "Authorization": "Bearer XXX"]) } }
2b75f99fbf58b2b5a0fc44f4209a37bc
35.972973
121
0.675439
false
true
false
false
NordicSemiconductor/IOS-Pods-DFU-Library
refs/heads/master
iOSDFULibrary/Classes/Utilities/crc32.swift
bsd-3-clause
1
/* Copyright (C) 1995-1998 Mark Adler Copyright (C) 2015 C.W. "Madd the Sane" Betts This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler jloup@gzip.org madler@alumni.caltech.edu */ import Foundation /** Table of CRC-32's of all single-byte values (made by make_crc_table) */ private let crcTable: [UInt32] = [ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d] /// Calculates CRC32 value from the given Data. /// /// - parameter data: Data to calculate CRC from. /// - returns: The CRC32 calculated over the whole Data object. func crc32(data: Data?) -> UInt32 { return crc32(0, data: data) } /// Updates the running crc with the bytes from given Data. /// /// - parameter crc: The crc to be updated. /// - parameter data: Data to calculate CRC from. /// - returns: The CRC32 updated using whole Data object. func crc32(_ crc: UInt32, data: Data?) -> UInt32 { guard let data = data else { return crc32(0, buffer: nil, length: 0) } return crc32(crc, buffer: (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), length: data.count) } /** Update a running crc with the bytes buf[0..len-1] and return the updated crc. If buf is `nil`, this function returns the required initial value for the crc. Pre- and post-conditioning (one's complement) is performed within this function so it shouldn't be done by the application. Usage example: var crc: UInt32 = crc32(0, nil, 0); while (read_buffer(buffer, length) != EOF) { crc = crc32(crc, buffer: buffer, length: length) } if (crc != original_crc) error(); */ func crc32(_ crc: UInt32, buffer: UnsafePointer<UInt8>?, length: Int) -> UInt32 { if buffer == nil { return 0 } var crc1 = crc ^ 0xffffffff var len = length var buf = buffer func DO1() { let toBuf = buf?.pointee buf = buf! + 1 crc1 = crcTable[Int((crc1 ^ UInt32(toBuf!)) & 0xFF)] ^ crc1 >> 8 } func DO2() { DO1(); DO1(); } func DO4() { DO2(); DO2(); } func DO8() { DO4(); DO4(); } while len >= 8 { DO8() len -= 8 } if len != 0 { repeat { len -= 1 DO1() } while len != 0 } return crc1 ^ 0xffffffff; } /* func ==(lhs: CRC32Calculator, rhs: CRC32Calculator) -> Bool { return lhs.initialized == rhs.initialized && lhs.crc == rhs.crc } final class CRC32Calculator: Hashable { fileprivate var initialized = false fileprivate(set) var crc: UInt32 = 0 init() {} convenience init(data: Data) { self.init() crc = crc32(crc, data: data) initialized = true } func run(buffer: UnsafePointer<UInt8>, length: Int) { crc = crc32(crc, buffer: buffer, length: length) initialized = true } func run(data: Data) { crc = crc32(crc, data: data) initialized = true } func hash(into hasher: inout Hasher) { hasher.combine(crc) } }*/
5907e1a604a0527e8eb6888da6e32da2
38.2
122
0.70394
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/Interpreter/SDK/libc.swift
apache-2.0
9
/* magic */ // Do not edit the line above. // RUN: %empty-directory(%t) // RUN: %target-run-simple-swift %s %t | %FileCheck %s // REQUIRES: executable_test // TODO: rdar://problem/33388782 // REQUIRES: CPU=x86_64 #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) import Glibc #endif let sourcePath = CommandLine.arguments[1] let tempPath = CommandLine.arguments[2] + "/libc.txt" // CHECK: Hello world fputs("Hello world", stdout) // CHECK: 4294967295 print("\(UINT32_MAX)") // CHECK: the magic word is ///* magic */// let sourceFile = open(sourcePath, O_RDONLY) assert(sourceFile >= 0) var bytes = UnsafeMutablePointer<CChar>.allocate(capacity: 12) var readed = read(sourceFile, bytes, 11) close(sourceFile) assert(readed == 11) bytes[11] = CChar(0) print("the magic word is //\(String(cString: bytes))//") // CHECK: O_CREAT|O_EXCL returned errno *17* let errFile = open(sourcePath, O_RDONLY | O_CREAT | O_EXCL) if errFile != -1 { print("O_CREAT|O_EXCL failed to return an error") } else { let e = errno print("O_CREAT|O_EXCL returned errno *\(e)*") } // CHECK-NOT: error // CHECK: created mode *33216* *33216* let tempFile = open(tempPath, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IXUSR) if tempFile == -1 { let e = errno print("error: open(tempPath \(tempPath)) returned -1, errno \(e)") abort() } let written = write(tempFile, bytes, 11) if (written != 11) { print("error: write(tempFile) returned \(written), errno \(errno)") abort() } var err: Int32 var statbuf1 = stat() err = fstat(tempFile, &statbuf1) if err != 0 { let e = errno print("error: fstat returned \(err), errno \(e)") abort() } close(tempFile) var statbuf2 = stat() err = stat(tempPath, &statbuf2) if err != 0 { let e = errno print("error: stat returned \(err), errno \(e)") abort() } print("created mode *\(statbuf1.st_mode)* *\(statbuf2.st_mode)*") assert(statbuf1.st_mode == S_IFREG | S_IRUSR | S_IWUSR | S_IXUSR) assert(statbuf1.st_mode == statbuf2.st_mode)
e838b35862ef1f6149b4d002a566fa17
23.352941
72
0.653623
false
false
false
false
Pluto-Y/SwiftyEcharts
refs/heads/master
SwiftyEcharts/Models/Type/Position.swift
mit
1
// // Position.swift // SwiftyEcharts // // Created by Pluto-Y on 15/02/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // /// 位置 public enum Position: FunctionOrOthers { case auto, left, center, right, top, middle, bottom, start, end, inside, inner, outside, insideLeft, insideTop, insideRight, insideBottom, insideTopLeft, insideBottomLeft, insideTopRight, insideBottomRight case value(LengthValue) case point(Point) case function(Function) public var jsonString: String { switch self { case .auto: return "auto".jsonString case .left: return "left".jsonString case .right: return "right".jsonString case .center: return "center".jsonString case .top: return "top".jsonString case .bottom: return "bottom".jsonString case .middle: return "middle".jsonString case .start: return "start".jsonString case .end: return "end".jsonString case .inside: return "inside".jsonString case .inner: return "inner".jsonString case .outside: return "outside".jsonString case .insideLeft: return "insideLeft".jsonString case .insideRight: return "insideRight".jsonString case .insideTop: return "insideTop".jsonString case .insideBottom: return "insideBottom".jsonString case .insideTopLeft: return "insideTopLeft".jsonString case .insideBottomLeft: return "insideBottomLeft".jsonString case .insideTopRight: return "insideTopRight".jsonString case .insideBottomRight: return "insideBottomRight".jsonString case let .point(point): return point.jsonString case let .value(val): return val.jsonString case let .function(f): return f.jsonString } } } extension Position: ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral { public init(floatLiteral value: Float) { self = .value(value) } public init(integerLiteral value: Int) { self = .value(value) } } public enum Location: String, Jsonable { case start = "start" case middle = "middle" case end = "end" public var jsonString: String { return self.rawValue.jsonString } }
ea2ce75e48d1e9e2fd777118f7aabe6a
28.081395
209
0.598161
false
false
false
false
mbigatti/ImagesGenerator
refs/heads/master
ImagesGenerator/ViewController.swift
mit
1
// // ViewController.swift // ImagesGenerator // // Created by Massimiliano Bigatti on 19/06/15. // Copyright © 2015 Massimiliano Bigatti. All rights reserved. // import UIKit import CoreGraphics class ViewController: UIViewController { @IBOutlet weak var circleView: UIView! @IBOutlet weak var color1TextField: UITextField! @IBOutlet weak var lineWidthTextField: UITextField! @IBOutlet weak var color2TextField: UITextField! @IBOutlet weak var sizeSlider: UISlider! let gradientLayer = CAGradientLayer() let shapeLayer = CAShapeLayer() let backgroundShapeLayer = CAShapeLayer() override func viewDidLoad() { super.viewDidLoad() // // // gradientLayer.frame = CGRect(x: 0, y: 0, width: circleView.layer.frame.width, height: circleView.layer.frame.height) gradientLayer.startPoint = CGPoint(x: 0, y: 0) gradientLayer.endPoint = CGPoint(x: 0, y: 1) gradientLayer.mask = shapeLayer circleView.layer.addSublayer(backgroundShapeLayer) circleView.layer.addSublayer(gradientLayer) updateImage() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sizeSliderValueChanged(sender: UISlider) { updateImage() } @IBAction func dataChanged(sender: UITextField) { updateImage() } @IBAction func export(sender: UIButton) { let oldSize = sizeSlider.value for index in 1...60 { sizeSlider.setValue(Float(index), animated: false) updateImage() let filename = "progress-\(index)@2x.png" saveImage(filename) } sizeSlider.value = oldSize updateImage() } private func updateImage() { updateGradient() updateBackgroundShape() updateArcShape() } private func updateGradient() { // // gradient // let color1 = UIColor.colorWithRGBString(color1TextField.text!) let color2 = UIColor.colorWithRGBString(color2TextField.text!) var colors = [AnyObject]() colors.append(color1.CGColor) colors.append(color2.CGColor) gradientLayer.colors = colors } private func updateBackgroundShape() { let center = CGPoint(x: circleView.frame.size.width / 2, y: circleView.frame.size.height / 2) let bezierPath = UIBezierPath(arcCenter: center, radius: (circleView.frame.size.width - CGFloat(strtoul(lineWidthTextField.text!, nil, 10))) / 2, startAngle: CGFloat(-M_PI_2), endAngle: CGFloat(3 * M_PI_2), clockwise: true) let path = CGPathCreateCopyByStrokingPath(bezierPath.CGPath, nil, CGFloat(strtoul(lineWidthTextField.text!, nil, 10)), bezierPath.lineCapStyle, bezierPath.lineJoinStyle, bezierPath.miterLimit) backgroundShapeLayer.path = path backgroundShapeLayer.fillColor = UIColor(white: 1.0, alpha: 0.2).CGColor } private func updateArcShape() { let center = CGPoint(x: circleView.frame.size.width / 2, y: circleView.frame.size.height / 2) let endAngle = (Double(sizeSlider.value) * 4 * M_PI_2) / 60 - M_PI_2 let bezierPath = UIBezierPath(arcCenter: center, radius: (circleView.frame.size.width - CGFloat(strtoul(lineWidthTextField.text!, nil, 10))) / 2, startAngle: CGFloat(-M_PI_2), endAngle: CGFloat(endAngle), clockwise: true) bezierPath.lineCapStyle = .Round let path = CGPathCreateCopyByStrokingPath(bezierPath.CGPath, nil, CGFloat(strtoul(lineWidthTextField.text!, nil, 10)), bezierPath.lineCapStyle, bezierPath.lineJoinStyle, bezierPath.miterLimit) shapeLayer.path = path } func saveImage(filename: String) { let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL let localUrl = NSURL(string: filename, relativeToURL: documentsUrl)! print("\(localUrl)") let color = circleView.backgroundColor; circleView.backgroundColor = UIColor.clearColor() UIGraphicsBeginImageContext(circleView.frame.size); circleView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); let imageData = UIImagePNGRepresentation(image); imageData?.writeToURL(localUrl, atomically: true) circleView.backgroundColor = color; } } extension UIColor { class func colorWithRGBString(hexString: String) -> UIColor { let redString = hexString.substringWithRange(Range(start: hexString.startIndex, end: hexString.startIndex.advancedBy(2))) let greenString = hexString.substringWithRange(Range(start: hexString.startIndex.advancedBy(2), end: hexString.startIndex.advancedBy(4))) let blueString = hexString.substringWithRange(Range(start: hexString.startIndex.advancedBy(4), end: hexString.startIndex.advancedBy(6))) let red = CGFloat(strtoul(redString, nil, 16)) / 255 let green = CGFloat(strtoul(greenString, nil, 16)) / 255 let blue = CGFloat(strtoul(blueString, nil, 16)) / 255 return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } }
8010f9f06e75a0550c0a862029b3fdd9
35.320513
200
0.643134
false
false
false
false
whiteshadow-gr/HatForIOS
refs/heads/master
HAT/Objects/Notes/HATNotesAuthor.swift
mpl-2.0
1
/** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * 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 SwiftyJSON // MARK: Struct public struct HATNotesAuthor: HATObject, HatApiType { // MARK: - JSON Fields /** The JSON fields used by the hat The Fields are the following: * `nickname` in JSON is `nick` * `name` in JSON is `name` * `photoURL` in JSON is `photo_url` * `phata` in JSON is `phata` * `authorID` in JSON is `authorID` */ private enum CodingKeys: String, CodingKey { case nickname = "nick" case name = "name" case photoURL = "photo_url" case phata = "phata" case authorID = "id" } // MARK: - Variables /// the nickname of the author. Optional public var nickname: String? /// the name of the author. Optional public var name: String? /// the photo url of the author. Optional public var photoURL: String? /// the phata of the author. Required public var phata: String = "" /// the id of the author. Optional public var authorID: Int? // MARK: - Initialiser /** The default initialiser. Initialises everything to default values. */ public init() { } /** It initialises everything from the received JSON file from the HAT - dict: The JSON file received from the HAT */ public init(dict: Dictionary<String, JSON>) { self.init() self.inititialize(dict: dict) } /** It initialises everything from the received JSON file from the HAT - dict: The JSON file received from the HAT */ public mutating func inititialize(dict: Dictionary<String, JSON>) { // this field will always have a value no need to use if let if let tempPHATA: String = dict[CodingKeys.phata.rawValue]?.string { phata = tempPHATA } // check optional fields for value, if found assign it to the correct variable if let tempID: String = dict[CodingKeys.authorID.rawValue]?.stringValue, !tempID.isEmpty { if let intTempID: Int = Int(tempID) { authorID = intTempID } } if let tempNickName: String = dict[CodingKeys.nickname.rawValue]?.string { nickname = tempNickName } if let tempName: String = dict[CodingKeys.name.rawValue]?.string { name = tempName } if let tempPhotoURL: String = dict[CodingKeys.photoURL.rawValue]?.string { photoURL = tempPhotoURL } } /** It initialises everything from the received Dictionary file from the cache - fromCache: The dictionary file received from the cache */ public mutating func initialize(fromCache: Dictionary<String, Any>) { let dictionary: JSON = JSON(fromCache) self.inititialize(dict: dictionary.dictionaryValue) } // MARK: - JSON Mapper /** Returns the object as Dictionary, JSON - returns: Dictionary<String, String> */ public func toJSON() -> Dictionary<String, Any> { return [ CodingKeys.phata.rawValue: self.phata, CodingKeys.authorID.rawValue: self.authorID ?? "", CodingKeys.nickname.rawValue: self.nickname ?? "", CodingKeys.name.rawValue: self.name ?? "", CodingKeys.photoURL.rawValue: self.photoURL ?? "" ] } }
e49f869196d62a79dfa339320b89cc05
26.802817
98
0.574975
false
false
false
false
PurpleSweetPotatoes/SwiftKit
refs/heads/master
SwiftKit/control/BQRefresh/BQRefreshView.swift
apache-2.0
1
// // BQRefreshView.swift // BQRefresh // // Created by baiqiang on 2017/7/5. // Copyright © 2017年 baiqiang. All rights reserved. // import UIKit enum RefreshStatus: Int { case idle //闲置 case pull //拖拽 case refreshing //刷新 case willRefresh //即将刷新 case noMoreData //无更多数据 } enum ObserverName: String { case scrollerOffset = "contentOffset" case scrollerSize = "contentSize" } typealias CallBlock = ()->() class BQRefreshView: UIView { //MARK: - ***** Ivars ***** var origiOffsetY: CGFloat = 0 public var scrollViewOriginalInset: UIEdgeInsets = .zero public var status: RefreshStatus = .idle public weak var scrollView: UIScrollView! public var refreshBlock: CallBlock! //MARK: - ***** public Method ***** public class func refreshLab() -> UILabel { let lab = UILabel() lab.font = UIFont.systemFont(ofSize: 14) lab.textAlignment = .center return lab } override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) if !(newSuperview is UIScrollView) { return } self.removeObservers() self.sizeW = newSuperview?.sizeW ?? 0 self.left = 0 self.scrollView = newSuperview as! UIScrollView self.scrollViewOriginalInset = self.scrollView.contentInset self.addObservers() //初始化状态(防止第一次无数据tableView下拉时出现异常) self.scrollView.contentOffset = CGPoint.zero } override func removeFromSuperview() { self.removeObservers() super.removeFromSuperview() } //MARK: - ***** private Method ***** private func addObservers() { let options: NSKeyValueObservingOptions = [.new, .old] self.scrollView.addObserver(self, forKeyPath: ObserverName.scrollerOffset.rawValue, options: options, context: nil) self.scrollView.addObserver(self, forKeyPath: ObserverName.scrollerSize.rawValue, options: options, context: nil) } private func removeObservers() { self.superview?.removeObserver(self, forKeyPath: ObserverName.scrollerOffset.rawValue) self.superview?.removeObserver(self, forKeyPath: ObserverName.scrollerSize.rawValue) } //MARK: - ***** respond event Method ***** override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if !self.isUserInteractionEnabled { return } if self.isHidden { return } if let key = keyPath { let value = ObserverName(rawValue: key)! switch value { case .scrollerOffset: self.contentOffsetDidChange(change: change) case .scrollerSize: self.contentSizeDidChange(change: change) } } } func contentOffsetDidChange(change: [NSKeyValueChangeKey : Any]?) { if self.status == .idle && !self.scrollView.isDragging { origiOffsetY = self.scrollView.contentOffset.y self.status = .pull } } func contentSizeDidChange(change: [NSKeyValueChangeKey : Any]?) { } }
0599c50cc84581972244e04d6fae2a46
30.407767
151
0.633385
false
false
false
false
dclelland/AudioKit
refs/heads/master
AudioKit/Common/Instruments/AKWavetableSynth.swift
mit
1
// // AKWavetableSynth.swift // AudioKit // // Created by Jeff Cooper, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation import AVFoundation /// A wrapper for AKOscillator to make it playable as a polyphonic instrument. public class AKWavetableSynth: AKPolyphonicInstrument { /// Attack time public var attackDuration: Double = 0.1 { didSet { for voice in voices { let oscillatorVoice = voice as! AKOscillatorVoice oscillatorVoice.adsr.attackDuration = attackDuration } } } /// Decay time public var decayDuration: Double = 0.1 { didSet { for voice in voices { let oscillatorVoice = voice as! AKOscillatorVoice oscillatorVoice.adsr.decayDuration = decayDuration } } } /// Sustain Level public var sustainLevel: Double = 0.66 { didSet { for voice in voices { let oscillatorVoice = voice as! AKOscillatorVoice oscillatorVoice.adsr.sustainLevel = sustainLevel } } } /// Release time public var releaseDuration: Double = 0.5 { didSet { for voice in voices { let oscillatorVoice = voice as! AKOscillatorVoice oscillatorVoice.adsr.releaseDuration = releaseDuration } } } /// Instantiate the Oscillator Instrument /// /// - parameter waveform: Shape of the waveform to oscillate /// - parameter voiceCount: Maximum number of voices that will be required /// public init(waveform: AKTable, voiceCount: Int) { super.init(voice: AKOscillatorVoice(waveform: waveform), voiceCount: voiceCount) } /// Start playback of a particular voice with MIDI style note and velocity /// /// - parameter voice: Voice to start /// - parameter note: MIDI Note Number /// - parameter velocity: MIDI Velocity (0-127) /// override internal func playVoice(voice: AKVoice, note: Int, velocity: Int) { let frequency = note.midiNoteToFrequency() let amplitude = Double(velocity) / 127.0 * 0.3 let oscillatorVoice = voice as! AKOscillatorVoice oscillatorVoice.oscillator.frequency = frequency oscillatorVoice.oscillator.amplitude = amplitude oscillatorVoice.start() } /// Stop playback of a particular voice /// /// - parameter voice: Voice to stop /// - parameter note: MIDI Note Number /// override internal func stopVoice(voice: AKVoice, note: Int) { let oscillatorVoice = voice as! AKOscillatorVoice oscillatorVoice.stop() } } internal class AKOscillatorVoice: AKVoice { var oscillator: AKOscillator var adsr: AKAmplitudeEnvelope var waveform: AKTable init(waveform: AKTable) { oscillator = AKOscillator(waveform: waveform) adsr = AKAmplitudeEnvelope(oscillator, attackDuration: 0.2, decayDuration: 0.2, sustainLevel: 0.8, releaseDuration: 1.0) self.waveform = waveform super.init() avAudioNode = adsr.avAudioNode } /// Function create an identical new node for use in creating polyphonic instruments override func duplicate() -> AKVoice { let copy = AKOscillatorVoice(waveform: self.waveform) return copy } /// Tells whether the node is processing (ie. started, playing, or active) override var isStarted: Bool { return oscillator.isPlaying } /// Function to start, play, or activate the node, all do the same thing override func start() { oscillator.start() adsr.start() } /// Function to stop or bypass the node, both are equivalent override func stop() { adsr.stop() } }
ef4049541f2b89f778dc46f551d19eb5
30.015625
88
0.615617
false
false
false
false
schrismartin/dont-shoot-the-messenger
refs/heads/master
Sources/Library/Models/FBIncomingMessage.swift
mit
1
// // FBMessageInformation.swift // the-narrator // // Created by Chris Martin on 11/14/16. // // import Foundation import Vapor import HTTP public struct FBIncomingMessage { public var senderId: SCMIdentifier public var recipientId: SCMIdentifier public var date: Date public var text: String? public var postback: String? /// Constructs an expected Facebook Messenger event from the received JSON data /// - Parameter json: The JSON payload representation of an event /// Fails if public init?(json: JSON) { // Extract Components guard let senderId = json[ "sender" ]?[ "id" ]?.string, let recipientId = json[ "recipient" ]?[ "id" ]?.string, let timestamp = json[ "timestamp" ]?.int else { console.log("Facebook Message must contain senderId, recipientId, and timestamp") return nil } // Make assignments self.senderId = SCMIdentifier(string: senderId) self.recipientId = SCMIdentifier(string: recipientId) self.date = Date(timeIntervalSince1970: TimeInterval(timestamp)) text = json[ "message" ]?[ "text" ]?.string postback = json[ "postback" ]?[ "payload" ]?.string } } extension FBIncomingMessage: CustomStringConvertible { public var description: String { return "Sender: \(senderId.string), Recipient: \(recipientId.string), Message: \(text), date: \(date)" } }
15b05f476d106e7617b3b2e334fa35eb
30.638298
110
0.634163
false
false
false
false
ProsoftEngineering/TimeMachineRemoteStatus
refs/heads/master
TimeMachineRemoteStatus/AppDelegate.swift
bsd-3-clause
1
// Copyright © 2016-2017, Prosoft Engineering, Inc. (A.K.A "Prosoft") // 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 Prosoft 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 PROSOFT ENGINEERING, INC. 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 Cocoa class AppDelegate: NSObject, NSApplicationDelegate { var statusItem: NSStatusItem? var statusImage: NSImage! let fmt = DateFormatter() let backupsManager = BackupsManager() var prefsController: PreferencesController! var scheduleTimer: Timer! var nextScheduledUpdate: Date! var lastUpdatedItem: NSMenuItem! var updateCount = 0 var backups: [String: BackupHost] = [:] var lastUpdate: Date? func applicationDidFinishLaunching(_ aNotification: Notification) { UserDefaults.standard.register(defaults: ["WarningNumDays": 1]) statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength) statusImage = NSImage(named: "img") statusItem?.alternateImage = colorizeImage(image: statusImage, color: NSColor.white) fmt.doesRelativeDateFormatting = true fmt.timeStyle = .short fmt.dateStyle = .short NotificationCenter.default.addObserver(forName: PreferencesController.hostsDidUpdateNotification, object: nil, queue: nil, using: {(_) in self.startUpdate() }) NSWorkspace.shared().notificationCenter.addObserver(forName: .NSWorkspaceDidWake, object: nil, queue: nil, using: {(_) in self.updateCycle() }) updateCycle() } func colorizeImage(image: NSImage, color: NSColor) -> NSImage { let newImage = NSImage(size: image.size) newImage.lockFocus() let rect = NSMakeRect(0, 0, image.size.width, image.size.height) image.draw(in: rect, from: NSZeroRect, operation: .sourceOver, fraction: 1.0) color.setFill() NSRectFillUsingOperation(rect, .sourceAtop) newImage.unlockFocus() return newImage } func updateCycle() { startUpdate() scheduleNextUpdate() } func startUpdate() { updateCount = updateCount + 1 if let hosts = UserDefaults().value(forKey: "Hosts") as? [String] { backupsManager.hosts = hosts } buildMenu() // to show "Updating..." backupsManager.update { (backups: [String : BackupHost]) -> (Void) in self.updateCount = self.updateCount - 1 self.lastUpdate = Date() self.backups = backups self.buildMenu() } } func buildMenu() { let menu = NSMenu() var error = false let now = NSDate() var warning = false let secondsInADay = 86400 let warningNumDays = Double(secondsInADay * UserDefaults.standard.integer(forKey: "WarningNumDays")) // Sort backup keys (hosts) based on their order in the original hosts array let backupsKeys = backups.keys.sorted { (s1: String, s2: String) -> Bool in // Indexes can be nil if a host is removed or renamed let index1 = backupsManager.hosts.index(of: s1) let index2 = backupsManager.hosts.index(of: s2) let s1 = index1 != nil ? index1! : Int.max let s2 = index2 != nil ? index2! : Int.max return s1 < s2 } for host in backupsKeys { let backupHost = backups[host] let hostItem = NSMenuItem(title: host, action: nil, keyEquivalent: "") menu.addItem(hostItem) if let backups = backupHost?.backups.sorted(by: { $0.date > $1.date }), backups.count > 0 { let item = backups[0] let dateStr = fmt.string(from: item.date) let titleStr = String(format: NSLocalizedString("Latest Backup to \"%@\":", comment: ""), item.volumeName) let titleItem = NSMenuItem(title: titleStr, action: nil, keyEquivalent: "") let dateItem = NSMenuItem(title: dateStr, action: nil, keyEquivalent: "") titleItem.indentationLevel = 1 dateItem.indentationLevel = 1 menu.addItem(titleItem) menu.addItem(dateItem) if now.timeIntervalSince(item.date) > warningNumDays { warning = true } } else { let errorItem = NSMenuItem(title: NSLocalizedString("Error", comment: ""), action: #selector(showError), keyEquivalent: "") errorItem.target = self errorItem.representedObject = backupHost! menu.addItem(errorItem) error = true } menu.addItem(NSMenuItem.separator()) } let lastUpdateItemTitle: String if lastUpdate == nil { lastUpdateItemTitle = NSLocalizedString("Updated: Never", comment: "") } else { lastUpdateItemTitle = String(format: NSLocalizedString("Updated: %@", comment: ""), fmt.string(from: lastUpdate!)) } lastUpdatedItem = NSMenuItem(title: lastUpdateItemTitle, action: nil, keyEquivalent: "") updateLastUpdatedItemToolTip() let updateItem: NSMenuItem if updateCount == 0 { updateItem = NSMenuItem(title: NSLocalizedString("Update Now", comment: ""), action: #selector(startUpdate), keyEquivalent: "") } else { updateItem = NSMenuItem(title: NSLocalizedString("Updating…", comment: ""), action: nil, keyEquivalent: "") } updateItem.target = self menu.addItem(lastUpdatedItem) menu.addItem(updateItem) menu.addItem(NSMenuItem.separator()) let prefsItem = NSMenuItem(title: NSLocalizedString("Preferences", comment: ""), action: #selector(showPreferences), keyEquivalent: "") prefsItem.target = self menu.addItem(prefsItem) let aboutStr = String(format: NSLocalizedString("About %@", comment: ""), NSRunningApplication.current().localizedName!) let aboutItem = NSMenuItem(title: aboutStr, action: #selector(showAbout), keyEquivalent: "") aboutItem.target = self menu.addItem(aboutItem) let quitItem = NSMenuItem(title: NSLocalizedString("Quit", comment: ""), action: #selector(NSApp.terminate), keyEquivalent: "") quitItem.target = NSApp menu.addItem(quitItem) if error { statusItem?.image = colorizeImage(image: statusImage, color: NSColor.red) } else if warning { statusItem?.image = colorizeImage(image: statusImage, color: NSColor(calibratedRed:0.50, green:0.00, blue:1.00, alpha:1.0)) } else { statusItem?.image = statusImage } statusItem?.menu = menu } func updateLastUpdatedItemToolTip() { if lastUpdatedItem == nil { return } if nextScheduledUpdate != nil { lastUpdatedItem.toolTip = String(format: NSLocalizedString("Next Update: %@", comment: ""), fmt.string(from: nextScheduledUpdate)) } else { lastUpdatedItem.toolTip = nil } } func showError(sender: Any?) { if let item = sender as? NSMenuItem, let backupHost = item.representedObject as? BackupHost { let alert = NSAlert() alert.informativeText = backupHost.error alert.alertStyle = .critical alert.runModal() } } func showPreferences(sender: Any?) { if prefsController == nil { prefsController = PreferencesController() } NSApp.activate(ignoringOtherApps: true) prefsController?.window?.makeKeyAndOrderFront(sender) } func showAbout(sender: Any?) { NSApp.activate(ignoringOtherApps: true) NSApp.orderFrontStandardAboutPanel(sender) } func scheduleNextUpdate() { // Update every hour at X:30 guard let cal = NSCalendar(calendarIdentifier: .gregorian) else { print("ERROR: Got nil calendar") return } let now = Date() let nowComps = cal.components([.hour, .minute], from: now) let scheduledMinute = 30 // If we're under 1 minute of the scheduled time, use the current hour. Otherwise use the next hour let hour: Int if nowComps.minute! < (scheduledMinute - 1) { hour = nowComps.hour! } else { hour = nowComps.hour! + 1 } guard let scheduledDate = cal.date(bySettingHour: hour, minute: scheduledMinute, second: 0, of: now) else { print("ERROR: Got nil date") return } nextScheduledUpdate = scheduledDate let timerBlock = {(timer: Timer) in self.updateCycle() } if scheduleTimer != nil { scheduleTimer.invalidate() } scheduleTimer = Timer(fire: scheduledDate, interval: 0, repeats: false, block: timerBlock) RunLoop.current.add(scheduleTimer, forMode: RunLoopMode.defaultRunLoopMode) updateLastUpdatedItemToolTip() } }
19efd3ac441a64a2275ba48d16aacf3e
41.408
145
0.624882
false
false
false
false
systers/PowerUp
refs/heads/develop
Powerup/MinesweeperGameScene.swift
gpl-2.0
1
import SpriteKit class MinesweeperGameScene: SKScene { // Make it as an array, so it is easy to add new entries. var possiblityPercentages = [90.0] // MARK: Game Constants let gridSizeCount = 5 let tutorialSceneImages = [ "minesweeper_tutorial_1", "minesweeper_tutorial_2", "minesweeper_tutorial_3" ] // How many boxes could be selected each round. let selectionMaxCount = 5 // Colors of game UIs. let uiColor = UIColor(red: 42.0 / 255.0, green: 203.0 / 255.0, blue: 211.0 / 255.0, alpha: 1.0) let textColor = UIColor(red: 21.0 / 255.0, green: 124.0 / 255.0, blue: 129.0 / 255.0, alpha: 1.0) let prosTextColor = UIColor(red: 105.0 / 255.0, green: 255.0 / 255.0, blue: 97.0 / 255.0, alpha: 1.0) let consTextColor = UIColor(red: 255.0 / 255.0, green: 105.0 / 255.0, blue: 105.0 / 255.0, alpha: 1.0) // Animation constants. let boxEnlargingScale = CGFloat(1.2) let boxEnlargingDuration = 0.25 let buttonWaitDuration = 0.5 let boxFlipInterval = 0.2 let showAllBoxesInterval = 0.3 let boxDarkening = SKAction.colorize(with: UIColor(white: 0.6, alpha: 0.8), colorBlendFactor: 1.0, duration: 0.2) let fadeInAction = SKAction.fadeIn(withDuration: 0.8) let fadeOutAction = SKAction.fadeOut(withDuration: 0.8) let scoreTextPopScale = CGFloat(1.2) let scoreTextPopDuraion = 0.25 // These are relative to the size of the view, so they can be applied to different screen sizes. let gridOffsetYRelativeToHeight = 0.0822 let gridSpacingRelativeToWidth = 0.0125 var gridOffsetXRelativeToWidth:Double var boxSizeRelativeToWidth:Double let continueButtonBottomMargin = 0.08 let continueButtonHeightRelativeToSceneHeight = 0.2 let continueButtonAspectRatio = 2.783 let prosDescriptionPosYRelativeToHeight = 0.77 let consDescriptionPosYRelativeToHeight = 0.33 let descriptionTextPosXReleativeToWidth = 0.53 // Offset the text in y direction so that it appears in the center of the button. let buttonTextOffsetY = -7.0 let scoreTextOffsetX = 10.0 let scoreTextOffsetY = 25.0 // Fonts. let scoreTextFontSize = CGFloat(20) let buttonTextFontSize = CGFloat(18) let descriptionTitleFontSize = CGFloat(24) let descriptionFontSize = CGFloat(20) let fontName = "Montserrat-Bold" let buttonStrokeWidth = CGFloat(3) // These are the actual sizing and positioning, will be calculated in init() let boxSize: Double let gridOffsetX: Double let gridOffsetY: Double let gridSpacing: Double // Sprite nodes let backgroundImage = SKSpriteNode(imageNamed: "minesweeper_background") let resultBanner = SKSpriteNode() let descriptionBanner = SKSpriteNode(imageNamed: "minesweeper_pros_cons_banner") let continueButton = SKSpriteNode(imageNamed: "continue_button") // Label wrapper nodes let scoreLabelNode = SKNode() let prosLabelNode = SKNode() let consLabelNode = SKNode() // Label nodes let scoreLabel = SKLabelNode() let prosLabel = SKLabelNode(text: "Pros text goes here...") let consLabel = SKLabelNode(text: "Cons text goes here...") // Textures let successBannerTexture = SKTexture(imageNamed: "success_banner") let failureBannerTexture = SKTexture(imageNamed: "failure_banner") // TODO: Replace the temporary sprite. let endGameText = "End Game" let scoreTextPrefix = "Score: " // Layer index, aka. zPosition. let backgroundLayer = CGFloat(-0.1) let gridLayer = CGFloat(0.1) let bannerLayer = CGFloat(0.2) let uiLayer = CGFloat(0.3) let uiTextLayer = CGFloat(0.4) let tutorialSceneLayer = CGFloat(5) // MARK: Properties var tutorialScene: SKTutorialScene! // Keep a reference to the view controller for end game transition. // (This is assigned in the MiniGameViewController class.) var viewController: MiniGameViewController! // Holding each boxes var gameGrid: [[GuessingBox]] = [] var roundCount = 0 var currBox: GuessingBox? = nil // Score. +1 if a successful box is chosen. +0 if a failed box is chosen. var score = 0 // Selected box count. var selectedBoxes = 0 // Avoid player interaction with boxes when they are animating. var boxSelected: Bool = false // Avoid player interaction with boxes when the game is in tutorial scene. var inTutorial = true // MARK: Constructor override init(size: CGSize) { // Positioning and sizing background image. backgroundImage.size = size backgroundImage.position = CGPoint(x: size.width / 2.0, y: size.height / 2.0) backgroundImage.zPosition = backgroundLayer // Positioning and sizing result banner. resultBanner.size = size resultBanner.position = CGPoint(x: size.width / 2.0, y: size.height / 2.0) resultBanner.zPosition = bannerLayer resultBanner.isHidden = true // Description Banner descriptionBanner.size = size descriptionBanner.anchorPoint = CGPoint.zero descriptionBanner.position = CGPoint.zero descriptionBanner.zPosition = bannerLayer descriptionBanner.isHidden = true // Score text scoreLabelNode.position = CGPoint(x: Double(size.width) - scoreTextOffsetX, y: Double(size.height) - scoreTextOffsetY) scoreLabelNode.zPosition = bannerLayer scoreLabel.position = CGPoint.zero scoreLabel.fontName = fontName scoreLabel.fontSize = scoreTextFontSize scoreLabel.zPosition = uiLayer scoreLabel.fontColor = uiColor scoreLabel.horizontalAlignmentMode = .right scoreLabelNode.addChild(scoreLabel) // Continue button continueButton.anchorPoint = CGPoint(x: 1.0, y: 0.0) continueButton.size = CGSize(width: CGFloat(continueButtonAspectRatio * continueButtonHeightRelativeToSceneHeight) * size.height, height: size.height * CGFloat(continueButtonHeightRelativeToSceneHeight)) continueButton.position = CGPoint(x: size.width, y: size.height * CGFloat(continueButtonBottomMargin)) continueButton.zPosition = uiLayer continueButton.isHidden = true // Pros label. prosLabelNode.position = CGPoint(x: Double(size.width) * descriptionTextPosXReleativeToWidth, y: Double(size.height) * prosDescriptionPosYRelativeToHeight) prosLabelNode.zPosition = bannerLayer prosLabel.position = CGPoint.zero prosLabel.horizontalAlignmentMode = .left prosLabel.fontName = fontName prosLabel.fontSize = descriptionFontSize prosLabel.fontColor = prosTextColor prosLabel.zPosition = uiLayer prosLabelNode.addChild(prosLabel) descriptionBanner.addChild(prosLabelNode) // Cons label. consLabelNode.position = CGPoint(x: Double(size.width) * descriptionTextPosXReleativeToWidth, y: Double(size.height) * consDescriptionPosYRelativeToHeight) consLabelNode.zPosition = bannerLayer consLabel.position = CGPoint.zero consLabel.horizontalAlignmentMode = .left consLabel.fontName = fontName consLabel.fontSize = descriptionFontSize consLabel.fontColor = consTextColor consLabel.zPosition = uiLayer consLabelNode.addChild(consLabel) descriptionBanner.addChild(consLabelNode) // Set different values of boxSizeRelativeToWidth, gridOffsetXRelativeToWidth for different screen width size let sizeWidth = Double(size.width) if (sizeWidth > 738.0){ gridOffsetXRelativeToWidth = 0.35 boxSizeRelativeToWidth = 0.066 } else{ gridOffsetXRelativeToWidth = 0.31 boxSizeRelativeToWidth = 0.084 } // Calcuate positioning and sizing according to the size of the view. boxSize = Double(size.width) * boxSizeRelativeToWidth gridOffsetX = Double(size.width) * gridOffsetXRelativeToWidth + boxSize / 2.0 gridOffsetY = Double(size.height) * gridOffsetYRelativeToHeight + boxSize / 2.0 gridSpacing = Double(size.width) * gridSpacingRelativeToWidth super.init(size: size) // Initialize grid. for x in 0..<gridSizeCount { gameGrid.append([GuessingBox]()) for y in 0..<gridSizeCount { let newBox = GuessingBox(xOfGrid: x, yOfGrid: y, isCorrect: false, size: CGSize(width: boxSize, height: boxSize)) // Positioning and sizing. let xPos = gridOffsetX + (boxSize + gridSpacing) * Double(x) let yPos = gridOffsetY + (boxSize + gridSpacing) * Double(y) newBox.position = CGPoint(x: xPos, y: yPos) newBox.zPosition = gridLayer gameGrid[x].append(newBox) } } } // MARK: Functions // For initializing the nodes of the game. override func didMove(to view: SKView) { backgroundColor = SKColor.white // Add background image. addChild(backgroundImage) // Add banners. addChild(resultBanner) addChild(descriptionBanner) // Add score label. scoreLabel.text = scoreTextPrefix + String(score) addChild(scoreLabelNode) // Add continue button. addChild(continueButton) // Add boxes. for gridX in gameGrid { for box in gridX { addChild(box) } } if !UserDefaults.tutorialViewed(key: .MineSweeperTutorialViewed) { // Show tutorial scene. After that, start the game. tutorialScene = SKTutorialScene(namedImages: tutorialSceneImages, size: size) { self.newRound() self.inTutorial = false } tutorialScene.position = CGPoint(x: size.width / 2.0, y: size.height / 2.0) tutorialScene.zPosition = tutorialSceneLayer addChild(tutorialScene) } else { self.newRound() self.inTutorial = false } } /** Reset the grid for a new round. - Parameter: The possibility of the contrceptive method in percentage. */ func newRound() { let possibility = possiblityPercentages[roundCount] // Reset selected box count. selectedBoxes = 0 // Successful boxes, grounded to an interger. let totalBoxCount = gridSizeCount * gridSizeCount let successfulBoxCount = Int(Double(totalBoxCount) * possibility / 100.0) let failureBoxCount = totalBoxCount - successfulBoxCount // An array of true/false values according to the success rate. var correctBoxes = [Bool](repeating: true, count: successfulBoxCount) correctBoxes.append(contentsOf: [Bool](repeating: false, count: failureBoxCount)) // Shuffle the array randomly. correctBoxes.shuffle() // Configure each box. for x in 0..<gridSizeCount { for y in 0..<gridSizeCount { let currBox = gameGrid[x][y] // Set whether it is a "success" box or a "failure" box. currBox.isCorrect = correctBoxes.popLast()! // Turn to back side. if currBox.onFrontSide { currBox.changeSide() } // Reset color. currBox.color = UIColor.white } } roundCount += 1 boxSelected = false } func selectBox(box: GuessingBox) { boxSelected = true selectedBoxes += 1 // Animations. let scaleBackAction = SKAction.scale(to: 1.0, duration: self.boxEnlargingDuration) let waitAction = SKAction.wait(forDuration: boxFlipInterval) let scaleBackAndWait = SKAction.sequence([scaleBackAction, waitAction]) box.flip(scaleX: boxEnlargingScale) { // Scale the box back to the original scale. box.run(scaleBackAndWait) { // Check if the round should end. if !box.isCorrect { // A failure box is chosen. self.showAllResults(isSuccessful: false) } else { // Update score. (With a pop animation) self.scoreLabel.setScale(self.scoreTextPopScale) self.score += 1 self.scoreLabel.text = self.scoreTextPrefix + String(self.score) self.scoreLabel.run(SKAction.scale(to: 1.0, duration: self.scoreTextPopDuraion)) // Check if max selection count is reached. if self.selectedBoxes == self.selectionMaxCount { self.showAllResults(isSuccessful: true) } else { // Reset boxSelected flag so that player could continue to select the next box. self.boxSelected = false } } } } currBox = nil } func showAllResults(isSuccessful: Bool) { // Show result banner. resultBanner.texture = isSuccessful ? successBannerTexture : failureBannerTexture resultBanner.alpha = 0.0 resultBanner.isHidden = false let waitAction = SKAction.wait(forDuration: showAllBoxesInterval) let bannerAnimation = SKAction.sequence([fadeInAction, waitAction]) let buttonWaitAction = SKAction.wait(forDuration: buttonWaitDuration) // Fade in banner. resultBanner.run(bannerAnimation) { for x in 0..<self.gridSizeCount { for y in 0..<self.gridSizeCount { let currBox = self.gameGrid[x][y] // Don't darken the selected box. if currBox.onFrontSide { continue } // Darkens the color and flip the box. currBox.run(self.boxDarkening) { currBox.changeSide() } } } // Continue button. Change text and fade in. self.continueButton.alpha = 0.0 self.continueButton.isHidden = false self.continueButton.run(SKAction.sequence([buttonWaitAction, self.fadeInAction])) } } // Called when "continue button" is pressed under the "result banner". func showDescription() { // Fade out result banner. resultBanner.run(fadeOutAction) { self.resultBanner.isHidden = true } // Fade in description banner. descriptionBanner.isHidden = false descriptionBanner.alpha = 0.0 descriptionBanner.run(fadeInAction) { // Fade in "next round" or "end game" button. self.continueButton.alpha = 0.0 self.continueButton.isHidden = false self.continueButton.run(self.fadeInAction) } } // Called when "continue button" is pressed under the "description banner". func hideDescription() { // Fade out description banner. descriptionBanner.run(fadeOutAction) { self.descriptionBanner.isHidden = true } } // MARK: Touch inputs override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if inTutorial { return } // Only the first touch is effective. guard let touch = touches.first else { return } let location = touch.location(in: self) // Continue button pressed. if !continueButton.isHidden && continueButton.contains(location) { // Hide button. Avoid multiple touches. continueButton.isHidden = true // Check if it is the button of "result banner" or "description banner". if !resultBanner.isHidden { // Button in the result banner. Show description when tapped. showDescription() // Record score to update karma points viewController.score = score viewController.endGame() } else if roundCount < possiblityPercentages.count { // Not the last round, hide description banner and start a new round. newRound() hideDescription() // Record score to update karma points viewController.score = score viewController.endGame() } else { // Record score to update karma points viewController.score = score // End game. viewController.endGame() } } // Guessing box selected, not animating, and not selected yet. if let guessingBox = atPoint(location) as? GuessingBox, !boxSelected, !guessingBox.onFrontSide { currBox = guessingBox // Perform animation. guessingBox.removeAction(forKey: boxShrinkingKey) guessingBox.run(SKAction.scale(to: boxEnlargingScale, duration: boxEnlargingDuration), withKey: boxEnlargingKey) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if inTutorial { return } // Only the first touch is effective. guard let touch = touches.first else { return } let location = touch.location(in: self) // Guessing box selected, equals to the current selected box, and no box is selected yet. if let guessingBox = atPoint(location) as? GuessingBox, guessingBox == currBox, !boxSelected { selectBox(box: guessingBox) } else if let box = currBox { // Animate (shrink) back the card. box.removeAction(forKey: boxEnlargingKey) box.run(SKAction.scale(to: 1.0, duration: boxEnlargingDuration), withKey: boxEnlargingKey) currBox = nil } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) not implemented.") } }
d9b8f1cc1bf87b2e376b8ceaf21f7cba
37.006024
211
0.60094
false
false
false
false
ricardorauber/iOS-Swift
refs/heads/master
iOS-Swift.playground/Pages/Constants and Variables.xcplaygroundpage/Contents.swift
mit
1
//: ## Constants and Variables //: ---- //: [Previous](@previous) import Foundation //: Constants let constant = "My first constant!" //: Variables var variable = "My first variable!" var r = 250.0, g = 100.0, b = 210.0 //: Type Annotations var hello: String hello = "Hello!" //: Emoji Names //: - Emoji shortcut: control + command + space let 😎 = ":)" //: Printing print(😎) print("Using a string with a constant or variable: \(hello) \(😎)") //: Comments // One line comment /* Multiple Lines Comment */ //: Integer let intConstant1 = 10 let intConstant2: Int = 10 let uIntConstant: UInt = 20 let uInt8Constant: UInt8 = 8 let uInt16Constant: UInt16 = 16 let uInt32Constant: UInt32 = 32 let uInt64Constant: UInt64 = 21 //: Float let floatConstant: Float = 10.5 //: Double let doubleConstant1 = 30.7 let doubleConstant2: Double = 30.7 //: Boolean let trueConstant = true let falseConstant: Bool = false let anotherOne = !trueConstant //: String let stringConstant1 = "You already know that, right?" let stringConstant2: String = "Yes, you know!" //: Tuples let tupleWith2Values = (100, "A message") let tupleWith2NamedValues = (number: 200, text: "Another Message") let (intValue, stringValue) = tupleWith2Values let (onlyTheIntValue, _) = tupleWith2NamedValues let (_, onlyTheStringValue) = tupleWith2NamedValues let standardConstantFromTuple = tupleWith2Values.0 let standardConstantFromNamedTuple = tupleWith2NamedValues.text print( intValue, stringValue, onlyTheIntValue, onlyTheStringValue, standardConstantFromTuple, standardConstantFromNamedTuple ) //: Type aliases typealias MyInt = Int8 var customAlias1 = MyInt.min var customAlias2 = MyInt.max //: Converting types let doubleToIntConstant = Int(45.32) let intToDoubleConstant = Double(50) //: [Next](@next)
3976e04bae7e5ac197098997e8dd872b
17.029703
66
0.716639
false
false
false
false
e78l/swift-corelibs-foundation
refs/heads/master
Foundation/NSPlatform.swift
apache-2.0
2
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if os(macOS) || os(iOS) fileprivate let _NSPageSize = Int(vm_page_size) #elseif os(Linux) || os(Android) fileprivate let _NSPageSize = Int(getpagesize()) #elseif os(Windows) import WinSDK fileprivate var _NSPageSize: Int { var siInfo: SYSTEM_INFO = SYSTEM_INFO() GetSystemInfo(&siInfo) return Int(siInfo.dwPageSize) } #endif public func NSPageSize() -> Int { return _NSPageSize } public func NSRoundUpToMultipleOfPageSize(_ size: Int) -> Int { let ps = NSPageSize() return (size + ps - 1) & ~(ps - 1) } public func NSRoundDownToMultipleOfPageSize(_ size: Int) -> Int { return size & ~(NSPageSize() - 1) } func NSCopyMemoryPages(_ source: UnsafeRawPointer, _ dest: UnsafeMutableRawPointer, _ bytes: Int) { #if os(macOS) || os(iOS) if vm_copy(mach_task_self_, vm_address_t(bitPattern: source), vm_size_t(bytes), vm_address_t(bitPattern: dest)) != KERN_SUCCESS { memmove(dest, source, bytes) } #else memmove(dest, source, bytes) #endif }
212e778f07967b70cdcd99f034d015be
28.688889
133
0.700599
false
false
false
false
BanyaKrylov/Learn-Swift
refs/heads/master
Skill/Homework 6/Homework 6.6.3/Homework 6.6.3/ViewController.swift
apache-2.0
1
// // ViewController.swift // Homework 6.6.3 // // Created by Ivan Krylov on 03.02.2020. // Copyright © 2020 Ivan Krylov. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var numberOne: UITextField! @IBOutlet weak var operatorForCalc: UITextField! @IBOutlet weak var numberTwo: UITextField! @IBAction func calculationButton(_ sender: Any) { let operators: Optional = (plus: "+", minus: "-", division: "/", multiple: "*") if Int(numberOne.text!) != nil && Int(numberTwo.text!) != nil && operators != nil{ switch operatorForCalc.text! { case operators!.plus: resultLabel.text = String(Int(numberOne.text!)! + Int(numberTwo.text!)!) case operators!.minus: resultLabel.text = String(Int(numberOne.text!)! - Int(numberTwo.text!)!) case operators!.division: resultLabel.text = String(Double(Int(numberOne.text!)!) / Double(Int(numberTwo.text!)!)) case operators!.multiple: resultLabel.text = String(Int(numberOne.text!)! * Int(numberTwo.text!)!) default: resultLabel.text = "Некорректные данные" } } else { resultLabel.text = "Некорректные данные" } } }
e80f4abfe09fa030c77ef19df588f619
34.738095
104
0.602931
false
false
false
false
youkchansim/CSPhotoGallery
refs/heads/master
Example/CSPhotoGallery/ViewController.swift
mit
1
// // ViewController.swift // CSPhotoGallery // // Created by chansim.youk on 12/30/2016. // Copyright (c) 2016 chansim.youk. All rights reserved. // import UIKit import CSPhotoGallery import Photos class ViewController: UIViewController { @IBAction func btnAction(_ sender: Any) { let designManager = CSPhotoDesignManager.instance // Main designManager.photoGalleryOKButtonTitle = "OK" let vc = CSPhotoGalleryViewController.instance vc.delegate = self vc.CHECK_MAX_COUNT = 10 vc.horizontalCount = 4 // present(vc, animated: true) navigationController?.pushViewController(vc, animated: true) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: CSPhotoGalleryDelegate { func getAssets(assets: [PHAsset]) { assets.forEach { let size = CGSize(width: $0.pixelWidth, height: $0.pixelHeight) PhotoManager.sharedInstance.assetToImage(asset: $0, imageSize: size, completionHandler: nil) } } }
5b923af69914208e7c25c9ae2c8f6808
27.73913
104
0.657337
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureCryptoDomain/Sources/FeatureCryptoDomainUI/Accessibility+CryptoDomain.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. enum AccessibilityIdentifiers { // MARK: - How it Works Sceren enum HowItWorks { static let prefix = "HowItWorksScreen." static let headerTitle = "\(prefix)headerTitle" static let headerDescription = "\(prefix)headerDescription" static let introductionList = "\(prefix)instructionList" static let smallButton = "\(prefix)smallButton" static let instructionText = "\(prefix)instructionText" static let ctaButton = "\(prefix)ctaButton" } // MARK: - Benefits Screen enum Benefits { static let prefix = "CryptoDomainBenefitsScreen." static let headerTitle = "\(prefix)headerTitle" static let headerDescription = "\(prefix)headerDescription" static let benefitsList = "\(prefix)benefitsList" static let ctaButton = "\(prefix)ctaButton" } // MARK: - Search Domain Screen enum SearchDomain { static let prefix = "SearchDomainScreen." static let searchBar = "\(prefix)searchBar" static let alertCard = "\(prefix)alertCard" static let domainList = "\(prefix)domainList" static let domainListRow = "\(prefix)domainListRow" } // MARK: - Domain Checkout Screen enum DomainCheckout { static let prefix = "DomainCheckoutScreen." static let selectedDomainList = "\(prefix)selectedDomainList" static let termsSwitch = "\(prefix)termsSwitch" static let termsText = "\(prefix)termsText" static let ctaButton = "\(prefix)ctaButton" static let emptyStateIcon = "\(prefix)emptyStateIcon" static let emptyStateTitle = "\(prefix)emptyStateTitle" static let emptyStateDescription = "\(prefix)emptyStateDescription" static let browseButton = "\(prefix)browseButton" } enum RemoveDomainBottomSheet { static let prefix = "RemoveDomainBottomSheet." static let removeIcon = "\(prefix)removeIcon" static let removeTitle = "\(prefix)removeTitle" static let removeButton = "\(prefix)removeButton" static let nevermindButton = "\(prefix)nevermindButton" } enum BuyDomainBottomSheet { static let prefix = "BuyDomainBottomSheet." static let buyTitle = "\(prefix)buyTitle" static let buyDescription = "\(prefix)buyTitle" static let buyButton = "\(prefix)buyButton" static let goBackButton = "\(prefix)goBackButton" } // MARK: - Checkout Confirmation Screen enum CheckoutConfirmation { static let prefix = "DomainCheckoutConfirmationScreen." static let icon = "\(prefix)icon" static let title = "\(prefix)title" static let description = "\(prefix)description" static let learnMoreButton = "\(prefix)learnMoreButton" static let okayButton = "\(prefix)okayButton" } }
cb158e47f0c258ac74d35c88f43f8a09
36.883117
75
0.661981
false
false
false
false
lfkdsk/JustUiKit
refs/heads/master
JustUiKit/params/JustLayoutParams.swift
mit
1
/// MIT License /// /// Copyright (c) 2017 JustWe /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in all /// copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// SOFTWARE. import UIKit public class LayoutParams { public static let MATCH_PARENT: CGFloat = -1 public static let WRAP_CONTENT: CGFloat = -2 public var width: CGFloat = 0 public var height: CGFloat = 0 public var bindView: UIView? = nil public init(width: CGFloat, height: CGFloat) { self.width = width self.height = height } public func bindWith(view: UIView?) { self.bindView = view } public init(_ params: LayoutParams) { self.width = params.width self.height = params.height } public static func generateDefaultLayoutParams() -> LayoutParams { return LayoutParams(width: 0, height: 0) } } public class MarginLayoutParams: LayoutParams { private static let DEFAULT_MARGIN: Int = 0; public var leftMargin = DEFAULT_MARGIN public var rightMargin = DEFAULT_MARGIN public var topMargin = DEFAULT_MARGIN public var bottomMargin = DEFAULT_MARGIN public var startMargin = DEFAULT_MARGIN public var endMargin = DEFAULT_MARGIN override public init(_ source: LayoutParams) { super.init(source) } override public init(width: CGFloat, height: CGFloat) { super.init(width: width, height: height) } public init(source: MarginLayoutParams) { super.init(width: source.width, height: source.height) self.leftMargin = source.leftMargin self.rightMargin = source.rightMargin self.topMargin = source.topMargin self.bottomMargin = source.bottomMargin } public func setMargins(left: Int, top: Int, right: Int, bottom: Int) { leftMargin = left; topMargin = top; rightMargin = right; bottomMargin = bottom; } }
421faf876ce5f93d2ab0c974e33071ab
32.397727
85
0.679823
false
false
false
false
alessandrostone/TKSwarmAlert
refs/heads/master
TKSwarmAlert/Classes/TKSwarmAlert.swift
mit
9
// // SWAlert.swift // SWAlertView // // Created by Takuya Okamoto on 2015/08/18. // Copyright (c) 2015年 Uniface. All rights reserved. // import UIKit public typealias Closure=()->Void public class TKSwarmAlert { public var didDissmissAllViews: Closure? private var staticViews: [UIView] = [] var animationView: FallingAnimationView? var blurView: TKSWBackgroundView? public init() { } public func addNextViews(views:[UIView]) { self.animationView?.nextViewsList.append(views) } public func addSubStaticView(view:UIView) { view.tag = -1 self.staticViews.append(view) } public func show(#type:TKSWBackgroundType ,views:[UIView]) { let window:UIWindow? = UIApplication.sharedApplication().keyWindow if window != nil { let frame:CGRect = window!.bounds blurView = TKSWBackgroundView(frame: frame) animationView = FallingAnimationView(frame: frame) let showDuration:NSTimeInterval = 0.2 for staticView in staticViews { let originalAlpha = staticView.alpha staticView.alpha = 0 animationView?.addSubview(staticView) UIView.animateWithDuration(showDuration) { staticView.alpha = originalAlpha } } window!.addSubview(blurView!) window!.addSubview(animationView!) blurView?.show(type: type, duration:showDuration) { self.spawn(views) } animationView?.willDissmissAllViews = { let fadeOutDuration:NSTimeInterval = 0.2 for v in self.staticViews { UIView.animateWithDuration(fadeOutDuration) { v.alpha = 0 } } UIView.animateWithDuration(fadeOutDuration) { blurView?.alpha = 0 } } animationView?.didDissmissAllViews = { self.blurView?.removeFromSuperview() self.animationView?.removeFromSuperview() self.didDissmissAllViews?() for staticView in self.staticViews { staticView.alpha = 1 } } } } public func spawn(views:[UIView]) { self.animationView?.spawn(views) } }
7c668f10ef10c2c7fc971447b97a581f
28.939759
74
0.552113
false
false
false
false
sdhzwm/BaiSI-Swift-
refs/heads/master
BaiSi/BaiSi/Classes/Main(主要)/Controller/WMNavigationController.swift
apache-2.0
1
// // WMNavigationController.swift // WMMatchbox // // Created by 王蒙 on 15/7/21. // Copyright © 2015年 wm. All rights reserved. // import UIKit class WMNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() UINavigationBar.appearance().setBackgroundImage(UIImage(named: "navigationbarBackgroundWhite"), forBarMetrics: UIBarMetrics.Default) } override func pushViewController(viewController: UIViewController, animated: Bool) { if (self.childViewControllers.count>0) { let btn = UIButton(type: UIButtonType.Custom) btn.setTitle("返回", forState: UIControlState.Normal) btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) btn.setTitleColor(UIColor.redColor(), forState: UIControlState.Highlighted) btn.setImage(UIImage(named: "navigationButtonReturn"), forState: UIControlState.Normal) btn.setImage(UIImage(named: "navigationButtonReturnClick"), forState: UIControlState.Highlighted) btn.sizeToFit() btn.contentEdgeInsets = UIEdgeInsetsMake(0, -35, 0, 0); // btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; // btn.size = CGSizeMake(60, 35); // btn.contentEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0); btn.addTarget(self, action: "onClick", forControlEvents: UIControlEvents.TouchUpInside) btn.titleLabel?.font = UIFont.systemFontOfSize(14) viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn) viewController.hidesBottomBarWhenPushed = true; } super.pushViewController(viewController, animated: true) } func onClick(){ self.popViewControllerAnimated(true) } }
c883356aaa708ee0c9557647266d7cca
36.692308
140
0.647449
false
false
false
false
r14r-work/fork_swift_intro-playgrounds
refs/heads/master
08-Functions (Part 2).playground/section-1.swift
mit
2
// Functions - Part 2 import Foundation // ************************************************************************* // Simple "void" function - takes no parameters, returns nothing func sayHi() { println("Hi") } sayHi() // ************************************************************************* // Function taking two parameters, printing result of adding parameters. func printAplusB(a: Int, b: Int) { println("\(a) + \(b) = \(a+b)") } printAplusB(10, 20) // ************************************************************************* // Function returning the answer as a string. // -> is called the "return arrow" func resultOfAplusB(a: Int, b: Int) -> String { return "\(a) + \(b) = \(a+b)" } // Try option+click on "result". Xcode shows you the type info! let result = resultOfAplusB(30, 40) // ************************************************************************* // Returning a tuple func doHTTPGet(urlString: String) -> (statusCode: Int, statusMessage: String) { // Imagine we are doing an actual HTTP request here. return (200, "OK") } let getResult = doHTTPGet("http://twitter.com") println("Code - \(getResult.statusCode)") println("Message - \(getResult.statusMessage)") // ************************************************************************* // You must return a value from each control path in a function! func missingReturn(flag: Bool) -> Int { if flag == true { return 1 } else { // Comment out to see error. return 0 // error: missing return in a function expected to return 'Int' } } // ********************* // START HERE FOR PART 2 // ********************* // ************************************************************************* // External parameter names (named parameters). If provided, external // parameter names must always be used when calling function. func distanceBetweenPoints(X1 x1: Double, Y1 y1: Double, X2 x2:Double, Y2 y2:Double) -> Double { let dx = x2 - x1 let dy = y2 - y1 return sqrt(dx * dx + dy * dy) } let distance = distanceBetweenPoints(X1: 0.0, Y1: 0.0, X2: 10.0, Y2: 0.0) // ************************************************************************* // Short-hand for external names (use when internal name is suitable for use // as external name too. func lineLength(#x1: Double, #y1: Double, #x2: Double, #y2: Double) -> Double { let dx = x2 - x1 let dy = y2 - y1 return sqrt(dx * dx + dy * dy) } let length = lineLength(x1: 0.0, y1: 0.0, x2: 10.0, y2: 0.0) // ************************************************************************* // Default parameter values func concatenateStrings(s1: String, s2: String, separator: String = " ") -> String { return s1 + separator + s2 } concatenateStrings("Bennett", "Smith") // Note: parameter with default value always has external name! concatenateStrings("Hello", "World", separator: ", ") // ************************************************************************* // Variadic paramters (variable length array of parameters, all of same type!) func addNumbers(numbers: Double ...) -> Double { var sum = 0.0 for number in numbers { sum += number } return sum } let total = addNumbers(0.99, 1.21, 0.30, 2.50) // ************************************************************************* // Constant vs. variable parameters. // Variable parameters can be changed within the function, but their // values do not live beyond the scope of the function. func applyOffset_Broken(number: Int, offset: Int) { // Uncomment to see error. // number = number + offset // error: cannot assign to 'let' value 'number' } func applyOffset_Works(var number: Int, offset: Int) { number = number + offset } var n = 10 let o = 2 applyOffset_Broken(n, o) n applyOffset_Works(n, o) n // ************************************************************************* // In-Out Parameters func applyOffset(inout Number n:Int, let Offset o:Int = 5) { n = n + o } applyOffset(Number: &n) n applyOffset(Number: &n, Offset: 25) n // ************************************************************************* // Function Types - Every function is actually a Swift type, made up of the // parameter types and the return type. // A function that takes no parameters and returns nothing. func degenerateCase() { } // Type of this function is "() -> ()" // More interesting case... func add(a: Int, b: Int) -> Int { return a + b } func mul(a: Int, b: Int) -> Int { return a * b } // Type for both functions is "(Int, Int) -> Int" // Can store a function in a variable like so: var mathOp: (Int, Int) -> Int = mul // Can invoke function using function type like so: let r1 = mathOp(2, 3) // And re-assign it, pointing at a different function. mathOp = add let r2 = mathOp(2, 3) // This is very similar to C function pointers! // ************************************************************************* // Passing function type as a parameter func performMathOp(mathOp: (Int, Int) -> Int, a: Int, b: Int) { let result = mathOp(a, b) println("result = \(result)") } performMathOp(add, 3, 2) // ************************************************************************* // Returning function type from a function func randomMathOp() -> (Int, Int) -> Int { let r = arc4random_uniform(1) if r == 0 { return add } else { return mul } } mathOp = randomMathOp() let r3 = mathOp(2, 2) // ************************************************************************* // Nested functions func sortNumbers(numbers: Int[]) -> Int[] { func compare(n1: Int, n2: Int) -> Bool { return n1 < n2 } var result = sort(numbers, compare) return result } let numbers = [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ] let sortedNumbers = sortNumbers(numbers) // *************************************************************************
b93875c6275f42ba7011c9911ba5edeb
23.395918
96
0.503932
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/Views/AvatarView.swift
gpl-3.0
1
// // AvatarView.swift // Habitica // // Created by Phillip Thelen on 07.02.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import UIKit import PinLayout import Kingfisher @objc enum AvatarViewSize: Int { case compact case regular } @IBDesignable class AvatarView: UIView { @objc var avatar: Avatar? { didSet { if let dict = avatar?.getFilenameDictionary(ignoreSleeping: ignoreSleeping) { nameDictionary = dict } updateView() } } @IBInspectable var showBackground: Bool = true @IBInspectable var showMount: Bool = true @IBInspectable var showPet: Bool = true @IBInspectable var isFainted: Bool = false @IBInspectable var ignoreSleeping: Bool = false @objc var size: AvatarViewSize = .regular public var onRenderingFinished: (() -> Void)? private var nameDictionary: [String: String?] = [:] private var viewDictionary: [String: Bool] = [:] private let viewOrder = [ "background", "mount-body", "chair", "back", "skin", "shirt", "head_0", "armor", "body", "hair-bangs", "hair-base", "hair-mustache", "hair-beard", "eyewear", "head", "head-accessory", "hair-flower", "shield", "weapon", "visual-buff", "mount-head", "zzz", "knockout", "pet" ] lazy private var constraintsDictionary = [ "background": backgroundConstraints, "mount-body": mountConstraints, "chair": characterConstraints, "back": characterConstraints, "skin": characterConstraints, "shirt": characterConstraints, "armor": characterConstraints, "body": characterConstraints, "head_0": characterConstraints, "hair-base": characterConstraints, "hair-bangs": characterConstraints, "hair-mustache": characterConstraints, "hair-beard": characterConstraints, "eyewear": characterConstraints, "head": characterConstraints, "head-accessory": characterConstraints, "hair-flower": characterConstraints, "shield": characterConstraints, "weapon": characterConstraints, "visual-buff": characterConstraints, "mount-head": mountConstraints, "zzz": characterConstraints, "knockout": characterConstraints, "pet": petConstraints ] lazy private var specialConstraintsDictionary = [ "weapon_special_0": weaponSpecialConstraints, "weapon_special_1": weaponSpecialConstraints, "weapon_special_critical": weaponSpecialCriticalConstraints, "head_special_0": headSpecialConstraints, "head_special_1": headSpecialConstraints ] func resize(view: UIImageView, image: UIImage, size: AvatarViewSize) { let ratio = image.size.width / image.size.height if size == .regular { view.pin.aspectRatio(ratio).height(image.size.height * (self.bounds.size.height / 147)) } else { view.pin.aspectRatio(ratio).height(image.size.height * (self.bounds.size.height / 90)) } } let backgroundConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in view.pin.all() } let characterConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in if size == .regular { view.pin.start(17%).top(offset) } else { view.pin.start().top(offset) } } let mountConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in view.pin.start(17.5%).top(12%) } let petConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in view.pin.start().bottom() } let weaponSpecialConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in if size == .regular { view.pin.start(8%).top(offset) } else { view.pin.start().top(offset) } } let weaponSpecialCriticalConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in if size == .regular { view.pin.start(8%).top(offset+10) } else { view.pin.start(-10%).top(offset) } } let headSpecialConstraints: ((AvatarView, UIImageView, AvatarViewSize, CGFloat) -> Void) = { superview, view, size, offset in if size == .regular { view.pin.start(17%).top(offset+3) } else { view.pin.start().top(offset+3) } } var imageViews = [NetworkImageView]() override init(frame: CGRect) { super.init(frame: frame) setupSubviews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSubviews() } private func setupSubviews() { viewOrder.forEach({ (_) in let imageView = NetworkImageView() addSubview(imageView) imageViews.append(imageView) }) } private func updateView() { guard let avatar = self.avatar else { return } viewDictionary = avatar.getViewDictionary(showsBackground: showBackground, showsMount: showMount, showsPet: showPet, isFainted: isFainted, ignoreSleeping: ignoreSleeping) viewOrder.enumerated().forEach({ (index, type) in if viewDictionary[type] ?? false { let imageView = imageViews[index] imageView.isHidden = false setImage(imageView, type: type) } else { let imageView = imageViews[index] imageView.image = nil imageView.isHidden = true } }) if let action = self.onRenderingFinished { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { action() } } } private func setImage(_ imageView: NetworkImageView, type: String) { guard let name = nameDictionary[type] else { return } imageView.setImagewith(name: name, completion: { image, error in if let image = image, type != "background" { self.resize(view: imageView, image: image, size: self.size) self.setLayout(imageView, type: type) } if error != nil { print(error?.localizedDescription ?? "") } }) } override func layoutSubviews() { super.layoutSubviews() layout() } private func layout() { viewOrder.enumerated().forEach({ (index, type) in if viewDictionary[type] ?? false { let imageView = imageViews[index] imageView.isHidden = false if let image = imageView.image, type != "background" { self.resize(view: imageView, image: image, size: self.size) setLayout(imageView, type: type) } setLayout(imageView, type: type) } else { let imageView = imageViews[index] imageView.image = nil imageView.isHidden = true } }) } private func setLayout(_ imageView: UIImageView, type: String) { var offset: CGFloat = 0 if !(viewDictionary["mount-head"] ?? false) && size == .regular { offset = 28 if viewDictionary["pet"] ?? false { offset -= 3 } } if nameDictionary["mount-head"]??.contains("Kangaroo") == true && size == .regular { offset = 16 } let name = nameDictionary[type] ?? "" if let name = name, specialConstraintsDictionary[name] != nil { specialConstraintsDictionary[name]?(self, imageView, size, offset) } else { constraintsDictionary[type]?(self, imageView, size, offset) } } }
3a196640e241b7ac5e3aa505aed69f31
31.316602
178
0.56822
false
false
false
false
vittoriom/NDHpple
refs/heads/master
NDHpple/NDHpple/NDHppleElement.swift
mit
1
// // NDHppleElement.swift // NDHpple // // Created by Nicolai on 24/06/14. // Copyright (c) 2014 Nicolai Davidsson. All rights reserved. // import Foundation enum NDHppleNodeKey: String { case Content = "nodeContent" case Name = "nodeName" case Children = "nodeChildArray" case AttributeArray = "nodeAttributeArray" case AttributeContent = "attributeContent" case AttributeName = "attributeName" } class NDHppleElement { typealias Node = Dictionary<String, AnyObject> let node: Node weak var parent: NDHppleElement? convenience init(node: Node) { self.init(node: node, parent: nil) } init(node: Node, parent: NDHppleElement?) { self.node = node self.parent = parent } subscript(key: String) -> AnyObject? { return self.node[key] } var description: String { return self.node.description } var hasChildren: Bool { return self[NDHppleNodeKey.Children.rawValue] as? Int != nil } var isTextNode: Bool { return self.tagName == "text" && self.content != nil } var raw: String? { return self["raw"] as? String } var content: String? { return self[NDHppleNodeKey.Content.rawValue] as? String } var tagName: String? { return self[NDHppleNodeKey.Name.rawValue] as? String } var children: Array<NDHppleElement>? { let children = self[NDHppleNodeKey.Children.rawValue] as? Array<Dictionary<String, AnyObject>> return children?.map{ NDHppleElement(node: $0, parent: self) } } var firstChild: NDHppleElement? { return self.children?[0] } func childrenWithTagName(tagName: String) -> Array<NDHppleElement>? { return self.children?.filter{ $0.tagName == tagName } } func firstChildWithTagName(tagName: String) -> NDHppleElement? { return self.childrenWithTagName(tagName)?[0] } func childrenWithClassName(className: String) -> Array<NDHppleElement>? { return self.children?.filter{ $0["class"] as? String == className } } func firstChildWithClassName(className: String) -> NDHppleElement? { return self.childrenWithClassName(className)?[0] } var firstTextChild: NDHppleElement? { return self.firstChildWithTagName("text") } var text: String? { return self.firstTextChild?.content } var attributes: Dictionary<String, AnyObject> { var translatedAttribtues = Dictionary<String, AnyObject>() for attributeDict in self[NDHppleNodeKey.AttributeArray.rawValue] as! Array<Dictionary<String, AnyObject>> { if attributeDict[NDHppleNodeKey.Content.rawValue] != nil && attributeDict[NDHppleNodeKey.AttributeName.rawValue] != nil { let value : AnyObject = attributeDict[NDHppleNodeKey.Content.rawValue]! let key : AnyObject = attributeDict[NDHppleNodeKey.AttributeName.rawValue]! translatedAttribtues.updateValue(value, forKey: key as! String) } } return translatedAttribtues } }
a5cd48a8b6e991d050e7b57d4da18029
33.153846
147
0.656049
false
false
false
false
kyleduo/TinyPNG4Mac
refs/heads/master
source/tinypng4mac/utils/TPConfig.swift
mit
1
// // KeyStore.swift // tinypng // // Created by kyle on 16/7/1. // Copyright © 2016年 kyleduo. All rights reserved. // import Foundation class TPConfig { static let KEY_API = "saved_api_key" static let KEY_OUTPUT_FILE = "output_path" static let KEY_REPLACE = "replace" static func saveKey(_ key: String) { UserDefaults.standard.set(key, forKey: KEY_API) } static func savedkey() -> String? { return UserDefaults.standard.string(forKey: KEY_API) } static func savePath(_ path: String) { UserDefaults.standard.set(path, forKey: KEY_OUTPUT_FILE) } static func savedPath() -> String? { var path = UserDefaults.standard.string(forKey: KEY_OUTPUT_FILE) if path == nil || path == "" { path = IOHeler.getDefaultOutputPath().path TPConfig.savePath(path!) } return path } static func saveReplace(_ replace: Bool) { UserDefaults.standard.set(replace, forKey: KEY_REPLACE); } static func shouldReplace() -> Bool! { return UserDefaults.standard.bool(forKey: KEY_REPLACE) } static func removeKey() { UserDefaults.standard.removeObject(forKey: KEY_API) UserDefaults.standard.removeObject(forKey: KEY_REPLACE) } }
3dd8903d74fb4b6bec4f3252706fb57f
22.734694
66
0.699054
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
Domain Model/EurofurenceModelTests/Test Doubles/API/FakeAPI.swift
mit
1
import EurofurenceModel import Foundation class FakeAPI: API { private var feedbackRequests: [EventFeedbackRequest: (Bool) -> Void] = [:] func submitEventFeedback(_ request: EventFeedbackRequest, completionHandler: @escaping (Bool) -> Void) { feedbackRequests[request] = completionHandler } func simulateSuccessfulFeedbackResponse(for request: EventFeedbackRequest) { guard let handler = feedbackRequests[request] else { return } handler(true) feedbackRequests[request] = nil } func simulateUnsuccessfulFeedbackResponse(for request: EventFeedbackRequest) { guard let handler = feedbackRequests[request] else { return } handler(false) feedbackRequests[request] = nil } private(set) var capturedLoginRequest: LoginRequest? private var loginHandler: ((LoginResponse?) -> Void)? func performLogin(request: LoginRequest, completionHandler: @escaping (LoginResponse?) -> Void) { capturedLoginRequest = request loginHandler = completionHandler } private(set) var wasToldToLoadPrivateMessages = false private(set) var capturedAuthToken: String? private var messagesHandler: (([MessageCharacteristics]?) -> Void)? func loadPrivateMessages(authorizationToken: String, completionHandler: @escaping ([MessageCharacteristics]?) -> Void) { wasToldToLoadPrivateMessages = true capturedAuthToken = authorizationToken self.messagesHandler = completionHandler } private(set) var messageIdentifierMarkedAsRead: String? private(set) var capturedAuthTokenForMarkingMessageAsRead: String? func markMessageWithIdentifierAsRead(_ identifier: String, authorizationToken: String) { messageIdentifierMarkedAsRead = identifier capturedAuthTokenForMarkingMessageAsRead = authorizationToken } var requestedFullStoreRefresh: Bool { return capturedLastSyncTime == nil } fileprivate var completionHandler: ((ModelCharacteristics?) -> Void)? private(set) var capturedLastSyncTime: Date? private(set) var didBeginSync = false func fetchLatestData(lastSyncTime: Date?, completionHandler: @escaping (ModelCharacteristics?) -> Void) { didBeginSync = true capturedLastSyncTime = lastSyncTime self.completionHandler = completionHandler } private struct DownloadRequest: Hashable { var identifier: String var contentHashSha1: String } private var stubbedResponses = [DownloadRequest: Data]() private(set) var downloadedImageIdentifiers = [String]() func fetchImage(identifier: String, contentHashSha1: String, completionHandler: @escaping (Data?) -> Void) { downloadedImageIdentifiers.append(identifier) let data = "\(identifier)_\(contentHashSha1)".data(using: .utf8) let request = DownloadRequest(identifier: identifier, contentHashSha1: contentHashSha1) stubbedResponses[request] = data completionHandler(data) } } extension FakeAPI { func stubbedImage(for identifier: String?, availableImages: [ImageCharacteristics]) -> Data? { return stubbedResponses.first(where: { $0.key.identifier == identifier })?.value } func simulateSuccessfulSync(_ response: ModelCharacteristics) { completionHandler?(response) } func simulateUnsuccessfulSync() { completionHandler?(nil) } func simulateLoginResponse(_ response: LoginResponse) { loginHandler?(response) } func simulateLoginFailure() { loginHandler?(nil) } func simulateMessagesResponse(response: [MessageCharacteristics] = []) { messagesHandler?(response) } func simulateMessagesFailure() { messagesHandler?(nil) } } class SlowFakeImageAPI: FakeAPI { fileprivate var pendingFetches = [() -> Void]() var numberOfPendingFetches: Int { return pendingFetches.count } override func fetchImage(identifier: String, contentHashSha1: String, completionHandler: @escaping (Data?) -> Void) { pendingFetches.append { super.fetchImage(identifier: identifier, contentHashSha1: contentHashSha1, completionHandler: completionHandler) } } } extension SlowFakeImageAPI { func resolvePendingFetches() { pendingFetches.forEach({ $0() }) pendingFetches.removeAll() } func resolveNextFetch() { guard pendingFetches.isEmpty == false else { return } let next = pendingFetches.remove(at: 0) next() } } class OnlyToldToRefreshOnceMockAPI: FakeAPI { private var refreshCount = 0 var toldToRefreshOnlyOnce: Bool { return refreshCount == 1 } override func fetchLatestData(lastSyncTime: Date?, completionHandler: @escaping (ModelCharacteristics?) -> Void) { refreshCount += 1 super.fetchLatestData(lastSyncTime: lastSyncTime, completionHandler: completionHandler) } }
393dbd481bb91ca5947218f968c2920a
31.018868
124
0.687684
false
false
false
false
ksco/swift-algorithm-club-cn
refs/heads/master
Two-Sum Problem/Solution 1/2Sum.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play func twoSumProblem(a: [Int], k: Int) -> ((Int, Int))? { var map = [Int: Int]() for i in 0 ..< a.count { if let newK = map[a[i]] { return (newK, i) } else { map[k - a[i]] = i } } return nil } let a = [7, 100, 2, 21, 12, 10, 22, 14, 3, 4, 8, 4, 9] if let (i, j) = twoSumProblem(a, k: 33) { i // 3 a[i] // 21 j // 4 a[j] // 12 a[i] + a[j] // 33 } twoSumProblem(a, k: 37) // nil
ec8a9266df59c9316aec5c7b6ff4a9f8
19.68
55
0.435203
false
false
false
false
awind/Pixel
refs/heads/master
Pixel/UserInfoViewController.swift
apache-2.0
1
// // UserInfoViewController.swift // Pixel // // Created by SongFei on 15/12/14. // Copyright © 2015年 SongFei. All rights reserved. // import UIKit import PureLayout import Alamofire class UserInfoViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var coverImageView: UIImageView! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var numberOfPhotosLabel: UILabel! @IBOutlet weak var numberOfFriendsLabel: UILabel! @IBOutlet weak var numberOfFollowersLabel: UILabel! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var birthdayLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var domainLabel: UILabel! var isSelf = false var rightButton: UIBarButtonItem? var userId: Int? override func viewDidLoad() { super.viewDidLoad() self.title = "User" if isSelf { self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "ic_settings"), style: .Plain, target: self, action: #selector(settings)) } else { rightButton = UIBarButtonItem(title: "Follow", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(updateFollowStatus)) self.navigationItem.rightBarButtonItem = rightButton } self.navigationController?.navigationBar.barTintColor = UIColor(red: 46.0/255.0, green: 123.0/255.0, blue: 213.0/255.0, alpha: 1.0) self.navigationController?.navigationBar.barStyle = UIBarStyle.Black self.navigationController?.navigationBar.translucent = true self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() avatarImageView.layer.masksToBounds = true avatarImageView.layer.cornerRadius = (avatarImageView.frame.size.height) / 2 avatarImageView.clipsToBounds = true scrollView.delegate = self if Account.checkIsLogin() && isSelf{ requestSelfInfo() } else if self.userId != nil { requestUserInfo() } else { // not login, add avatar avatarImageView.image = UIImage(named: "user_placeholder") let userSingleTap = UITapGestureRecognizer(target: self, action: #selector(userAvatarTapped)) userSingleTap.numberOfTapsRequired = 1 avatarImageView.addGestureRecognizer(userSingleTap) usernameLabel.text = "点击头像登录" } } func requestSelfInfo() { Alamofire.request(Router.Users()) .responseSwiftyJSON { response in if let json = response.result.value { if let username = json["user"]["username"].string, avatar = json["user"]["userpic_https_url"].string,id = json["user"]["id"].int, photosCount = json["user"]["photos_count"].int, friendsCount = json["user"]["friends_count"].int, followersCount = json["user"]["followers_count"].int { self.userId = id let user = User(id: id, username: username, avatar: avatar) user.email = json["user"]["email"].string var city = "" var country = "" if let cityString = json["user"]["city"].string { city = cityString } if let countryString = json["user"]["country"].string { country = countryString } user.location = "\(city) \(country)" user.domain = json["user"]["domain"].string user.coverURL = json["user"]["cover_url"].string user.followersCount = followersCount user.friendsCount = friendsCount user.photosCount = photosCount self.updateUserInfo(user) } } } } func requestUserInfo() { Alamofire.request(Router.UsersShow(self.userId!)) .responseSwiftyJSON { response in if let json = response.result.value { if let username = json["user"]["username"].string, avatar = json["user"]["userpic_https_url"].string, id = json["user"]["id"].int, photosCount = json["user"]["photos_count"].int, friendsCount = json["user"]["friends_count"].int, followersCount = json["user"]["followers_count"].int { self.userId = id let user = User(id: id, username: username, avatar: avatar) user.email = json["user"]["email"].string var city = "" var country = "" if let cityString = json["user"]["city"].string { city = cityString } if let countryString = json["user"]["country"].string { country = countryString } user.location = "\(city) \(country)" user.domain = json["user"]["domain"].string user.coverURL = json["user"]["cover_url"].string user.followersCount = followersCount user.friendsCount = friendsCount user.photosCount = photosCount if !self.isSelf && Account.checkIsLogin() { user.following = json["user"]["following"].bool! } self.updateUserInfo(user) } } } } func updateUserInfo(user: User) { if let coverUrl = user.coverURL { self.coverImageView.sd_setImageWithURL(NSURL(string: coverUrl), placeholderImage: UIImage(named: "ic_user_header")) } self.avatarImageView.sd_setImageWithURL(NSURL(string: user.avatar), placeholderImage: UIImage(named: "user_placeholder")) self.usernameLabel.text = user.username self.numberOfFollowersLabel.text = "\(user.followersCount!)" self.numberOfPhotosLabel.text = "\(user.photosCount!)" self.numberOfFriendsLabel.text = "\(user.friendsCount!)" if let email = user.email { self.birthdayLabel.text = email } if let location = user.location { self.locationLabel.text = location } if let domain = user.domain { self.domainLabel.text = domain } if !isSelf { if user.following { self.rightButton?.title = "Following" } else { self.rightButton?.title = "Follow" } } } func updateFollowStatus() { if !Account.checkIsLogin() { let alert = UIAlertController(title: nil, message: "未登录无法赞这张照片,现在去登录吗?", preferredStyle: UIAlertControllerStyle.Alert) let alertConfirm = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default) { alertConfirm in self.presentViewController(UINavigationController(rootViewController: AuthViewController()), animated: true, completion: nil) } let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel) { (cancle) -> Void in } alert.addAction(alertConfirm) alert.addAction(cancel) self.presentViewController(alert, animated: true, completion: nil) return } if self.rightButton?.title == "Follow" { Alamofire.request(Router.FollowUser(self.userId!)) .responseSwiftyJSON { response in self.rightButton?.title = "Following" } } else { Alamofire.request(Router.UnFollowUser(self.userId!)) .responseSwiftyJSON { response in self.rightButton?.title = "Follow" } } } // MARK: UIBarButtonItem func settings() { let settingsVC = UINavigationController(rootViewController: SettingViewController()) self.presentViewController(settingsVC, animated: true, completion: nil) } @IBAction func photoButtonTapped(sender: UIButton) { if let id = self.userId { let galleryVC = ImageCollectionViewController() galleryVC.requestType = 4 galleryVC.userId = id galleryVC.title = "Photos" galleryVC.parentNavigationController = self.navigationController self.navigationController?.pushViewController(galleryVC, animated: true) } } @IBAction func friendButtonTapped(sender: UIButton) { if let id = self.userId { let friendVC = FriendsViewController() friendVC.userId = id self.navigationController?.pushViewController(friendVC, animated: true) } } @IBAction func followerButtonTapped(sender: UIButton) { if let id = self.userId { let friendVC = FriendsViewController() friendVC.userId = id friendVC.requestType = 1 self.navigationController?.pushViewController(friendVC, animated: true) } } func userAvatarTapped() { let signInVC = AuthViewController() self.presentViewController(UINavigationController(rootViewController: signInVC), animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
649ac27eb550702c3ab338fdf3aea9e4
40.308333
303
0.567985
false
false
false
false
LKY769215561/KYHandMade
refs/heads/master
KYHandMade/Pods/DynamicColor/Sources/DynamicColor+RGBA.swift
apache-2.0
2
/* * DynamicColor * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #if os(iOS) || os(tvOS) || os(watchOS) import UIKit #elseif os(OSX) import AppKit #endif // MARK: RGBA Color Space public extension DynamicColor { /** Initializes and returns a color object using the specified opacity and RGB component values. Notes that values out of range are clipped. - Parameter r: The red component of the color object, specified as a value from 0.0 to 255.0. - Parameter g: The green component of the color object, specified as a value from 0.0 to 255.0. - Parameter b: The blue component of the color object, specified as a value from 0.0 to 255.0. - Parameter a: The opacity value of the color object, specified as a value from 0.0 to 255.0. The default value is 255. */ public convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 255) { self.init(red: clip(r, 0, 255) / 255, green: clip(g, 0, 255) / 255, blue: clip(b, 0, 255) / 255, alpha: clip(a, 0, 255) / 255) } // MARK: - Getting the RGBA Components /** Returns the RGBA (red, green, blue, alpha) components. - returns: The RGBA components as a tuple (r, g, b, a). */ public final func toRGBAComponents() -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 #if os(iOS) || os(tvOS) || os(watchOS) getRed(&r, green: &g, blue: &b, alpha: &a) return (r, g, b, a) #elseif os(OSX) if isEqual(DynamicColor.black) { return (0, 0, 0, 0) } else if isEqual(DynamicColor.white) { return (1, 1, 1, 1) } getRed(&r, green: &g, blue: &b, alpha: &a) return (r, g, b, a) #endif } #if os(iOS) || os(tvOS) || os(watchOS) /** The red component as CGFloat between 0.0 to 1.0. */ public final var redComponent: CGFloat { return toRGBAComponents().r } /** The green component as CGFloat between 0.0 to 1.0. */ public final var greenComponent: CGFloat { return toRGBAComponents().g } /** The blue component as CGFloat between 0.0 to 1.0. */ public final var blueComponent: CGFloat { return toRGBAComponents().b } /** The alpha component as CGFloat between 0.0 to 1.0. */ public final var alphaComponent: CGFloat { return toRGBAComponents().a } #endif // MARK: - Setting the RGBA Components /** Creates and returns a color object with the alpha increased by the given amount. - parameter amount: CGFloat between 0.0 and 1.0. - returns: A color object with its alpha channel modified. */ public final func adjustedAlpha(amount: CGFloat) -> DynamicColor { let components = toRGBAComponents() let normalizedAlpha = clip(components.a + amount, 0, 1) return DynamicColor(red: components.r, green: components.g, blue: components.b, alpha: normalizedAlpha) } }
0e1c3854a5155fda33715587110b3ead
31.967213
130
0.676778
false
false
false
false
cleexiang/CLRouter
refs/heads/master
CLRouter/ViewController3.swift
apache-2.0
1
// // ViewController3.swift // CLRouter // // Created by clee on 15/9/5. // Copyright © 2015年 cleexiang. All rights reserved. // import UIKit @objc(ViewController3) class ViewController3: UIViewController, CLRouteNodeProtocol { @IBOutlet weak var label1:UILabel? @IBOutlet weak var label2:UILabel? @IBOutlet weak var value1:UILabel? @IBOutlet weak var value2:UILabel? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.navigationItem.title = "VC3" self.value1?.text = param1 self.value2?.text = param2 } var param1:String? var param2:String? override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } static func customerController() -> UIViewController { let sb:UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let vc = sb.instantiateViewControllerWithIdentifier("ViewController3") return vc } }
729d1685aaf87e8c99e2055b8044e4fd
24.785714
87
0.67867
false
false
false
false
gguuss/gplus-ios-swift
refs/heads/master
basic-signin/swiftsignin/ViewController.swift
apache-2.0
1
// // ViewController.swift // swiftsignin // // Created by Gus Class on 12/12/14. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit class ViewController: UIViewController, GPPSignInDelegate { var kClientId = "REPLACE_CLIENT_ID"; // Get this from https://console.developers.google.com @IBOutlet weak var toggleFetchEmail: UISwitch! @IBOutlet weak var toggleFetchUserID: UISwitch! @IBOutlet weak var signinButton: UIButton! @IBOutlet weak var signOutButton: UIButton! @IBOutlet weak var disconnectButton: UIButton! @IBOutlet weak var emailDataField: UITextView! @IBOutlet weak var userData: UITextView! override func viewDidLoad() { super.viewDidLoad(); // Configure the sign in object. var signIn = GPPSignIn.sharedInstance(); signIn.shouldFetchGooglePlusUser = true; signIn.clientID = kClientId; signIn.shouldFetchGoogleUserEmail = toggleFetchEmail.on; signIn.shouldFetchGoogleUserID = toggleFetchUserID.on; signIn.scopes = [kGTLAuthScopePlusLogin]; signIn.trySilentAuthentication(); signIn.delegate = self; // Update the buttons and text. updateUI(); } @IBAction func signInClicked(sender: AnyObject) { var signIn = GPPSignIn.sharedInstance(); signIn.authenticate(); } func finishedWithAuth(auth: GTMOAuth2Authentication!, error: NSError!) { updateUI(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func toggleFetchEmailClick(sender: AnyObject) { GPPSignIn.sharedInstance().shouldFetchGoogleUserEmail = toggleFetchEmail.on; } @IBAction func toggleUserId(sender: AnyObject) { GPPSignIn.sharedInstance().shouldFetchGoogleUserID = toggleFetchUserID.on; } @IBAction func disconnect(sender: AnyObject) { GPPSignIn.sharedInstance().disconnect(); updateUI(); } @IBAction func signOut(sender: AnyObject) { GPPSignIn.sharedInstance().signOut(); updateUI(); } func updateUI() { // TODO: Toggle buttons here. if (GPPSignIn.sharedInstance().userID != nil){ // Signed in? var user = GPPSignIn.sharedInstance().googlePlusUser; userData.text = user.name.JSONString(); if (user.emails != nil){ emailDataField.text = user.emails.first?.JSONString() ?? "no email"; } else { emailDataField.text = "no email"; } signOutButton.enabled = true; disconnectButton.enabled = true; signinButton.enabled = true; } else { userData.text = "Signed out."; emailDataField.text = "Signed out."; signOutButton.enabled = false; disconnectButton.enabled = false; signinButton.enabled = true; } } }
089789594be640f27317d15b1b4ade82
28.534483
95
0.671337
false
false
false
false
blitzagency/events
refs/heads/master
Events/Models/Event.swift
mit
1
// // Event.swift // Events // // Created by Adam Venturella on 12/2/15. // Copyright © 2015 BLITZ. All rights reserved. // import Foundation public protocol Event{ var name: String { get } } public protocol PublisherAssociated{ associatedtype Publisher var publisher: Publisher { get } } public protocol DataAssociated{ associatedtype Data var data: Data { get } } public struct EventPublisher<Publisher>: Event, PublisherAssociated{ public let name: String public let publisher: Publisher public init(name: String, publisher: Publisher){ self.name = name self.publisher = publisher } } public struct EventPublisherData<Publisher, Data>: Event, PublisherAssociated, DataAssociated{ public let name: String public let publisher: Publisher public let data: Data public init(name: String, publisher: Publisher, data: Data){ self.name = name self.publisher = publisher self.data = data } }
d31055e20a88c8b2a9262f63303bf159
18.346154
94
0.680915
false
false
false
false
JaSpa/swift
refs/heads/master
test/Constraints/bridging.swift
apache-2.0
6
// RUN: %target-swift-frontend -typecheck -verify %s // REQUIRES: objc_interop import Foundation public class BridgedClass : NSObject, NSCopying { @objc(copyWithZone:) public func copy(with zone: NSZone?) -> Any { return self } } public class BridgedClassSub : BridgedClass { } // Attempt to bridge to a non-whitelisted type from another module. extension LazyFilterIterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'LazyFilterIterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}} public typealias _ObjectiveCType = BridgedClassSub public func _bridgeToObjectiveC() -> _ObjectiveCType { return BridgedClassSub() } public static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterIterator? ) { } public static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout LazyFilterIterator? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> LazyFilterIterator { let result: LazyFilterIterator? return result! } } struct BridgedStruct : Hashable, _ObjectiveCBridgeable { var hashValue: Int { return 0 } func _bridgeToObjectiveC() -> BridgedClass { return BridgedClass() } static func _forceBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct?) { } static func _conditionallyBridgeFromObjectiveC( _ x: BridgedClass, result: inout BridgedStruct? ) -> Bool { return true } static func _unconditionallyBridgeFromObjectiveC(_ source: BridgedClass?) -> BridgedStruct { var result: BridgedStruct? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } func ==(x: BridgedStruct, y: BridgedStruct) -> Bool { return true } struct NotBridgedStruct : Hashable { var hashValue: Int { return 0 } } func ==(x: NotBridgedStruct, y: NotBridgedStruct) -> Bool { return true } class OtherClass : Hashable { var hashValue: Int { return 0 } } func ==(x: OtherClass, y: OtherClass) -> Bool { return true } // Basic bridging func bridgeToObjC(_ s: BridgedStruct) -> BridgedClass { return s // expected-error{{cannot convert return expression of type 'BridgedStruct' to return type 'BridgedClass'}} return s as BridgedClass } func bridgeToAnyObject(_ s: BridgedStruct) -> AnyObject { return s // expected-error{{return expression of type 'BridgedStruct' does not conform to 'AnyObject'}} return s as AnyObject } func bridgeFromObjC(_ c: BridgedClass) -> BridgedStruct { return c // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return c as BridgedStruct } func bridgeFromObjCDerived(_ s: BridgedClassSub) -> BridgedStruct { return s // expected-error{{'BridgedClassSub' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}} return s as BridgedStruct } // Array -> NSArray func arrayToNSArray() { var nsa: NSArray nsa = [AnyObject]() // expected-error {{cannot assign value of type '[AnyObject]' to type 'NSArray'}} nsa = [BridgedClass]() // expected-error {{cannot assign value of type '[BridgedClass]' to type 'NSArray'}} nsa = [OtherClass]() // expected-error {{cannot assign value of type '[OtherClass]' to type 'NSArray'}} nsa = [BridgedStruct]() // expected-error {{cannot assign value of type '[BridgedStruct]' to type 'NSArray'}} nsa = [NotBridgedStruct]() // expected-error{{cannot assign value of type '[NotBridgedStruct]' to type 'NSArray'}} nsa = [AnyObject]() as NSArray nsa = [BridgedClass]() as NSArray nsa = [OtherClass]() as NSArray nsa = [BridgedStruct]() as NSArray nsa = [NotBridgedStruct]() as NSArray _ = nsa } // NSArray -> Array func nsArrayToArray(_ nsa: NSArray) { var arr1: [AnyObject] = nsa // expected-error{{'NSArray' is not implicitly convertible to '[AnyObject]'; did you mean to use 'as' to explicitly convert?}} {{30-30= as [AnyObject]}} var _: [BridgedClass] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} {{30-30= as! [BridgedClass]}} var _: [OtherClass] = nsa // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} {{28-28= as! [OtherClass]}} var _: [BridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} {{31-31= as! [BridgedStruct]}} var _: [NotBridgedStruct] = nsa // expected-error{{use 'as!' to force downcast}} var _: [AnyObject] = nsa as [AnyObject] var _: [BridgedClass] = nsa as [BridgedClass] // expected-error{{'NSArray' is not convertible to '[BridgedClass]'; did you mean to use 'as!' to force downcast?}} {{31-33=as!}} var _: [OtherClass] = nsa as [OtherClass] // expected-error{{'NSArray' is not convertible to '[OtherClass]'; did you mean to use 'as!' to force downcast?}} {{29-31=as!}} var _: [BridgedStruct] = nsa as [BridgedStruct] // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'; did you mean to use 'as!' to force downcast?}} {{32-34=as!}} var _: [NotBridgedStruct] = nsa as [NotBridgedStruct] // expected-error{{use 'as!' to force downcast}} var arr6: Array = nsa as Array arr6 = arr1 arr1 = arr6 } func dictionaryToNSDictionary() { // FIXME: These diagnostics are awful. var nsd: NSDictionary nsd = [NSObject : AnyObject]() // expected-error {{cannot assign value of type '[NSObject : AnyObject]' to type 'NSDictionary'}} nsd = [NSObject : AnyObject]() as NSDictionary nsd = [NSObject : BridgedClass]() // expected-error {{cannot assign value of type '[NSObject : BridgedClass]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass]() as NSDictionary nsd = [NSObject : OtherClass]() // expected-error {{cannot assign value of type '[NSObject : OtherClass]' to type 'NSDictionary'}} nsd = [NSObject : OtherClass]() as NSDictionary nsd = [NSObject : BridgedStruct]() // expected-error {{cannot assign value of type '[NSObject : BridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct]() as NSDictionary nsd = [NSObject : NotBridgedStruct]() // expected-error{{cannot assign value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary'}} nsd = [NSObject : NotBridgedStruct]() as NSDictionary nsd = [NSObject : BridgedClass?]() // expected-error{{cannot assign value of type '[NSObject : BridgedClass?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedClass?]() as NSDictionary nsd = [NSObject : BridgedStruct?]() // expected-error{{cannot assign value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary'}} nsd = [NSObject : BridgedStruct?]() as NSDictionary nsd = [BridgedClass : AnyObject]() // expected-error {{cannot assign value of type '[BridgedClass : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedClass : AnyObject]() as NSDictionary nsd = [OtherClass : AnyObject]() // expected-error {{cannot assign value of type '[OtherClass : AnyObject]' to type 'NSDictionary'}} nsd = [OtherClass : AnyObject]() as NSDictionary nsd = [BridgedStruct : AnyObject]() // expected-error {{cannot assign value of type '[BridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [BridgedStruct : AnyObject]() as NSDictionary nsd = [NotBridgedStruct : AnyObject]() // expected-error{{cannot assign value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary'}} nsd = [NotBridgedStruct : AnyObject]() as NSDictionary // <rdar://problem/17134986> var bcOpt: BridgedClass? nsd = [BridgedStruct() : bcOpt as Any] bcOpt = nil _ = nsd } // In this case, we should not implicitly convert Dictionary to NSDictionary. struct NotEquatable {} func notEquatableError(_ d: Dictionary<Int, NotEquatable>) -> Bool { // FIXME: Another awful diagnostic. return d == d // expected-error{{binary operator '==' cannot be applied to two 'Dictionary<Int, NotEquatable>' operands}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }} } // NSString -> String var nss1 = "Some great text" as NSString var nss2: NSString = ((nss1 as String) + ", Some more text") as NSString // <rdar://problem/17943223> var inferDouble = 1.0/10 let d: Double = 3.14159 inferDouble = d // rdar://problem/17962491 var inferDouble2 = 1 % 3 / 3.0 // expected-error{{'%' is unavailable: Use truncatingRemainder instead}} let d2: Double = 3.14159 inferDouble2 = d2 // rdar://problem/18269449 var i1: Int = 1.5 * 3.5 // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}} // rdar://problem/18330319 func rdar18330319(_ s: String, d: [String : AnyObject]) { _ = d[s] as! String? } // rdar://problem/19551164 func rdar19551164a(_ s: String, _ a: [String]) {} func rdar19551164b(_ s: NSString, _ a: NSArray) { rdar19551164a(s, a) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{18-18= as String}} // expected-error@-1{{'NSArray' is not convertible to '[String]'; did you mean to use 'as!' to force downcast?}}{{21-21= as! [String]}} } // rdar://problem/19695671 func takesSet<T: Hashable>(_ p: Set<T>) {} // expected-note {{in call to function 'takesSet'}} func takesDictionary<K: Hashable, V>(_ p: Dictionary<K, V>) {} // expected-note {{in call to function 'takesDictionary'}} func takesArray<T>(_ t: Array<T>) {} // expected-note {{in call to function 'takesArray'}} func rdar19695671() { takesSet(NSSet() as! Set) // expected-error{{generic parameter 'T' could not be inferred}} takesDictionary(NSDictionary() as! Dictionary) // expected-error{{generic parameter 'K' could not be inferred}} takesArray(NSArray() as! Array) // expected-error{{generic parameter 'T' could not be inferred}} } // This failed at one point while fixing rdar://problem/19600325. func getArrayOfAnyObject(_: AnyObject) -> [AnyObject] { return [] } func testCallback(_ f: (AnyObject) -> AnyObject?) {} testCallback { return getArrayOfAnyObject($0) } // expected-error {{cannot convert value of type '[AnyObject]' to closure result type 'AnyObject?'}} // <rdar://problem/19724719> Type checker thinks "(optionalNSString ?? nonoptionalNSString) as String" is a forced cast func rdar19724719(_ f: (String) -> (), s1: NSString?, s2: NSString) { f((s1 ?? s2) as String) } // <rdar://problem/19770981> func rdar19770981(_ s: String, ns: NSString) { func f(_ s: String) {} f(ns) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7= as String}} f(ns as String) // 'as' has higher precedence than '>' so no parens are necessary with the fixit: s > ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}} _ = s > ns as String ns > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}} _ = ns as String > s // 'as' has lower precedence than '+' so add parens with the fixit: s + ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7=(}}{{9-9= as String)}} _ = s + (ns as String) ns + s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{3-3=(}}{{5-5= as String)}} _ = (ns as String) + s } // <rdar://problem/19831919> Fixit offers as! conversions that are known to always fail func rdar19831919() { var s1 = 1 + "str"; // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note{{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} } // <rdar://problem/19831698> Incorrect 'as' fixits offered for invalid literal expressions func rdar19831698() { var v70 = true + 1 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}} var v71 = true + 1.0 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Double'}} // expected-note@-1{{overloads for '+'}} var v72 = true + true // expected-error{{binary operator '+' cannot be applied to two 'Bool' operands}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var v73 = true + [] // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and '[Any]'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var v75 = true + "str" // expected-error {{binary operator '+' cannot be applied to operands of type 'Bool' and 'String'}} expected-note {{expected an argument list of type '(String, String)'}} } // <rdar://problem/19836341> Incorrect fixit for NSString? to String? conversions func rdar19836341(_ ns: NSString?, vns: NSString?) { var vns = vns let _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} var _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} // FIXME: there should be a fixit appending "as String?" to the line; for now // it's sufficient that it doesn't suggest appending "as String" // Important part about below diagnostic is that from-type is described as // 'NSString?' and not '@lvalue NSString?': let _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} var _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}} vns = ns } // <rdar://problem/20029786> Swift compiler sometimes suggests changing "as!" to "as?!" func rdar20029786(_ ns: NSString?) { var s: String = ns ?? "str" as String as String // expected-error{{cannot convert value of type 'NSString?' to expected argument type 'String?'}} var s2 = ns ?? "str" as String as String // expected-error {{cannot convert value of type 'String' to expected argument type 'NSString'}} let s3: NSString? = "str" as String? // expected-error {{cannot convert value of type 'String?' to specified type 'NSString?'}} var s4: String = ns ?? "str" // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{20-20=(}}{{31-31=) as String}} var s5: String = (ns ?? "str") as String // fixed version } // <rdar://problem/19813772> QoI: Using as! instead of as in this case produces really bad diagnostic func rdar19813772(_ nsma: NSMutableArray) { var a1 = nsma as! Array // expected-error{{generic parameter 'Element' could not be inferred in cast to 'Array<_>'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<Any>}} var a2 = nsma as! Array<AnyObject> // expected-warning{{forced cast from 'NSMutableArray' to 'Array<AnyObject>' always succeeds; did you mean to use 'as'?}} {{17-20=as}} var a3 = nsma as Array<AnyObject> } func rdar28856049(_ nsma: NSMutableArray) { _ = nsma as? [BridgedClass] _ = nsma as? [BridgedStruct] _ = nsma as? [BridgedClassSub] } // <rdar://problem/20336036> QoI: Add cast-removing fixit for "Forced cast from 'T' to 'T' always succeeds" func force_cast_fixit(_ a : [NSString]) -> [NSString] { return a as! [NSString] // expected-warning {{forced cast of '[NSString]' to same type has no effect}} {{12-27=}} } // <rdar://problem/21244068> QoI: IUO prevents specific diagnostic + fixit about non-implicitly converted bridge types func rdar21244068(_ n: NSString!) -> String { return n // expected-error {{'NSString!' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}} {{11-11= as String}} } func forceBridgeDiag(_ obj: BridgedClass!) -> BridgedStruct { return obj // expected-error{{'BridgedClass!' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}{{13-13= as BridgedStruct}} } struct KnownUnbridged {} class KnownClass {} protocol KnownClassProtocol: class {} func forceUniversalBridgeToAnyObject<T, U: KnownClassProtocol>(a: T, b: U, c: Any, d: KnownUnbridged, e: KnownClass, f: KnownClassProtocol, g: AnyObject, h: String) { var z: AnyObject z = a as AnyObject z = b as AnyObject z = c as AnyObject z = d as AnyObject z = e as AnyObject z = f as AnyObject z = g as AnyObject z = h as AnyObject z = a // expected-error{{does not conform to 'AnyObject'}} z = b z = c // expected-error{{does not conform to 'AnyObject'}} z = d // expected-error{{does not conform to 'AnyObject'}} z = e z = f z = g z = h // expected-error{{does not conform to 'AnyObject'}} _ = z } func bridgeAnyContainerToAnyObject(x: [Any], y: [NSObject: Any]) { var z: AnyObject z = x as AnyObject z = y as AnyObject _ = z } func bridgeTupleToAnyObject() { let x = (1, "two") let y = x as AnyObject _ = y }
62d5ab80da682c54a7cff8d3ca3c5900
46.303279
305
0.694218
false
false
false
false
luzefeng/SwiftTask
refs/heads/swift/2.0
SwiftTaskTests/AlamofireTests.swift
mit
3
// // AlamofireTests.swift // SwiftTaskTests // // Created by Yasuhiro Inami on 2014/08/21. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // import SwiftTask import Alamofire import XCTest class AlamofireTests: _TestCase { typealias Progress = (bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) func testFulfill() { let expect = self.expectationWithDescription(__FUNCTION__) let task = Task<Progress, String, NSError> { progress, fulfill, reject, configure in request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .response { (request, response, data, error) in if let error = error { reject(error) return } fulfill("OK") } return } task.success { (value: String) -> Void in XCTAssertEqual(value, "OK") expect.fulfill() } self.wait() } func testReject() { let expect = self.expectationWithDescription(__FUNCTION__) let task = Task<Progress, String?, NSError> { progress, fulfill, reject, configure in let dummyURLString = "http://xxx-swift-task.org/get" request(.GET, dummyURLString, parameters: ["foo": "bar"]) .response { (request, response, data, error) in if let error = error { reject(error) // pass non-nil error return } if response?.statusCode >= 300 { reject(NSError(domain: "", code: 0, userInfo: nil)) } fulfill("OK") } } task.success { (value: String?) -> Void in XCTFail("Should never reach here.") }.failure { (error: NSError?, isCancelled: Bool) -> Void in XCTAssertTrue(error != nil, "Should receive non-nil error.") expect.fulfill() } self.wait() } func testProgress() { let expect = self.expectationWithDescription(__FUNCTION__) // define task let task = Task<Progress, String, NSError> { progress, fulfill, reject, configure in download(.GET, "http://httpbin.org/stream/100", destination: Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)) .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in progress((bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) as Progress) }.response { (request, response, data, error) in if let error = error { reject(error) return } fulfill("OK") // return nil anyway } return } // set progress & then task.progress { _, progress in print("bytesWritten = \(progress.bytesWritten)") print("totalBytesWritten = \(progress.totalBytesWritten)") print("totalBytesExpectedToWrite = \(progress.totalBytesExpectedToWrite)") print("") }.then { value, errorInfo -> Void in expect.fulfill() } self.wait() } func testNSProgress() { let expect = self.expectationWithDescription(__FUNCTION__) let nsProgress = NSProgress(totalUnitCount: 100) // define task let task = Task<Progress, String, NSError> { progress, fulfill, reject, configure in nsProgress.becomeCurrentWithPendingUnitCount(50) // NOTE: test with url which returns totalBytesExpectedToWrite != -1 download(.GET, "http://httpbin.org/bytes/1024", destination: Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)) .response { (request, response, data, error) in if let error = error { reject(error) return } fulfill("OK") // return nil anyway } nsProgress.resignCurrent() } task.then { value, errorInfo -> Void in XCTAssertTrue(nsProgress.completedUnitCount == 50) expect.fulfill() } self.wait() } // // NOTE: temporarily ignored Alamofire-cancelling test due to NSURLSessionDownloadTaskResumeData issue. // // Error log: // Property list invalid for format: 100 (property lists cannot contain NULL) // Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: object cannot be nil (key: NSURLSessionDownloadTaskResumeData)' // // Ref: // nsurlsession - (NSURLSessionDownloadTask cancelByProducingResumeData) crashes nsnetwork daemon iOS 7.0 - Stack Overflow // http://stackoverflow.com/questions/25297750/nsurlsessiondownloadtask-cancelbyproducingresumedata-crashes-nsnetwork-daemon // func testCancel() { let expect = self.expectationWithDescription(__FUNCTION__) let task = Task<Progress, String?, NSError> { progress, fulfill, reject, configure in let downloadRequst = download(.GET, "http://httpbin.org/stream/100", destination: Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)) .response { (request, response, data, error) in if let error = error { reject(error) return } fulfill("OK") } // configure cancel for cleanup after reject or task.cancel() // NOTE: use weak to let task NOT CAPTURE downloadRequst via configure configure.cancel = { [weak downloadRequst] in if let downloadRequst = downloadRequst { downloadRequst.cancel() } } } // end of 1st task definition (NOTE: don't chain with `then` or `failure` for 1st task cancellation) task.success { (value: String?) -> Void in XCTFail("Should never reach here because task is cancelled.") }.failure { (error: NSError?, isCancelled: Bool) -> Void in XCTAssertTrue(error == nil, "Should receive nil error via task.cancel().") XCTAssertTrue(isCancelled) expect.fulfill() } // cancel after 1ms dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1_000_000), dispatch_get_main_queue()) { task.cancel() // sends no error XCTAssertEqual(task.state, TaskState.Cancelled) } self.wait() } // TODO: func __testPauseResume() { } }
0de4ecaaf764cdf3c5f26cd9eacee8cb
31.644068
187
0.511293
false
true
false
false
sodascourse/swift-introduction
refs/heads/master
Swift-Introduction.playground/Pages/Struct and Class.xcplaygroundpage/Contents.swift
apache-2.0
1
/*: # Struct and Class */ /*: ## Struct ### Point example */ struct Point { let x: Double let y: Double static let origin = Point(x: 0, y: 0) func distance(to another: Point) -> Double { let deltaX = self.x - another.x let deltaY = self.y - another.y return (deltaX*deltaX + deltaY*deltaY).squareRoot() } var distanceToOrigin: Double { return self.distance(to: Point.origin) } } let point1 = Point(x: 3, y: 4) let point2 = Point(x: 15, y: 9) let origin = Point.origin point1.distanceToOrigin point1.distance(to: point2) /*: ### Tour example */ struct Tour { var origin: String var destination: String } let tour1 = Tour(origin: "Taipei", destination: "Tokyo") //tour1.destination = "Osaka" // Try to uncomment above line to see what Xcode yields. var tour2 = Tour(origin: "Tokyo", destination: "San Francisco") tour2.destination = "Sapporo" /*: ### Back Account example */ struct BankAccount { var deposit: Int { willSet { print(">>> Deposit value will change from \(self.deposit) to \(newValue).") } didSet { print(">>> Deposit value did change from \(oldValue) to \(self.deposit).") } } } var account = BankAccount(deposit: 1000) account.deposit += 10 /*: ### Rectangle example */ struct Rect { struct Point { var x, y: Double } struct Size { var width, height: Double mutating func scale(by times: Double) { self.width *= times self.height *= times } } var origin: Point, size: Size var center: Point { get { return Point(x: self.origin.x + self.size.width/2, y: self.origin.y + self.size.height/2) } set(newCenter) { self.origin.x = newCenter.x - self.size.width/2 self.origin.y = newCenter.y - self.size.height/2 } } mutating func move(toX x: Double, y: Double) { self.origin.x = x self.origin.y = y } mutating func scaleSize(by times: Double) { self.size.scale(by: times) } } var rect = Rect(origin: Rect.Point(x: 5, y: 5), size: Rect.Size(width: 20, height: 40)) rect.origin rect.center rect.center = Rect.Point(x: 40, y: 40) rect.origin /*: ### Book example */ import Foundation struct Book { var title: String let author: String var price = 10.0 let publishDate = Date() init(title: String, author: String, price: Double) { self.title = title self.author = author self.price = price } init(title: String, author: String) { self.init(title: title, author: author, price: 10.0) } } let book1 = Book(title: "Harry Potter 1", author: "J.K. Rowling") let book2 = Book(title: "Harry Potter 2", author: "J.K. Rowling") book1.publishDate == book2.publishDate /*: ### Fraction and Complex example */ struct Fraction { var numerator: Int var denominator: Int init?(numerator: Int, denominator: Int) { guard denominator != 0 else { return nil } self.numerator = numerator self.denominator = denominator } init(_ integer: Int) { self.init(numerator: integer, denominator: 1)! } } let half = Fraction(numerator: 1, denominator: 2) let nilFraction = Fraction(numerator: 2, denominator: 0) struct Complex { var real: Double var imaginary: Double var isReal: Bool { return self.imaginary == 0 } } let someComplexNumber = Complex(real: 1, imaginary: 2) // 1+2i /*: ### Audio channel example */ struct AudioChannel { static let thresholdLevel = 10 // Use as constants static var maxLevelOfAllChannels = 0 // Use as shared variables var currentLevel: Int = 0 { didSet { if (self.currentLevel > AudioChannel.thresholdLevel) { self.currentLevel = AudioChannel.thresholdLevel } if (self.currentLevel > AudioChannel.maxLevelOfAllChannels) { AudioChannel.maxLevelOfAllChannels = self.currentLevel } } } } //: -------------------------------------------------------------------------------------------------------------------- /*: ## Class ### Animal example */ class Animal { var name: String? func makeNoise() {} init(name: String) { self.name = name } } class Cat: Animal { override func makeNoise() { print("meow~") } } class Dog: Animal { override func makeNoise() { print("wof!") } } let kitty = Cat(name: "Kitty") let puppy = Dog(name: "Puppy") print("\n\n---") kitty.makeNoise() // meow~ kitty.name // Kitty puppy.makeNoise() // wof! /*: ### View example */ struct Frame { var x, y, width, height: Double } class View { var frame: Frame init(frame: Frame) { self.frame = frame } func draw() { print("Start to draw a view at (x=\(self.frame.x), y=\(self.frame.y)).") print("The size of this view is \(self.frame.width)*\(self.frame.height).") } } class BorderedView: View { override func draw() { super.draw() print("Draw a stroke for this view.") } } print("\n\n---") let borderedView = BorderedView(frame: Frame(x: 10.0, y: 10.0, width: 200.0, height: 300.0)) borderedView.draw() /*: ### Student example */ class Person { var name: String init(name: String) { self.name = name } static func ==(lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name } } class Student: Person { var school: String var department: String? init(name: String, school: String, department: String?) { self.school = school self.department = department super.init(name: name) } convenience init(name: String, school: String) { self.init(name: name, school: school, department: nil) } } /*: ### Reference example */ let person1 = Person(name: "Peter") let person2 = person1 let person3 = Person(name: "Peter") person1 == person2 person1 == person3 person1 === person2 // Check identity: Memory block person1 === person3 // Check identity: Memory block person1.name = "Annie" person2.name // Also changed, because `person1` and `person2` are the same memory block. person3.name // Still "Peter". var fraction1 = Fraction(numerator: 1, denominator: 2)! var fraction2 = fraction1 fraction1.denominator = 3 fraction2.denominator // Still 2, because Fraction is a struct, value type. //: -------------------------------------------------------------------------------------------------------------------- //: # Advanced Example //: -------------------------------------------------------------------------------------------------------------------- class LinkedListNode<Element> { // LinkedList should be reference based ... use `class` // And in Swift, we ususally use `Element` as name for generic type of content // Optional is actually made by enum, `cmd+click` on `.none` to see it var nextNode: LinkedListNode? = .none var content: Element init(content: Element) { self.content = content } var isLastNode: Bool { return self.nextNode == nil } var lastNode: LinkedListNode { var lastNode = self while !lastNode.isLastNode { lastNode = lastNode.nextNode! } return lastNode } func toArray() -> [Element] { var result = [Element]() var node: LinkedListNode<Element>? = self repeat { result.append(node!.content) node = node!.nextNode } while node != nil return result } // Override operators static func +=(left: inout LinkedListNode, right: LinkedListNode) { left.lastNode.nextNode = right } // `subscript` is the method of `[]` operator subscript(steps: Int) -> LinkedListNode? { guard steps >= 0 else { print("Steps should equals to or be greater than 0") return nil } var resultNode: LinkedListNode? = self for _ in 0..<steps { resultNode = resultNode?.nextNode } return resultNode } subscript(indexes: Int...) -> [Element?] { var result = [Element?]() for index in indexes { result.append(self[index]?.content) } return result } // A static func is usually used as factory. static func createLinkedList(items: Element...) -> LinkedListNode<Element>? { guard !items.isEmpty else { return nil } let resultNode = LinkedListNode(content: items.first!) var lastNode = resultNode for item in items[1..<items.count] { lastNode.nextNode = LinkedListNode(content: item) lastNode = lastNode.nextNode! // Step forward } return resultNode } } var linkedList1 = LinkedListNode.createLinkedList(items: 1, 2, 3, 4)! linkedList1[0]?.content linkedList1[1]?.content linkedList1[2]?.content linkedList1[3]?.content linkedList1[4]?.content linkedList1[0]!.isLastNode linkedList1.lastNode.isLastNode linkedList1.lastNode.content linkedList1[0, 1, 5] linkedList1.toArray() let linkedList2 = LinkedListNode.createLinkedList(items: 5, 6, 7)! linkedList1 += linkedList2 linkedList1.toArray() //: --- //: //: [<- Previous](@previous) | [Next ->](@next) //:
e80f56ae8176c8407ed058622843b9d0
22.704261
120
0.582364
false
false
false
false
samodom/TestableUIKit
refs/heads/master
TestableUIKit/UIResponder/UIView/UITableView/UITableViewInsertSectionsSpy.swift
mit
1
// // UITableViewInsertSectionsSpy.swift // TestableUIKit // // Created by Sam Odom on 2/21/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import UIKit import TestSwagger import FoundationSwagger public extension UITableView { private static let insertSectionsCalledKeyString = UUIDKeyString() private static let insertSectionsCalledKey = ObjectAssociationKey(insertSectionsCalledKeyString) private static let insertSectionsCalledReference = SpyEvidenceReference(key: insertSectionsCalledKey) private static let insertSectionsSectionsKeyString = UUIDKeyString() private static let insertSectionsSectionsKey = ObjectAssociationKey(insertSectionsSectionsKeyString) private static let insertSectionsSectionsReference = SpyEvidenceReference(key: insertSectionsSectionsKey) private static let insertSectionsAnimationKeyString = UUIDKeyString() private static let insertSectionsAnimationKey = ObjectAssociationKey(insertSectionsAnimationKeyString) private static let insertSectionsAnimationReference = SpyEvidenceReference(key: insertSectionsAnimationKey) private static let insertSectionsCoselectors = SpyCoselectors( methodType: .instance, original: #selector(UITableView.insertSections(_:with:)), spy: #selector(UITableView.spy_insertSections(_:with:)) ) /// Spy controller for ensuring that a table view has had `insertSections(_:with:)` called on it. public enum InsertSectionsSpyController: SpyController { public static let rootSpyableClass: AnyClass = UITableView.self public static let vector = SpyVector.direct public static let coselectors: Set = [insertSectionsCoselectors] public static let evidence: Set = [ insertSectionsCalledReference, insertSectionsSectionsReference, insertSectionsAnimationReference ] public static let forwardsInvocations = true } /// Spy method that replaces the true implementation of `insertSections(_:with:)` dynamic public func spy_insertSections( _ sections: IndexSet, with animation: UITableViewRowAnimation ) { insertSectionsCalled = true insertSectionsSections = sections insertSectionsAnimation = animation spy_insertSections(sections, with: animation) } /// Indicates whether the `insertSections(_:with:)` method has been called on this object. public final var insertSectionsCalled: Bool { get { return loadEvidence(with: UITableView.insertSectionsCalledReference) as? Bool ?? false } set { saveEvidence(newValue, with: UITableView.insertSectionsCalledReference) } } /// Provides the sections passed to `insertSections(_:with:)` if called. public final var insertSectionsSections: IndexSet? { get { return loadEvidence(with: UITableView.insertSectionsSectionsReference) as? IndexSet } set { let reference = UITableView.insertSectionsSectionsReference guard let sections = newValue else { return removeEvidence(with: reference) } saveEvidence(sections, with: reference) } } /// Provides the animation type passed to `insertSections(_:with:)` if called. public final var insertSectionsAnimation: UITableViewRowAnimation? { get { return loadEvidence(with: UITableView.insertSectionsAnimationReference) as? UITableViewRowAnimation } set { let reference = UITableView.insertSectionsAnimationReference guard let animation = newValue else { return removeEvidence(with: reference) } saveEvidence(animation, with: reference) } } }
c582d20ba490027957e591d700083ca4
33.919643
111
0.694707
false
false
false
false
VladiMihaylenko/omim
refs/heads/master
iphone/Maps/Classes/CarPlay/Template Builders/SettingsTemplateBuilder.swift
apache-2.0
1
import CarPlay @available(iOS 12.0, *) final class SettingsTemplateBuilder { // MARK: - CPGridTemplate builder class func buildGridTemplate() -> CPGridTemplate { let actions = SettingsTemplateBuilder.buildGridButtons() let gridTemplate = CPGridTemplate(title: L("settings"), gridButtons: actions) return gridTemplate } private class func buildGridButtons() -> [CPGridButton] { let options = RoutingOptions() return [createUnpavedButton(options: options), createTollButton(options: options), createFerryButton(options: options), createTrafficButton(), createSpeedcamButton()] } // MARK: - CPGridButton builders private class func createTollButton(options: RoutingOptions) -> CPGridButton { var tollIconName = "ic_carplay_toll" if options.avoidToll { tollIconName += "_active" } let tollButton = CPGridButton(titleVariants: [L("avoid_tolls")], image: UIImage(named: tollIconName)!) { _ in options.avoidToll = !options.avoidToll options.save() CarPlayService.shared.updateRouteAfterChangingSettings() CarPlayService.shared.popTemplate(animated: true) } return tollButton } private class func createUnpavedButton(options: RoutingOptions) -> CPGridButton { var unpavedIconName = "ic_carplay_unpaved" if options.avoidDirty { unpavedIconName += "_active" } let unpavedButton = CPGridButton(titleVariants: [L("avoid_unpaved")], image: UIImage(named: unpavedIconName)!) { _ in options.avoidDirty = !options.avoidDirty options.save() CarPlayService.shared.updateRouteAfterChangingSettings() CarPlayService.shared.popTemplate(animated: true) } return unpavedButton } private class func createFerryButton(options: RoutingOptions) -> CPGridButton { var ferryIconName = "ic_carplay_ferry" if options.avoidFerry { ferryIconName += "_active" } let ferryButton = CPGridButton(titleVariants: [L("avoid_ferry")], image: UIImage(named: ferryIconName)!) { _ in options.avoidFerry = !options.avoidFerry options.save() CarPlayService.shared.updateRouteAfterChangingSettings() CarPlayService.shared.popTemplate(animated: true) } return ferryButton } private class func createTrafficButton() -> CPGridButton { var trafficIconName = "ic_carplay_trafficlight" let isTrafficEnabled = MWMTrafficManager.trafficEnabled() if isTrafficEnabled { trafficIconName += "_active" } let trafficButton = CPGridButton(titleVariants: [L("button_layer_traffic")], image: UIImage(named: trafficIconName)!) { _ in MWMTrafficManager.setTrafficEnabled(!isTrafficEnabled) CarPlayService.shared.popTemplate(animated: true) } return trafficButton } private class func createSpeedcamButton() -> CPGridButton { var speedcamIconName = "ic_carplay_speedcam" let isSpeedCamActivated = CarPlayService.shared.isSpeedCamActivated if isSpeedCamActivated { speedcamIconName += "_active" } let speedButton = CPGridButton(titleVariants: [L("speedcams_alert_title")], image: UIImage(named: speedcamIconName)!) { _ in CarPlayService.shared.isSpeedCamActivated = !isSpeedCamActivated CarPlayService.shared.popTemplate(animated: true) } return speedButton } }
9eb889bde80282fadba064c9be415515
45.860465
100
0.5933
false
false
false
false
niunaruto/DeDaoAppSwift
refs/heads/master
DeDaoSwift/DeDaoSwift/Home/View/DDHomeFreeAudioCell.swift
mit
1
// // DDHomeFreeAudioCell.swift // DeDaoSwift // // Created by niuting on 2017/3/13. // Copyright © 2017年 niuNaruto. All rights reserved. // import UIKit class DDHomeFreeAudioCell: DDBaseTableViewCell { override func setCellsViewModel(_ model: Any?) { if let modelT = model as? DDHomeFreeAudioModel { guard modelT.list?.count ?? 0 >= 4 && labelArray.count >= 4 else { return } if let list = modelT.list{ for i in 0...(list.count - 1) { let indef = "▶ " let cont = list[i].title labelArray[i].attributedText = DDTool.setLabelAttributedString(indef, cont, UIColor.init("#999999"), UIColor.init("#666666"), UIFont.systemFont(ofSize: 8), UIFont.systemFont(ofSize: 13)) } } } } let playBtnW : CGFloat = 100 lazy var playButton : UIButton = { let playButton = UIButton() playButton.setImage(UIImage.init(named: "new_main_audio_play_icon"), for: .normal) return playButton }() lazy var labelArray = Array<UILabel> () override func setUI() { contentView.addSubview(playButton) for i in 0...4 { let contentLable = UILabel() let height : CGFloat = 14 let starY : CGFloat = 18 contentLable.frame = CGRect(x: 10, y: starY + CGFloat(i) * height + CGFloat(10 * i), width: UIView.screenWidth - playBtnW , height: height) contentLable.font = UIFont.systemFont(ofSize: 13) contentLable.textColor = UIColor.init("#666666") contentView.addSubview(contentLable) labelArray.append(contentLable) } } override func setLayout() { playButton.snp.makeConstraints { (make) in make.centerY.equalToSuperview() make.right.equalToSuperview().offset(-20) make.bottom.equalToSuperview().offset(-30) } } }
f584d57a1ed0f5d8185b3e3f5976c3eb
26.463415
206
0.513321
false
false
false
false
cpuu/OTT
refs/heads/master
OTT/Utils/BeaconStore.swift
mit
1
// // BeaconStore.swift // BlueCap // // Created by Troy Stribling on 9/16/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import Foundation import BlueCapKit class BeaconStore { class func getBeacons() -> [String: NSUUID] { if let storedBeacons = NSUserDefaults.standardUserDefaults().dictionaryForKey("beacons") { var beacons = [String: NSUUID]() for (name, uuid) in storedBeacons { if let uuid = uuid as? String { beacons[name] = NSUUID(UUIDString: uuid) } } return beacons } else { return [:] } } class func setBeacons(beacons: [String: NSUUID]) { var storedBeacons = [String: String]() for (name, uuid) in beacons { storedBeacons[name] = uuid.UUIDString } NSUserDefaults.standardUserDefaults().setObject(storedBeacons, forKey: "beacons") } class func getBeaconNames() -> [String] { return Array(self.getBeacons().keys) } class func addBeacon(name: String, uuid: NSUUID) { var beacons = self.getBeacons() beacons[name] = uuid self.setBeacons(beacons) } class func removeBeacon(name: String) { var beacons = self.getBeacons() beacons.removeValueForKey(name) self.setBeacons(beacons) } }
3bbaa75393c2eaea8a7f0dff23e747ea
26.705882
98
0.57932
false
false
false
false