repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Antondomashnev/Sourcery
Pods/XcodeEdit/Sources/XCProjectFile.swift
1
5572
// // XCProjectFile.swift // XcodeEdit // // Created by Tom Lokhorst on 2015-08-12. // Copyright (c) 2015 nonstrict. All rights reserved. // import Foundation enum ProjectFileError : Error, CustomStringConvertible { case invalidData case notXcodeproj case missingPbxproj var description: String { switch self { case .invalidData: return "Data in .pbxproj file not in expected format" case .notXcodeproj: return "Path is not a .xcodeproj package" case .missingPbxproj: return "project.pbxproj file missing" } } } public class AllObjects { var dict: [String: PBXObject] = [:] var fullFilePaths: [String: Path] = [:] func object<T : PBXObject>(_ key: String) -> T { let obj = dict[key]! if let t = obj as? T { return t } return T(id: key, dict: obj.dict as AnyObject, allObjects: self) } } public class XCProjectFile { public let project: PBXProject let dict: JsonObject var format: PropertyListSerialization.PropertyListFormat let allObjects = AllObjects() public convenience init(xcodeprojURL: URL) throws { let pbxprojURL = xcodeprojURL.appendingPathComponent("project.pbxproj", isDirectory: false) let data = try Data(contentsOf: pbxprojURL) try self.init(propertyListData: data) } public convenience init(propertyListData data: Data) throws { let options = PropertyListSerialization.MutabilityOptions() var format: PropertyListSerialization.PropertyListFormat = PropertyListSerialization.PropertyListFormat.binary let obj = try PropertyListSerialization.propertyList(from: data, options: options, format: &format) guard let dict = obj as? JsonObject else { throw ProjectFileError.invalidData } self.init(dict: dict, format: format) } init(dict: JsonObject, format: PropertyListSerialization.PropertyListFormat) { self.dict = dict self.format = format let objects = dict["objects"] as! [String: JsonObject] for (key, obj) in objects { allObjects.dict[key] = XCProjectFile.createObject(key, dict: obj, allObjects: allObjects) } let rootObjectId = dict["rootObject"]! as! String let projDict = objects[rootObjectId]! self.project = PBXProject(id: rootObjectId, dict: projDict as AnyObject, allObjects: allObjects) self.allObjects.fullFilePaths = paths(self.project.mainGroup, prefix: "") } static func projectName(from url: URL) throws -> String { let subpaths = url.pathComponents guard let last = subpaths.last, let range = last.range(of: ".xcodeproj") else { throw ProjectFileError.notXcodeproj } return last.substring(to: range.lowerBound) } static func createObject(_ id: String, dict: JsonObject, allObjects: AllObjects) -> PBXObject { let isa = dict["isa"] as? String if let isa = isa, let type = types[isa] { return type.init(id: id, dict: dict as AnyObject, allObjects: allObjects) } // Fallback assertionFailure("Unknown PBXObject subclass isa=\(String(describing: isa))") return PBXObject(id: id, dict: dict as AnyObject, allObjects: allObjects) } func paths(_ current: PBXGroup, prefix: String) -> [String: Path] { var ps: [String: Path] = [:] for file in current.fileRefs { switch file.sourceTree { case .group: switch current.sourceTree { case .absolute: ps[file.id] = .absolute(prefix + "/" + file.path!) case .group: ps[file.id] = .relativeTo(.sourceRoot, prefix + "/" + file.path!) case .relativeTo(let sourceTreeFolder): ps[file.id] = .relativeTo(sourceTreeFolder, prefix + "/" + file.path!) } case .absolute: ps[file.id] = .absolute(file.path!) case let .relativeTo(sourceTreeFolder): ps[file.id] = .relativeTo(sourceTreeFolder, file.path!) } } for group in current.subGroups { if let path = group.path { let str: String switch group.sourceTree { case .absolute: str = path case .group: str = prefix + "/" + path case .relativeTo(.sourceRoot): str = path case .relativeTo(.buildProductsDir): str = path case .relativeTo(.developerDir): str = path case .relativeTo(.sdkRoot): str = path } ps += paths(group, prefix: str) } else { ps += paths(group, prefix: prefix) } } return ps } } let types: [String: PBXObject.Type] = [ "PBXProject": PBXProject.self, "PBXContainerItemProxy": PBXContainerItemProxy.self, "PBXBuildFile": PBXBuildFile.self, "PBXCopyFilesBuildPhase": PBXCopyFilesBuildPhase.self, "PBXFrameworksBuildPhase": PBXFrameworksBuildPhase.self, "PBXHeadersBuildPhase": PBXHeadersBuildPhase.self, "PBXResourcesBuildPhase": PBXResourcesBuildPhase.self, "PBXShellScriptBuildPhase": PBXShellScriptBuildPhase.self, "PBXSourcesBuildPhase": PBXSourcesBuildPhase.self, "PBXBuildStyle": PBXBuildStyle.self, "XCBuildConfiguration": XCBuildConfiguration.self, "PBXAggregateTarget": PBXAggregateTarget.self, "PBXNativeTarget": PBXNativeTarget.self, "PBXTargetDependency": PBXTargetDependency.self, "XCConfigurationList": XCConfigurationList.self, "PBXReference": PBXReference.self, "PBXReferenceProxy": PBXReferenceProxy.self, "PBXFileReference": PBXFileReference.self, "PBXGroup": PBXGroup.self, "PBXVariantGroup": PBXVariantGroup.self, "XCVersionGroup": XCVersionGroup.self ]
mit
DroidsOnRoids/SwiftCarousel
Source/SwiftCarouselDelegate.swift
1
3186
/* * Copyright (c) 2015 Droids on Roids LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @objc public protocol SwiftCarouselDelegate { /** Delegate method that fires up when item has been selected. If there was an animation, it fires up _after_ animation. Warning! Do not rely on item to get index from your data source. Index is passed as a variable in that function and you should use it instead. - parameter item: Item that is selected. You can style it as you want. - parameter index: Index of selected item that you can use with your data source. - parameter tapped: Indicate that the item has been tapped, true it means that it was tapped before the selection, and false that was scrolled. - returns: Return UIView that you customized (or not). */ @objc optional func didSelectItem(item: UIView, index: Int, tapped: Bool) -> UIView? /** Delegate method that fires up when item has been deselected. If there was an animation, it fires up _after_ animation. Warning! Do not rely on item to get index from your data source. Index is passed as a variable in that function and you should use it instead. - parameter item: Item that is deselected. You can style it as you want. - parameter index: Index of deselected item that you can use with your data source. - returns: Return UIView that you customized (or not). */ @objc optional func didDeselectItem(item: UIView, index: Int) -> UIView? /** Delegate method that fires up when Carousel has been scrolled. - parameter offset: New offset of the Carousel. */ @objc optional func didScroll(toOffset offset: CGPoint) /** Delegate method that fires up just before someone did dragging. - parameter offset: Current offset of the Carousel. */ @objc optional func willBeginDragging(withOffset offset: CGPoint) /** Delegate method that fires up right after someone did end dragging. - parameter offset: New offset of the Carousel. */ @objc optional func didEndDragging(withOffset offset: CGPoint) }
mit
AlexChekanov/Gestalt
Gestalt/UI/Views/Details/DetailViewControllerPresenter.swift
1
357
import Foundation protocol DetailViewControllerPresenter { var task: TaskDTO! { get } var title: String? { get } } class DetailViewControllerPresenterImpl: DetailViewControllerPresenter { var task: TaskDTO! var title: String? { return task.brief ?? "Title" } init(with task: TaskDTO) { self.task = task } }
apache-2.0
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILEReadLocalSupportedFeatures.swift
1
1965
// // HCILEReadLocalSupportedFeaturesReturn.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/15/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// LE Read Local Supported Features Command /// /// This command requests the list of the supported LE features for the Controller. func lowEnergyReadLocalSupportedFeatures(timeout: HCICommandTimeout = .default) async throws -> LowEnergyFeatureSet { let returValue = try await deviceRequest(HCILEReadLocalSupportedFeatures.self, timeout: timeout) return returValue.features } } // MARK: - Return parameter /// LE Read Local Supported Features Command /// /// This command requests the list of the supported LE features for the Controller. @frozen public struct HCILEReadLocalSupportedFeatures: HCICommandReturnParameter { public static let command = HCILowEnergyCommand.readLocalSupportedFeatures // 0x0003 public static let length = 8 public let features: LowEnergyFeatureSet public init?(data: Data) { guard data.count == type(of: self).length else { return nil } let featuresRawValue = UInt64(littleEndian: UInt64(bytes: (data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]))) self.features = LowEnergyFeatureSet(rawValue: featuresRawValue) } }
mit
parrotbait/CorkWeather
Pods/R.swift.Library/Library/UIKit/UITableView+ReuseIdentifierProtocol.swift
1
3331
// // UITableView+ReuseIdentifierProtocol.swift // R.swift Library // // Created by Mathijs Kadijk on 06-12-15. // From: https://github.com/mac-cain13/R.swift.Library // License: MIT License // import Foundation import UIKit public extension UITableView { /** Returns a typed reusable table-view cell object for the specified reuse identifier and adds it to the table. - parameter identifier: A R.reuseIdentifier.* value identifying the cell object to be reused. - parameter indexPath: The index path specifying the location of the cell. The data source receives this information when it is asked for the cell and should just pass it along. This method uses the index path to perform additional configuration based on the cell’s position in the table view. - returns: The UITableViewCell subclass with the associated reuse identifier or nil if it couldn't be casted correctly. - precondition: You must register a class or nib file using the registerNib: or registerClass:forCellReuseIdentifier: method before calling this method. */ func dequeueReusableCell<Identifier: ReuseIdentifierType>(withIdentifier identifier: Identifier, for indexPath: IndexPath) -> Identifier.ReusableType? where Identifier.ReusableType: UITableViewCell { return dequeueReusableCell(withIdentifier: identifier.identifier, for: indexPath) as? Identifier.ReusableType } @available(*, unavailable, message: "Use dequeueReusableCell(withIdentifier:for:) instead") func dequeueReusableCell<Identifier: ReuseIdentifierType>(withIdentifier identifier: Identifier) -> Identifier.ReusableType? where Identifier.ReusableType: UITableViewCell { fatalError() } /** Returns a typed reusable header or footer view located by its identifier. - parameter identifier: A R.reuseIdentifier.* value identifying the header or footer view to be reused. - returns: A UITableViewHeaderFooterView object with the associated identifier or nil if no such object exists in the reusable view queue or if it couldn't be cast correctly. */ func dequeueReusableHeaderFooterView<Identifier: ReuseIdentifierType>(withIdentifier identifier: Identifier) -> Identifier.ReusableType? where Identifier.ReusableType: UITableViewHeaderFooterView { return dequeueReusableHeaderFooterView(withIdentifier: identifier.identifier) as? Identifier.ReusableType } /** Register a R.nib.* containing a cell with the table view under it's contained identifier. - parameter nibResource: A nib resource (R.nib.*) containing a table view cell that has a reuse identifier */ func register<Resource: NibResourceType & ReuseIdentifierType>(_ nibResource: Resource) where Resource.ReusableType: UITableViewCell { register(UINib(resource: nibResource), forCellReuseIdentifier: nibResource.identifier) } /** Register a R.nib.* containing a header or footer with the table view under it's contained identifier. - parameter nibResource: A nib resource (R.nib.*) containing a view that has a reuse identifier */ func registerHeaderFooterView<Resource: NibResourceType>(_ nibResource: Resource) where Resource: ReuseIdentifierType, Resource.ReusableType: UIView { register(UINib(resource: nibResource), forHeaderFooterViewReuseIdentifier: nibResource.identifier) } }
mit
ECP-CANDLE/Supervisor
scratch/keras/py-krs.swift
1
225
import io; import python; import sys; printf("LLP: %s", getenv("LD_LIBRARY_PATH")); printf("PP: %s", getenv("PYTHONPATH")); app keras() { "python" "/lustre/atlas2/csc242/scratch/wozniak/mcs/ste/try-krs.py" ; } keras();
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/02743-swift-sourcemanager-getmessage.swift
11
217
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let h = 0 { { case c, ([Void{ } { class case c,
mit
yisimeng/YSMFactory-swift
YSMFactory-swift/BaseClass/ViewController/YSMNavigationController.swift
1
983
// // YSMNavigationController.swift // YSMFactory-swift // // Created by 忆思梦 on 2016/12/19. // Copyright © 2016年 忆思梦. All rights reserved. // import UIKit class YSMNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() guard let targets = interactivePopGestureRecognizer!.value(forKey: "_targets") as? [NSObject] else { return } let targetObjc = targets[0] let target = targetObjc.value(forKey: "target") let action = Selector(("handleNavigationTransition:")) let pan = UIPanGestureRecognizer(target: target, action: action) view.addGestureRecognizer(pan) } override func pushViewController(_ viewController: UIViewController, animated: Bool) { if viewControllers.count != 0 { viewController.hidesBottomBarWhenPushed = true } super.pushViewController(viewController, animated: animated) } }
mit
eurofurence/ef-app_ios
Packages/EurofurenceComponents/Tests/EventFeedbackComponentTests/Scene/EventFeedbackSceneTests.swift
1
759
import EventFeedbackComponent import XCTest import XCTEurofurenceModel class EventFeedbackSceneTests: XCTestCase { func testModuleFactoryUsesSceneFromStoryboard() { let presenterFactory = DummyEventFeedbackPresenterFactory() let sceneFactory = StoryboardEventFeedbackSceneFactory() let moduleFactory = EventFeedbackComponentFactoryImpl( presenterFactory: presenterFactory, sceneFactory: sceneFactory ) let module = moduleFactory.makeEventFeedbackModule( for: .random, delegate: CapturingEventFeedbackComponentDelegate() ) as? EventFeedbackViewController XCTAssertNotNil(module) XCTAssertNotNil(module?.storyboard) } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/11567-resolvetypedecl.swift
11
239
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class c<T where T : C func < { class A : c< { let start = d var d = c
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/09289-swift-sourcemanager-getmessage.swift
11
251
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing init { extension Array { deinit { ( { protocol A { class a { let a { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/09447-swift-modulefile-maybereadgenericparams.swift
11
284
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol b { { { } } protocol b { func a<d : a { } { { { } { { } { } { } } } { } { } } } func a: e typealias e = b
mit
hollance/swift-algorithm-club
Dijkstra Algorithm/VisualizedDijkstra.playground/Sources/GraphView.swift
4
10463
import UIKit public class GraphView: UIView { private var graph: Graph private var panningView: VertexView? = nil private var graphColors = GraphColors.sharedInstance public init(frame: CGRect, graph: Graph) { self.graph = graph super.init(frame: frame) backgroundColor = graphColors.graphBackgroundColor layer.cornerRadius = 15 } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func removeGraph() { for vertex in graph.vertices { if let view = vertex.view { view.removeFromSuperview() vertex.view = nil } } for vertex in graph.vertices { for edge in vertex.edges { if let edgeRepresentation = edge.edgeRepresentation { edgeRepresentation.layer.removeFromSuperlayer() edgeRepresentation.label.removeFromSuperview() edge.edgeRepresentation = nil } } } } public func createNewGraph() { setupVertexViews() setupEdgeRepresentations() addGraph() } public func reset() { for vertex in graph.vertices { vertex.edges.forEach { $0.edgeRepresentation?.setDefaultColor() } vertex.setDefaultColor() } } private func addGraph() { for vertex in graph.vertices { for edge in vertex.edges { if let edgeRepresentation = edge.edgeRepresentation { layer.addSublayer(edgeRepresentation.layer) addSubview(edgeRepresentation.label) } } } for vertex in graph.vertices { if let view = vertex.view { addSubview(view) } } } private func setupVertexViews() { var level = 0 var buildViewQueue = [graph.startVertex!] let itemWidth: CGFloat = 40 while !buildViewQueue.isEmpty { let levelItemsCount = CGFloat(buildViewQueue.count) let xStep = (frame.width - levelItemsCount * itemWidth) / (levelItemsCount + 1) var previousVertexMaxX: CGFloat = 0.0 for vertex in buildViewQueue { let x: CGFloat = previousVertexMaxX + xStep let y: CGFloat = CGFloat(level * 100) previousVertexMaxX = x + itemWidth let frame = CGRect(x: x, y: y, width: itemWidth, height: itemWidth) let vertexView = VertexView(frame: frame) vertex.view = vertexView vertexView.vertex = vertex vertex.view?.setIdLabel(text: vertex.identifier) vertex.view?.setPathLengthLabel(text: "\(vertex.pathLengthFromStart)") vertex.view?.addTarget(self, action: #selector(didTapVertex(sender:)), for: .touchUpInside) let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:))) vertex.view?.addGestureRecognizer(panGesture) } level += 1 buildViewQueue = graph.vertices.filter { $0.level == level } } } private var movingVertexInputEdges: [EdgeRepresentation] = [] private var movingVertexOutputEdges: [EdgeRepresentation] = [] @objc private func handlePan(recognizer: UIPanGestureRecognizer) { guard let vertexView = recognizer.view as? VertexView, let vertex = vertexView.vertex else { return } if panningView != nil { if panningView != vertexView { return } } switch recognizer.state { case .began: let movingVertexViewFrame = vertexView.frame let sizedVertexView = CGRect(x: movingVertexViewFrame.origin.x - 10, y: movingVertexViewFrame.origin.y - 10, width: movingVertexViewFrame.width + 20, height: movingVertexViewFrame.height + 20) vertex.edges.forEach { edge in if let edgeRepresentation = edge.edgeRepresentation{ if sizedVertexView.contains(edgeRepresentation.layer.startPoint!) { movingVertexOutputEdges.append(edgeRepresentation) } else { movingVertexInputEdges.append(edgeRepresentation) } } } panningView = vertexView case .changed: if movingVertexOutputEdges.isEmpty && movingVertexInputEdges.isEmpty { return } let translation = recognizer.translation(in: self) if vertexView.frame.origin.x + translation.x <= 0 || vertexView.frame.origin.y + translation.y <= 0 || (vertexView.frame.origin.x + vertexView.frame.width + translation.x) >= frame.width || (vertexView.frame.origin.y + vertexView.frame.height + translation.y) >= frame.height { break } movingVertexInputEdges.forEach { edgeRepresentation in let originalLabelCenter = edgeRepresentation.label.center edgeRepresentation.label.center = CGPoint(x: originalLabelCenter.x + translation.x * 0.625, y: originalLabelCenter.y + translation.y * 0.625) CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) let newPath = path(fromEdgeRepresentation: edgeRepresentation, movingVertex: vertex, translation: translation, outPath: false) edgeRepresentation.layer.path = newPath CATransaction.commit() } movingVertexOutputEdges.forEach { edgeRepresentation in let originalLabelCenter = edgeRepresentation.label.center edgeRepresentation.label.center = CGPoint(x: originalLabelCenter.x + translation.x * 0.375, y: originalLabelCenter.y + translation.y * 0.375) CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) let newPath = path(fromEdgeRepresentation: edgeRepresentation, movingVertex: vertex, translation: translation, outPath: true) edgeRepresentation.layer.path = newPath CATransaction.commit() } vertexView.center = CGPoint(x: vertexView.center.x + translation.x, y: vertexView.center.y + translation.y) recognizer.setTranslation(CGPoint.zero, in: self) case .ended: movingVertexInputEdges = [] movingVertexOutputEdges = [] panningView = nil default: break } } private func path(fromEdgeRepresentation edgeRepresentation: EdgeRepresentation, movingVertex: Vertex, translation: CGPoint, outPath: Bool) -> CGPath { let bezier = UIBezierPath() if outPath == true { bezier.move(to: edgeRepresentation.layer.endPoint!) let startPoint = CGPoint(x: edgeRepresentation.layer.startPoint!.x + translation.x, y: edgeRepresentation.layer.startPoint!.y + translation.y) edgeRepresentation.layer.startPoint = startPoint bezier.addLine(to: startPoint) } else { bezier.move(to: edgeRepresentation.layer.startPoint!) let endPoint = CGPoint(x: edgeRepresentation.layer.endPoint!.x + translation.x, y: edgeRepresentation.layer.endPoint!.y + translation.y) edgeRepresentation.layer.endPoint = endPoint bezier.addLine(to: endPoint) } return bezier.cgPath } @objc private func didTapVertex(sender: AnyObject) { DispatchQueue.main.async { if self.graph.state == .completed { for vertex in self.graph.vertices { vertex.edges.forEach { $0.edgeRepresentation?.setDefaultColor() } vertex.setVisitedColor() } if let vertexView = sender as? VertexView, let vertex = vertexView.vertex { for (index, pathVertex) in vertex.pathVerticesFromStart.enumerated() { pathVertex.setCheckingPathColor() if vertex.pathVerticesFromStart.count > index + 1 { let nextVertex = vertex.pathVerticesFromStart[index + 1] if let edge = pathVertex.edges.filter({ $0.neighbor == nextVertex }).first { edge.edgeRepresentation?.setCheckingColor() } } } } } else if self.graph.state == .interactiveVisualization { if let vertexView = sender as? VertexView, let vertex = vertexView.vertex { if vertex.visited { return } else { self.graph.didTapVertex(vertex: vertex) } } } } } private func setupEdgeRepresentations() { var edgeQueue: [Vertex] = [graph.startVertex!] //BFS while !edgeQueue.isEmpty { let currentVertex = edgeQueue.first! currentVertex.haveAllEdges = true for edge in currentVertex.edges { let neighbor = edge.neighbor let weight = edge.weight if !neighbor.haveAllEdges { let edgeRepresentation = EdgeRepresentation(from: currentVertex, to: neighbor, weight: weight) edge.edgeRepresentation = edgeRepresentation let index = neighbor.edges.index(where: { $0.neighbor == currentVertex })! neighbor.edges[index].edgeRepresentation = edgeRepresentation edgeQueue.append(neighbor) } } edgeQueue.removeFirst() } } }
mit
danielmartin/swift
validation-test/stdlib/StringSlicesConcurrentAppend.swift
2
3046
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: stress_test import StdlibUnittest import SwiftPrivateThreadExtras #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif var StringTestSuite = TestSuite("String") extension String { var capacity: Int { return _classify()._capacity } } // Swift.String used to hsve an optimization that allowed us to append to a // shared string buffer. However, as lock-free programming invariably does, it // introduced a race condition [rdar://25398370 Data Race in StringBuffer.append // (found by TSan)]. // // These tests verify that it works correctly when two threads try to append to // different non-shared strings that point to the same shared buffer. They used // to verify that the first append could succeed without reallocation even if // the string was held by another thread, but that has been removed. This could // still be an effective thread-safety test, though. enum ThreadID { case Primary case Secondary } var barrierVar: UnsafeMutablePointer<_stdlib_thread_barrier_t>? var sharedString: String = "" var secondaryString: String = "" func barrier() { var ret = _stdlib_thread_barrier_wait(barrierVar!) expectTrue(ret == 0 || ret == _stdlib_THREAD_BARRIER_SERIAL_THREAD) } func sliceConcurrentAppendThread(_ tid: ThreadID) { for i in 0..<100 { barrier() if tid == .Primary { // Get a fresh buffer. sharedString = "" sharedString.append("abc") sharedString.reserveCapacity(16) expectLE(16, sharedString.capacity) } barrier() // Get a private string. var privateString = sharedString barrier() // Append to the private string. if tid == .Primary { privateString.append("def") } else { privateString.append("ghi") } barrier() // Verify that contents look good. if tid == .Primary { expectEqual("abcdef", privateString) } else { expectEqual("abcghi", privateString) } expectEqual("abc", sharedString) // Verify that only one thread took ownership of the buffer. if tid == .Secondary { secondaryString = privateString } barrier() } } StringTestSuite.test("SliceConcurrentAppend") { barrierVar = UnsafeMutablePointer.allocate(capacity: 1) barrierVar!.initialize(to: _stdlib_thread_barrier_t()) var ret = _stdlib_thread_barrier_init(barrierVar!, 2) expectEqual(0, ret) let (createRet1, tid1) = _stdlib_thread_create_block( sliceConcurrentAppendThread, .Primary) let (createRet2, tid2) = _stdlib_thread_create_block( sliceConcurrentAppendThread, .Secondary) expectEqual(0, createRet1) expectEqual(0, createRet2) let (joinRet1, _) = _stdlib_thread_join(tid1!, Void.self) let (joinRet2, _) = _stdlib_thread_join(tid2!, Void.self) expectEqual(0, joinRet1) expectEqual(0, joinRet2) ret = _stdlib_thread_barrier_destroy(barrierVar!) expectEqual(0, ret) barrierVar!.deinitialize(count: 1) barrierVar!.deallocate() } runAllTests()
apache-2.0
mjhassan/Radio-Ga-Ga
SwiftRadio/Player.swift
1
398
// // Player.swift // Swift Radio // // Created by Matthew Fecher on 7/13/15. // Copyright (c) 2015 MatthewFecher.com. All rights reserved. // import MediaPlayer //***************************************************************** // This is a singleton struct using Swift //***************************************************************** struct Player { static var radio = AVPlayer() }
mit
caoimghgin/HexKit
Pod/Classes/Board.swift
1
5623
// // Board.swift // https://github.com/caoimghgin/HexKit // // Copyright © 2015 Kevin Muldoon. // // This code is distributed under the terms and conditions of the 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 UIKit class Board : UIView, UIGestureRecognizerDelegate { var artwork = Artwork() var arena = Arena() var grid = Grid() var transit = Transit() var sceneDelegate = HexKitSceneDelegate?() init() { super.init(frame: grid.frame) // addSubview(artwork) // addSubview(UIImageView(image: UIImage(imageLiteral: "Tobruk"))) // addSubview(grid) addSubview(arena) let panGesture = UIPanGestureRecognizer(target: self, action: "panGestureRecognizerAction:") panGesture.delegate = self self.addGestureRecognizer(panGesture) let tapGesture = UITapGestureRecognizer(target: self, action: "tapGestureRecognizerAction:") tapGesture.numberOfTapsRequired = 1 tapGesture.delegate = self self.addGestureRecognizer(tapGesture) } override func drawRect(rect: CGRect) { } func tapGestureRecognizerAction(gesture : UITapGestureRecognizer) { let tile = Touch.tile(gesture) self.sceneDelegate?.tileWasTapped(tile) if (tile.units.count > 0) { let unit = tile.units.first unit!.superview!.sendSubviewToBack(unit!) tile.sendUnitToBack(unit!) Move.prettyStack(tile) } } func panGestureRecognizerAction(gesture : UIPanGestureRecognizer) { switch gesture.state { case UIGestureRecognizerState.Possible: print("Possible") case UIGestureRecognizerState.Began: let tile = Touch.tile(gesture) if (tile.units.count > 0) { transit = Transit(tile: tile) transit.departure(tile) } self.layer.addSublayer(transit.line) case UIGestureRecognizerState.Changed: let state = transit.transit(Touch.tile(gesture)) switch state { case Transit.State.Allowed: print("allowed") case Transit.State.InsufficiantMovementPoints: gesture.enabled = false print("InsufficiantMovementPoints error") case Transit.State.MaximumMovementReached: gesture.enabled = false print("MaximumMovementReached error") case Transit.State.Unexpected: print("Transit.State.Unexpected") } case UIGestureRecognizerState.Ended: let tile = Touch.tile(gesture) transit.transit(tile) transit.end() _ = Move(transit: transit) case UIGestureRecognizerState.Cancelled: /* move unit back to originating hex and set gesture to enabled */ transit.arrival(transit.departing) gesture.enabled = true case UIGestureRecognizerState.Failed: print("failed") } } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { // return true; /* uncomment to disable UIScrollView scrolling **/ let tile = Touch.tile(touch) if (tile.units.count > 0) { let unit = tile.units.first if (unit?.alliance == HexKit.sharedInstance.turn) { return true } else { return false } } return false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false; } } class Artwork : UIImageView { } class Arena: UIView { }
mit
szehnder/emitter-kit
tests/NotificationListenerTests.swift
1
1027
import XCTest import EmitterKit class NotificationListenerTests: XCTestCase { var listener: Listener! var event: Notification! var calls = 0 override func setUp() { super.setUp() event = Notification("test") listener = nil calls = 0 } func testOnce () { listener = event.once { XCTAssertNotNil($0["test"], "NotificationListener failed to receive intact NSDictionary") self.calls += 1 } event.emit([ "test": true ]) event.emit([ "test": true ]) XCTAssertTrue(calls == 1, "Single-use NotificationListener did not stop listening after being executed") } func testOn () { listener = event.on { _ in self.calls += 1 } event.emit([:]) event.emit([:]) XCTAssertTrue(calls == 2, "NotificationListener listening after one execution") } func testOnDeinit () { event.on { _ in self.calls += 1 } event.emit([:]) XCTAssertTrue(calls == 0, "NotificationListener did not stop listening on deinit") } }
mit
EstefaniaGilVaquero/ciceIOS
App_Master_Detail_TableView/App_Master_Detail_TableView/AppDelegate.swift
1
2148
// // AppDelegate.swift // App_Master_Detail_TableView // // Created by cice on 15/6/16. // Copyright © 2016 cice. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
PoissonBallon/EasyRealm
EasyRealm/Classes/EasyRealmQueue.swift
1
411
// // EasyRealmCore.swift // Pods // // Created by Allan Vialatte on 17/02/2017. // // import Foundation import RealmSwift internal struct EasyRealmQueue { let realm:Realm let queue:DispatchQueue init?() { queue = DispatchQueue(label: UUID().uuidString) var tmp:Realm? = nil queue.sync { tmp = try? Realm() } guard let valid = tmp else { return nil } self.realm = valid } }
mit
PoissonBallon/EasyRealm
Example/Tests/TestSave.swift
1
1779
// // Test_Save.swift // EasyRealm // // Created by Allan Vialatte on 10/03/2017. // import XCTest import RealmSwift import EasyRealm class TestSave: XCTestCase { let testPokemon = ["Bulbasaur", "Ivysaur", "Venusaur","Charmander","Charmeleon","Charizard"] override func setUp() { super.setUp() Realm.Configuration.defaultConfiguration.inMemoryIdentifier = self.name } override func tearDown() { super.tearDown() let realm = try! Realm() try! realm.write { realm.deleteAll() } } func testSaveUnmanaged() { HelpPokemon.pokemons(with: self.testPokemon).forEach { try! $0.er.save(update: true) } HelpPokemon.pokemons(with: self.testPokemon).forEach { try! $0.er.save(update: true) } try! Pokeball.create().er.save() try! Pokeball.create().er.save() let numberOfPokemon = try! Pokemon.er.all() let numberOfPokeball = try! Pokeball.er.all() XCTAssertEqual(self.testPokemon.count, numberOfPokemon.count) XCTAssertEqual(2, numberOfPokeball.count) } func testSaveManaged() { HelpPokemon.pokemons(with: self.testPokemon).forEach { try! $0.er.save(update: true) } let managedPokemon = testPokemon.compactMap { try! Pokemon.er.fromRealm(with: $0) } managedPokemon.forEach { try! $0.er.save(update: true) } } func testMeasureSaveUnmanaged() { self.measure { try! Pokeball.create().er.save() } } func testMeasureSaveManaged() { let pokemon = HelpPokemon.pokemons(with: [self.testPokemon[0]]).first! try! pokemon.er.save(update: true) self.measure { try! pokemon.er.save(update: true) } } func testSaveLotOfComplexObject() { for _ in 0...10000 { try! HelpPokemon.generateCapturedRandomPokemon().er.save(update: true) } } }
mit
codestergit/swift
test/DebugInfo/autoclosure.swift
2
1030
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s // CHECK: define{{.*}}@_T011autoclosure7call_meys5Int64VF // CHECK-NOT: ret void // CHECK: call void @llvm.dbg.declare{{.*}}, !dbg // CHECK-NOT: ret void // CHECK: , !dbg ![[DBG:.*]] // CHECK: ret void func get_truth(_ input: Int64) -> Int64 { return input % 2 } // Since this is an autoclosure test, don't use &&, which is transparent. infix operator &&&&& : LogicalConjunctionPrecedence func &&&&&(lhs: Bool, rhs: @autoclosure () -> Bool) -> Bool { return lhs ? rhs() : false } func call_me(_ input: Int64) -> Void { // rdar://problem/14627460 // An autoclosure should have a line number in the debug info and a scope line of 0. // CHECK-DAG: !DISubprogram({{.*}}linkageName: "_T011autoclosure7call_meys5Int64VFSbyXKfu_",{{.*}} line: [[@LINE+3]],{{.*}} isLocal: true, isDefinition: true // But not in the line table. // CHECK-DAG: ![[DBG]] = !DILocation(line: [[@LINE+1]], if input != 0 &&&&& ( get_truth (input * 2 + 1) > 0 ) { } } call_me(5)
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/27226-swift-lexer-leximpl.swift
1
434
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck a){struct S{let s{class B<T:T.E}r}}
apache-2.0
cloudinary/cloudinary_ios
Cloudinary/Classes/Core/Features/ManagementApi/Results/CLDExplodeResult.swift
1
1948
// // CLDExplodeResult.swift // // Copyright (c) 2016 Cloudinary (http://cloudinary.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 @objcMembers open class CLDExplodeResult: CLDBaseResult { // MARK: - Getters open var status: String? { return getParam(.status) as? String } open var batchId: String? { return getParam(.batchId) as? String } // MARK: - Private Helpers fileprivate func getParam(_ param: ExplodeResultKey) -> AnyObject? { return resultJson[String(describing: param)] } fileprivate enum ExplodeResultKey: CustomStringConvertible { case status, batchId var description: String { switch self { case .status: return "status" case .batchId: return "batch_id" } } } }
mit
ypopovych/Boilerplate
Tests/BoilerplateTests/ContainerTests.swift
1
2861
// // ContainerTests.swift // Boilerplate // // Created by Daniel Leping on 3/5/16. // Copyright © 2016 Crossroad Labs, LTD. All rights reserved. // import XCTest import Foundation import Result @testable import Boilerplate enum MockError : Error { case Error1 case Error2 } class CantainerWithParticularError<V, E: Error> : ContainerWithErrorType { typealias Value = V typealias Error = E let error:Error init(_ content: V, error: E) { self.error = error } func withdrawResult() -> Result<V, Error> { return Result(error: error) } } class CantainerWithAnyError<V> : ContainerWithErrorType { typealias Value = V typealias Error = AnyError init(_ content: V) { } func withdrawResult() -> Result<V, Error> { return Result(error: MockError.Error1) } } class ContainerTests: XCTestCase { func testParticularError() { let container = CantainerWithParticularError("string", error: MockError.Error1) do { let _ = try container^! XCTFail("Must have thrown") } catch let e { switch e { case MockError.Error1: break default: XCTFail("Wrong error thrown") } } XCTAssertNil(container^) let _ = container^%.analysis(ifSuccess: { value -> Result<String, MockError> in XCTFail("Can not be with success") return Result<String, MockError>(value: value) }, ifFailure: { error in XCTAssertEqual(error, MockError.Error1) return Result<String, MockError>(error: error) }) } func testAnyError() { let container = CantainerWithAnyError("string") do { let _ = try container^! XCTFail("Must have thrown") } catch let e { switch e { case MockError.Error1: break default: XCTFail("Wrong error thrown") } } XCTAssertNil(container^) let _ = container^%.analysis(ifSuccess: { value -> Result<String, AnyError> in XCTFail("Can not be with success") return Result<String, AnyError>(value: value) }, ifFailure: { error in switch error.error { case MockError.Error1: break default: XCTFail("Wrong error thrown") } return Result<String, AnyError>(error: error) }) } } #if os(Linux) extension ContainerTests { static var allTests : [(String, (ContainerTests) -> () throws -> Void)] { return [ ("testParticularError", testParticularError), ("testAnyError", testAnyError), ] } } #endif
apache-2.0
bartshappee/ioscreator
IOS8SwiftShakeGesureTutorial/IOS8SwiftShakeGesureTutorialTests/IOS8SwiftShakeGesureTutorialTests.swift
40
970
// // IOS8SwiftShakeGesureTutorialTests.swift // IOS8SwiftShakeGesureTutorialTests // // Created by Arthur Knopper on 18/10/14. // Copyright (c) 2014 Arthur Knopper. All rights reserved. // import UIKit import XCTest class IOS8SwiftShakeGesureTutorialTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
debugsquad/nubecero
nubecero/Model/OnboardForm/MOnboardForm.swift
1
5041
import Foundation class MOnboardForm { enum Method { case Register case Signin } let items:[MOnboardFormItem] let title:String let buttonMessage:String let method:Method weak var itemEmail:MOnboardFormItemEmail! weak var itemPassword:MOnboardFormItemPassword! private let kEmailMinLength:Int = 4 private let kPasswordMinLength:Int = 6 class func Register() -> MOnboardForm { let method:Method = Method.Register let title:String = NSLocalizedString("MOnboardForm_titleRegister", comment:"") let buttonMessage:String = NSLocalizedString("MOnboardForm_buttonRegister", comment:"") let itemEmail:MOnboardFormItemEmailRegister = MOnboardFormItemEmailRegister() let itemPassword:MOnboardFormItemPasswordRegister = MOnboardFormItemPasswordRegister() let itemPassGenerator:MOnboardFormItemPassGenerator = MOnboardFormItemPassGenerator() let itemRemember:MOnboardFormItemRemember = MOnboardFormItemRemember() let items:[MOnboardFormItem] = [ itemEmail, itemPassword, itemPassGenerator, itemRemember ] let model:MOnboardForm = MOnboardForm( method:method, items:items, title:title, buttonMessage:buttonMessage, itemEmail:itemEmail, itemPassword:itemPassword) return model } class func Signin() -> MOnboardForm { let method:Method = Method.Signin let title:String = NSLocalizedString("MOnboardForm_titleSignin", comment:"") let buttonMessage:String = NSLocalizedString("MOnboardForm_buttonSignin", comment:"") let itemEmail:MOnboardFormItemEmailSignin = MOnboardFormItemEmailSignin() let itemPassword:MOnboardFormItemPasswordSignin = MOnboardFormItemPasswordSignin() let itemRemember:MOnboardFormItemRemember = MOnboardFormItemRemember() let itemForgot:MOnboardFormItemForgot = MOnboardFormItemForgot() let items:[MOnboardFormItem] = [ itemEmail, itemPassword, itemRemember, itemForgot ] let model:MOnboardForm = MOnboardForm( method:method, items:items, title:title, buttonMessage:buttonMessage, itemEmail:itemEmail, itemPassword:itemPassword) return model } private init(method:Method, items:[MOnboardFormItem], title:String, buttonMessage:String, itemEmail:MOnboardFormItemEmail, itemPassword:MOnboardFormItemPassword) { self.method = method self.items = items self.title = title self.buttonMessage = buttonMessage self.itemEmail = itemEmail self.itemPassword = itemPassword } init() { fatalError() } //MARK: public func createCredentials(completion:@escaping((MOnboardFormCredentials?, String?) -> ())) { let emailMinLength:Int = kEmailMinLength let passwordMinLength:Int = kPasswordMinLength DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in let credentials:MOnboardFormCredentials? let errorString:String? guard let email:String = self?.itemEmail.email else { credentials = nil errorString = NSLocalizedString("MOnboardForm_errorEmail", comment:"") completion(credentials, errorString) return } if email.characters.count < emailMinLength { credentials = nil errorString = NSLocalizedString("MOnboardForm_errorEmailShort", comment:"") completion(credentials, errorString) return } guard let password:String = self?.itemPassword.password else { credentials = nil errorString = NSLocalizedString("MOnboardForm_errorPassword", comment:"") completion(credentials, errorString) return } if password.characters.count < passwordMinLength { credentials = nil errorString = NSLocalizedString("MOnboardForm_errorPasswordShort", comment:"") completion(credentials, errorString) return } credentials = MOnboardFormCredentials( email:email, password:password) errorString = nil completion(credentials, errorString) } } }
mit
cnoon/swift-compiler-crashes
crashes-duplicates/02451-swift-sourcemanager-getmessage.swift
11
206
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing [ { struct A { func a { class case ,
mit
avito-tech/Marshroute
Marshroute/Sources/Transitions/TransitionAnimations/Modal/Dismissal/ModalDismissalAnimationContext.swift
1
1146
import UIKit /// Описание параметров анимаций обратного модального перехода c UIViewController'а public struct ModalDismissalAnimationContext { /// контроллер, на который нужно осуществить обратный модальный переход public let targetViewController: UIViewController /// контроллер, с которого нужно осуществить обратный модальный переход public let sourceViewController: UIViewController public init( targetViewController: UIViewController, sourceViewController: UIViewController) { self.targetViewController = targetViewController self.sourceViewController = sourceViewController } public init( modalDismissalAnimationLaunchingContext: ModalDismissalAnimationLaunchingContext) { self.targetViewController = modalDismissalAnimationLaunchingContext.targetViewController self.sourceViewController = modalDismissalAnimationLaunchingContext.sourceViewController } }
mit
avito-tech/Marshroute
Marshroute/Sources/Transitions/TransitionContexts/PresentationTransitionContext.swift
1
14575
import UIKit /// Описание перехода `вперед` на следующий модуль public struct PresentationTransitionContext { /// идентификатор перехода /// для точной отмены нужного перехода и возвращения на предыдущий экран через /// ```swift /// undoTransitionWith(transitionId:) public let transitionId: TransitionId /// контроллер, на который нужно перейти public let targetViewController: UIViewController /// обработчик переходов для модуля, на который нужно перейти /// (может отличаться от обработчика переходов, ответственного за выполнение текущего перехода) public private(set) var targetTransitionsHandlerBox: PresentationTransitionTargetTransitionsHandlerBox /// параметры перехода, на которые нужно держать сильную ссылку (например, обработчик переходов SplitViewController'а) public let storableParameters: TransitionStorableParameters? /// параметры запуска анимации прямого перехода public var presentationAnimationLaunchingContextBox: PresentationAnimationLaunchingContextBox } // MARK: - Init public extension PresentationTransitionContext { // MARK: - Push /// Контекст описывает последовательный переход внутри UINavigationController'а /// если UINavigationController'а не является самым верхним, то переход будет прокинут /// в самый верхний UINavigationController init(pushingViewController targetViewController: UIViewController, animator: NavigationTransitionsAnimator, transitionId: TransitionId) { self.transitionId = transitionId self.targetViewController = targetViewController self.targetTransitionsHandlerBox = .pendingAnimating self.storableParameters = nil let animationLaunchingContext = PushAnimationLaunchingContext( targetViewController: targetViewController, animator: animator ) self.presentationAnimationLaunchingContextBox = .push( launchingContext: animationLaunchingContext ) } // MARK: - Modal /// Контекст описывает переход на простой модальный контроллер init(presentingModalViewController targetViewController: UIViewController, targetTransitionsHandler: AnimatingTransitionsHandler, animator: ModalTransitionsAnimator, transitionId: TransitionId) { marshrouteAssert( !(targetViewController is UISplitViewController) && !(targetViewController is UITabBarController), "use presentingModalMasterDetailViewController:targetTransitionsHandler:animator:transitionId:" ) marshrouteAssert( !(targetViewController is UINavigationController), "use presentingModalNavigationController:targetTransitionsHandler:animator:transitionId:" ) self.transitionId = transitionId self.targetViewController = targetViewController self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler) self.storableParameters = NavigationTransitionStorableParameters( presentedTransitionsHandler: targetTransitionsHandler ) let animationLaunchingContext = ModalPresentationAnimationLaunchingContext( targetViewController: targetViewController, animator: animator ) self.presentationAnimationLaunchingContextBox = .modal( launchingContext: animationLaunchingContext ) } /// Контекст описывает переход на модальный контроллер, который нельзя! положить в UINavigationController: /// UISplitViewController init(presentingModalMasterDetailViewController targetViewController: UISplitViewController, targetTransitionsHandler: ContainingTransitionsHandler, animator: ModalMasterDetailTransitionsAnimator, transitionId: TransitionId) { self.transitionId = transitionId self.targetViewController = targetViewController self.targetTransitionsHandlerBox = .init(containingTransitionsHandler: targetTransitionsHandler) self.storableParameters = NavigationTransitionStorableParameters( presentedTransitionsHandler: targetTransitionsHandler ) let animationLaunchingContext = ModalMasterDetailPresentationAnimationLaunchingContext( targetViewController: targetViewController, animator: animator ) self.presentationAnimationLaunchingContextBox = .modalMasterDetail( launchingContext: animationLaunchingContext ) } /// Контекст описывает переход на модальный контроллер, который положен в UINavigationController init(presentingModalViewController targetViewController: UIViewController, inNavigationController navigationController: UINavigationController, targetTransitionsHandler: NavigationTransitionsHandlerImpl, animator: ModalNavigationTransitionsAnimator, transitionId: TransitionId) { marshrouteAssert( !(targetViewController is UISplitViewController) && !(targetViewController is UITabBarController), "use presentingModalMasterDetailViewController:targetTransitionsHandler:animator:transitionId:" ) self.transitionId = transitionId self.targetViewController = targetViewController self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler) self.storableParameters = NavigationTransitionStorableParameters( presentedTransitionsHandler: targetTransitionsHandler ) let animationLaunchingContext = ModalNavigationPresentationAnimationLaunchingContext( targetNavigationController: navigationController, targetViewController: targetViewController, animator: animator ) self.presentationAnimationLaunchingContextBox = .modalNavigation( launchingContext: animationLaunchingContext ) } /// Контекст описывает переход на конечный модальный UINavigationController /// использовать для MFMailComposeViewController, UIImagePickerController init(presentingModalEndpointNavigationController navigationController: UINavigationController, targetTransitionsHandler: NavigationTransitionsHandlerImpl, animator: ModalEndpointNavigationTransitionsAnimator, transitionId: TransitionId) { self.transitionId = transitionId self.targetViewController = navigationController self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler) self.storableParameters = NavigationTransitionStorableParameters( presentedTransitionsHandler: targetTransitionsHandler ) let animationLaunchingContext = ModalEndpointNavigationPresentationAnimationLaunchingContext( targetNavigationController: navigationController, animator: animator ) self.presentationAnimationLaunchingContextBox = .modalEndpointNavigation( launchingContext: animationLaunchingContext ) } // MARK: - Popover /// Контекст описывает вызов поповера, содержащего простой UIViewController init(presentingViewController targetViewController: UIViewController, inPopoverController popoverController: UIPopoverController, fromRect rect: CGRect, inView view: UIView, targetTransitionsHandler: AnimatingTransitionsHandler, animator: PopoverTransitionsAnimator, transitionId: TransitionId) { self.targetViewController = targetViewController self.transitionId = transitionId self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler) self.storableParameters = PopoverTransitionStorableParameters( popoverController: popoverController, presentedTransitionsHandler: targetTransitionsHandler ) let animationLaunchingContext = PopoverPresentationAnimationLaunchingContext( transitionStyle: .popoverFromView(sourceView: view, sourceRect: rect), targetViewController: targetViewController, popoverController: popoverController, animator: animator) self.presentationAnimationLaunchingContextBox = .popover( launchingContext: animationLaunchingContext ) } /// Контекст описывает вызов поповера, содержащего контроллер, который положен в UINavigationController init(presentingViewController targetViewController: UIViewController, inNavigationController navigationController: UINavigationController, inPopoverController popoverController: UIPopoverController, fromRect rect: CGRect, inView view: UIView, targetTransitionsHandler: NavigationTransitionsHandlerImpl, animator: PopoverNavigationTransitionsAnimator, transitionId: TransitionId) { self.targetViewController = targetViewController self.transitionId = transitionId self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler) self.storableParameters = PopoverTransitionStorableParameters( popoverController: popoverController, presentedTransitionsHandler: targetTransitionsHandler ) let animationLaunchingContext = PopoverNavigationPresentationAnimationLaunchingContext( transitionStyle: .popoverFromView(sourceView: view, sourceRect: rect), targetViewController: targetViewController, targetNavigationController: navigationController, popoverController: popoverController, animator: animator) self.presentationAnimationLaunchingContextBox = .popoverNavigation( launchingContext: animationLaunchingContext ) } /// Контекст описывает вызов поповера, содержащего простой UIViewController init(presentingViewController targetViewController: UIViewController, inPopoverController popoverController: UIPopoverController, fromBarButtonItem buttonItem: UIBarButtonItem, targetTransitionsHandler: AnimatingTransitionsHandler, animator: PopoverTransitionsAnimator, transitionId: TransitionId) { self.transitionId = transitionId self.targetViewController = targetViewController self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler) self.storableParameters = PopoverTransitionStorableParameters( popoverController: popoverController, presentedTransitionsHandler: targetTransitionsHandler ) let animationLaunchingContext = PopoverPresentationAnimationLaunchingContext( transitionStyle: .popoverFromBarButtonItem(buttonItem: buttonItem), targetViewController: targetViewController, popoverController: popoverController, animator: animator) self.presentationAnimationLaunchingContextBox = .popover( launchingContext: animationLaunchingContext ) } /// Контекст описывает вызов поповера, содержащего контроллер, который положен в UINavigationController init(presentingViewController targetViewController: UIViewController, inNavigationController navigationController: UINavigationController, inPopoverController popoverController: UIPopoverController, fromBarButtonItem buttonItem: UIBarButtonItem, targetTransitionsHandler: AnimatingTransitionsHandler, animator: PopoverNavigationTransitionsAnimator, transitionId: TransitionId) { self.transitionId = transitionId self.targetViewController = targetViewController self.targetTransitionsHandlerBox = .init(animatingTransitionsHandler: targetTransitionsHandler) self.storableParameters = PopoverTransitionStorableParameters( popoverController: popoverController, presentedTransitionsHandler: targetTransitionsHandler ) let animationLaunchingContext = PopoverNavigationPresentationAnimationLaunchingContext( transitionStyle: .popoverFromBarButtonItem(buttonItem: buttonItem), targetViewController: targetViewController, targetNavigationController: navigationController, popoverController: popoverController, animator: animator) self.presentationAnimationLaunchingContextBox = .popoverNavigation( launchingContext: animationLaunchingContext ) } } // MARK: - Convenience extension PresentationTransitionContext { var needsAnimatingTargetTransitionHandler: Bool { let result = self.targetTransitionsHandlerBox.needsAnimatingTargetTransitionHandler return result } /// Проставляем непроставленного ранее обработчика переходов mutating func setAnimatingTargetTransitionsHandler(_ transitionsHandler: AnimatingTransitionsHandler) { marshrouteAssert(needsAnimatingTargetTransitionHandler) targetTransitionsHandlerBox = .init(animatingTransitionsHandler: transitionsHandler) } }
mit
swimmath27/GameOfGames
GameOfGames/ViewControllers/DrawCardViewController.swift
1
4593
// // DrawCardViewController.swift // GameOfGames // // Created by Michael Lombardo on 5/31/16. // Copyright © 2016 Michael Lombardo. All rights reserved. // import UIKit class DrawCardViewController: UIViewController { @IBOutlet weak var playerIntroductionLabel: UILabel! @IBOutlet weak var youDrewLabel: UILabel! @IBOutlet weak var cardImageButton: UIButton! @IBOutlet weak var whichCardLabel: UILabel! @IBOutlet weak var skipButton: UIButton! @IBOutlet weak var wonButton: UIButton! @IBOutlet weak var lostButton: UIButton! @IBOutlet weak var stolenButton: UIButton! fileprivate var game:Game = Game.getInstance(); override func viewDidLoad() { super.viewDidLoad() playerIntroductionLabel.text = "\(game.getCurrentPlayerName())," self.loadCurrentCard(); //TODO: check if losable and hide the lose button as well //background gradient self.view.layer.insertSublayer(UIHelper.getBackgroundGradient(), at: 0) } func loadCurrentCard() { whichCardLabel.text = "\(game.getCurrentCard()!.shortDesc)!"; let cardPic: UIImage? = UIImage(named: game.getCurrentCard()!.getFileName()) if cardPic != nil { cardImageButton.setImage(cardPic, for: UIControlState()) cardImageButton.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,0) } else { cardImageButton.setTitle(game.getCurrentCard()!.toString(), for: UIControlState()) } if game.getCurrentCard()!.stealable { stolenButton.isEnabled = true stolenButton.alpha = 1.0; } else { stolenButton.isEnabled = false stolenButton.alpha = 0.5; } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cardInfoButtonPressed(_ sender: AnyObject) { CardInfoViewController.currentCard = game.getCurrentCard()!; CardInfoViewController.from = "DrawCard"; performSegue(withIdentifier: "DrawCardToCardInfo", sender: nil) } @IBAction func WonButtonPressed(_ sender: AnyObject) { // let drink:String = game.getCurrentCard()!.getDrink(); //alertAndGoBack("Congratz", s:"Please add \(drink) into the cup and send \(drink) to any player on the other team", whichAction: "won") self.goToNext("won"); } @IBAction func LostButtonPressed(_ sender: AnyObject) { // let drink:String = game.getCurrentCard()!.getDrink(); //alertAndGoBack("Too bad", s:"Please drink \(drink) and give \(drink) to a team member",whichAction: "lost") self.goToNext("lost"); } @IBAction func StolenButtonPressed(_ sender: AnyObject) { // let drink:String = game.getCurrentCard()!.getDrink(); //alertAndGoBack("...", s:"Please add \(drink) into the cup and the other team sends \(drink) to any player on your team", whichAction: "stolen") self.goToNext("stolen"); } @IBAction func skipCardButtonPressed(_ sender: AnyObject) { alertAndGoBack("Alert", s:"Card will be skipped. Make sure both team captains agree as this cannot be undone",whichAction: "skipped") } /* // 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. } */ func goToNext(_ whichAction:String) { switch whichAction { case "won": game.cardWasWon(); case "lost": game.cardWasLost(); case "stolen": game.cardWasStolen(); case "skipped": _ = game.drawCard(); self.loadCurrentCard(); return; // stay here if skipped default: break } self.performSegue( withIdentifier: "DrawCardToPlayGame", sender: self) } func alertAndGoBack(_ t:String, s : String, whichAction:String) { let popup = UIAlertController(title: t, message: s, preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title:"OK", style: .default, handler: { action in self.goToNext(whichAction) }) popup.addAction(okAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) popup.addAction(cancelAction); self.present(popup, animated: true, completion: nil) } }
mit
cdmx/MiniMancera
miniMancera/Model/Option/WhistlesVsZombies/Node/MOptionWhistlesVsZombiesHud.swift
1
1032
import Foundation class MOptionWhistlesVsZombiesHud:MGameUpdate<MOptionWhistlesVsZombies> { weak var model:MOptionWhistlesVsZombies! weak var view:VOptionWhistlesVsZombiesHud? private var lastElapsedTime:TimeInterval? private let kUpdateRate:TimeInterval = 0.3 override func update( elapsedTime:TimeInterval, scene:ViewGameScene<MOptionWhistlesVsZombies>) { if let lastElapsedTime:TimeInterval = self.lastElapsedTime { let deltaTime:TimeInterval = abs(elapsedTime - lastElapsedTime) if deltaTime > kUpdateRate { self.lastElapsedTime = elapsedTime updateView() } } else { lastElapsedTime = elapsedTime } } //MARK: private private func updateView() { let zombies:String = "\(model.score)" let coins:String = "\(model.coins)" view?.update(zombies:zombies, coins:coins) } }
mit
HongliYu/firefox-ios
SyncTests/RecordTests.swift
2
27164
/* 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 Shared import Account import Storage @testable import Sync import UIKit import XCTest import SwiftyJSON class RecordTests: XCTestCase { func testGUIDs() { let s = Bytes.generateGUID() print("Got GUID: \(s)", terminator: "\n") XCTAssertEqual(12, s.lengthOfBytes(using: .utf8)) } func testSwiftyJSONSerializingControlChars() { let input = "{\"foo\":\"help \\u000b this\"}" let json = JSON(parseJSON: input) XCTAssertNil(json.error) XCTAssertNil(json.null) XCTAssertEqual(input, json.stringify()) let pairs: [String: Any] = ["foo": "help \(Character(UnicodeScalar(11))) this"] let built = JSON(pairs) XCTAssertEqual(input, built.stringify()) } func testEnvelopeNullTTL() { let p = CleartextPayloadJSON(JSON(["id": "guid"])) let r = Record<CleartextPayloadJSON>(id: "guid", payload: p, modified: Date.now(), sortindex: 15, ttl: nil) let k = KeyBundle.random() let s = keysPayloadSerializer(keyBundle: k, { $0.json }) let json = s(r)! XCTAssertEqual(json["id"].stringValue, "guid") XCTAssertTrue(json["ttl"].isNull()) } func testParsedNulls() { // Make this a thorough test: use a real-ish blob of JSON. // Look to see whether fields with explicit null values match isNull(). let fullRecord = "{\"id\":\"global\"," + "\"payload\":" + "\"{\\\"syncID\\\":\\\"zPSQTm7WBVWB\\\"," + "\\\"declined\\\":[\\\"bookmarks\\\"]," + "\\\"storageVersion\\\":5," + "\\\"engines\\\":{" + "\\\"clients\\\":{\\\"version\\\":1,\\\"syncID\\\": null}," + "\\\"tabs\\\":null}}\"," + "\"username\":\"5817483\"," + "\"modified\":1.32046073744E9}" let record = EnvelopeJSON(fullRecord) let bodyJSON = JSON(parseJSON: record.payload) XCTAssertTrue(bodyJSON["engines"]["tabs"].isNull()) let clients = bodyJSON["engines"]["clients"] // Make sure we're really getting a value out. XCTAssertEqual(clients["version"].int, 1) // An explicit null in the input has .type == null, so our .isNull works. XCTAssertTrue(clients["syncID"].isNull()) // Oh, and it's a valid meta/global. let global = MetaGlobal.fromJSON(bodyJSON) XCTAssertTrue(global != nil) } func testEnvelopeJSON() { let e = EnvelopeJSON(JSON(parseJSON: "{}")) XCTAssertFalse(e.isValid()) let ee = EnvelopeJSON("{\"id\": \"foo\"}") XCTAssertFalse(ee.isValid()) XCTAssertEqual(ee.id, "foo") let eee = EnvelopeJSON(JSON(parseJSON: "{\"id\": \"foo\", \"collection\": \"bar\", \"payload\": \"baz\"}")) XCTAssertTrue(eee.isValid()) XCTAssertEqual(eee.id, "foo") XCTAssertEqual(eee.collection, "bar") XCTAssertEqual(eee.payload, "baz") } func testRecord() { // This is malformed JSON (no closing brace). let malformedPayload = "{\"id\": \"abcdefghijkl\", \"collection\": \"clients\", \"payload\": \"in" // Invalid: the payload isn't stringified JSON. let invalidPayload = "{\"id\": \"abcdefghijkl\", \"collection\": \"clients\", \"payload\": \"invalid\"}" // Invalid: the payload is missing a GUID. let emptyPayload = "{\"id\": \"abcdefghijkl\", \"collection\": \"clients\", \"payload\": \"{}\"}" // This one is invalid because the payload "id" isn't a string. // (It'll also fail implicitly because the guid doesn't match the envelope.) let badPayloadGUIDPayload: [String: Any] = ["id": 0] let badPayloadGUIDPayloadString = JSON(badPayloadGUIDPayload).stringify()! let badPayloadGUIDRecord: [String: Any] = ["id": "abcdefghijkl", "collection": "clients", "payload": badPayloadGUIDPayloadString] let badPayloadGUIDRecordString = JSON(badPayloadGUIDRecord).stringify()! // This one is invalid because the payload doesn't contain an "id" at all, but it's non-empty. // See also `emptyPayload` above. // (It'll also fail implicitly because the guid doesn't match the envelope.) let noPayloadGUIDPayload: [String: Any] = ["some": "thing"] let noPayloadGUIDPayloadString = JSON(noPayloadGUIDPayload).stringify()! let noPayloadGUIDRecord: [String: Any] = ["id": "abcdefghijkl", "collection": "clients", "payload": noPayloadGUIDPayloadString] let noPayloadGUIDRecordString = JSON(noPayloadGUIDRecord).stringify()! // And this is a valid record. let clientBody: [String: Any] = ["id": "abcdefghijkl", "name": "Foobar", "commands": [], "type": "mobile"] let clientBodyString = JSON(clientBody).stringify()! let clientRecord: [String: Any] = ["id": "abcdefghijkl", "collection": "clients", "payload": clientBodyString] let clientPayload = JSON(clientRecord).stringify()! let cleartextClientsFactory: (String) -> ClientPayload? = { (s: String) -> ClientPayload? in return ClientPayload(s) } let clearFactory: (String) -> CleartextPayloadJSON? = { (s: String) -> CleartextPayloadJSON? in return CleartextPayloadJSON(s) } print(clientPayload, terminator: "\n") // Non-JSON malformed payloads don't even yield a value. XCTAssertNil(Record<CleartextPayloadJSON>.fromEnvelope(EnvelopeJSON(malformedPayload), payloadFactory: clearFactory)) // Only payloads that parse as JSON objects are valid. XCTAssertNil(Record<CleartextPayloadJSON>.fromEnvelope(EnvelopeJSON(invalidPayload), payloadFactory: clearFactory)) // Missing ID. XCTAssertNil(Record<CleartextPayloadJSON>.fromEnvelope(EnvelopeJSON(emptyPayload), payloadFactory: clearFactory)) // No ID in non-empty payload. let noPayloadGUIDEnvelope = EnvelopeJSON(noPayloadGUIDRecordString) // The envelope is valid... XCTAssertTrue(noPayloadGUIDEnvelope.isValid()) // ... but the payload is not. let noID = Record<CleartextPayloadJSON>.fromEnvelope(noPayloadGUIDEnvelope, payloadFactory: cleartextClientsFactory) XCTAssertNil(noID) // Non-string ID in payload. let badPayloadGUIDEnvelope = EnvelopeJSON(badPayloadGUIDRecordString) // The envelope is valid... XCTAssertTrue(badPayloadGUIDEnvelope.isValid()) // ... but the payload is not. let badID = Record<CleartextPayloadJSON>.fromEnvelope(badPayloadGUIDEnvelope, payloadFactory: cleartextClientsFactory) XCTAssertNil(badID) // Only valid ClientPayloads are valid. XCTAssertNil(Record<ClientPayload>.fromEnvelope(EnvelopeJSON(invalidPayload), payloadFactory: cleartextClientsFactory)) XCTAssertTrue(Record<ClientPayload>.fromEnvelope(EnvelopeJSON(clientPayload), payloadFactory: cleartextClientsFactory)!.payload.isValid()) } func testEncryptedClientRecord() { let b64E = "0A7mU5SZ/tu7ZqwXW1og4qHVHN+zgEi4Xwfwjw+vEJw=" let b64H = "11GN34O9QWXkjR06g8t0gWE1sGgQeWL0qxxWwl8Dmxs=" let expectedGUID = "0-P9fabp9vJD" let expectedSortIndex = 131 let expectedLastModified: Timestamp = 1326254123650 let inputString = "{\"sortindex\": 131, \"payload\": \"{\\\"ciphertext\\\":\\\"YJB4dr0vZEIWPirfU2FCJvfzeSLiOP5QWasol2R6ILUxdHsJWuUuvTZVhxYQfTVNou6hVV67jfAvi5Cs+bqhhQsv7icZTiZhPTiTdVGt+uuMotxauVA5OryNGVEZgCCTvT3upzhDFdDbJzVd9O3/gU/b7r/CmAHykX8bTlthlbWeZ8oz6gwHJB5tPRU15nM/m/qW1vyKIw5pw/ZwtAy630AieRehGIGDk+33PWqsfyuT4EUFY9/Ly+8JlnqzxfiBCunIfuXGdLuqTjJOxgrK8mI4wccRFEdFEnmHvh5x7fjl1ID52qumFNQl8zkB75C8XK25alXqwvRR6/AQSP+BgQ==\\\",\\\"IV\\\":\\\"v/0BFgicqYQsd70T39rraA==\\\",\\\"hmac\\\":\\\"59605ed696f6e0e6e062a03510cff742bf6b50d695c042e8372a93f4c2d37dac\\\"}\", \"id\": \"0-P9fabp9vJD\", \"modified\": 1326254123.65}" let keyBundle = KeyBundle(encKeyB64: b64E, hmacKeyB64: b64H)! let decryptClient = keysPayloadFactory(keyBundle: keyBundle, { CleartextPayloadJSON($0) }) let encryptClient = keysPayloadSerializer(keyBundle: keyBundle, { $0.json }) // It's already a JSON. let toRecord = { return Record<CleartextPayloadJSON>.fromEnvelope($0, payloadFactory: decryptClient) } let envelope = EnvelopeJSON(inputString) if let r = toRecord(envelope) { XCTAssertEqual(r.id, expectedGUID) XCTAssertTrue(r.modified == expectedLastModified) //1326254123650 XCTAssertEqual(r.sortindex, expectedSortIndex) if let ee = encryptClient(r) { let envelopePrime = EnvelopeJSON(ee) XCTAssertEqual(envelopePrime.id, expectedGUID) XCTAssertEqual(envelopePrime.id, envelope.id) XCTAssertEqual(envelopePrime.sortindex, envelope.sortindex) XCTAssertTrue(envelopePrime.modified == 0) if let rPrime = toRecord(envelopePrime) { // The payloads should be identical. XCTAssertTrue(rPrime.equalPayloads(r)) } else { XCTFail("No record.") } } else { XCTFail("No record.") } } else { XCTFail("No record.") } // Test invalid Base64. let badInputString = "{\"sortindex\": 131, \"payload\": \"{\\\"ciphertext\\\":\\\"~~~YJB4dr0vZEIWPirfU2FCJvfzeSLiOP5QWasol2R6ILUxdHsJWuUuvTZVhxYQfTVNou6hVV67jfAvi5Cs+bqhhQsv7icZTiZhPTiTdVGt+uuMotxauVA5OryNGVEZgCCTvT3upzhDFdDbJzVd9O3/gU/b7r/CmAHykX8bTlthlbWeZ8oz6gwHJB5tPRU15nM/m/qW1vyKIw5pw/ZwtAy630AieRehGIGDk+33PWqsfyuT4EUFY9/Ly+8JlnqzxfiBCunIfuXGdLuqTjJOxgrK8mI4wccRFEdFEnmHvh5x7fjl1ID52qumFNQl8zkB75C8XK25alXqwvRR6/AQSP+BgQ==\\\",\\\"IV\\\":\\\"v/0BFgicqYQsd70T39rraA==\\\",\\\"hmac\\\":\\\"59605ed696f6e0e6e062a03510cff742bf6b50d695c042e8372a93f4c2d37dac\\\"}\", \"id\": \"0-P9fabp9vJD\", \"modified\": 1326254123.65}" let badEnvelope = EnvelopeJSON(badInputString) XCTAssertTrue(badEnvelope.isValid()) // It's a valid envelope containing nonsense ciphertext. XCTAssertNil(toRecord(badEnvelope)) // Even though the envelope is valid, the payload is invalid, so we can't construct a record. } func testMeta() { let fullRecord = "{\"id\":\"global\"," + "\"payload\":" + "\"{\\\"syncID\\\":\\\"zPSQTm7WBVWB\\\"," + "\\\"declined\\\":[\\\"bookmarks\\\"]," + "\\\"storageVersion\\\":5," + "\\\"engines\\\":{" + "\\\"clients\\\":{\\\"version\\\":1,\\\"syncID\\\":\\\"fDg0MS5bDtV7\\\"}," + "\\\"forms\\\":{\\\"version\\\":1,\\\"syncID\\\":\\\"GXF29AFprnvc\\\"}," + "\\\"history\\\":{\\\"version\\\":1,\\\"syncID\\\":\\\"av75g4vm-_rp\\\"}," + "\\\"passwords\\\":{\\\"version\\\":1,\\\"syncID\\\":\\\"LT_ACGpuKZ6a\\\"}," + "\\\"prefs\\\":{\\\"version\\\":2,\\\"syncID\\\":\\\"-3nsksP9wSAs\\\"}," + "\\\"tabs\\\":{\\\"version\\\":1,\\\"syncID\\\":\\\"W4H5lOMChkYA\\\"}}}\"," + "\"username\":\"5817483\"," + "\"modified\":1.32046073744E9}" let record = EnvelopeJSON(fullRecord) XCTAssertTrue(record.isValid()) let global = MetaGlobal.fromJSON(JSON(parseJSON: record.payload)) XCTAssertTrue(global != nil) if let global = global { XCTAssertEqual(["bookmarks"], global.declined) XCTAssertEqual(5, global.storageVersion) let modified = record.modified XCTAssertTrue(1320460737440 == modified) let forms = global.engines["forms"] let syncID = forms!.syncID XCTAssertEqual("GXF29AFprnvc", syncID) let payload: JSON = global.asPayload().json XCTAssertEqual("GXF29AFprnvc", payload["engines"]["forms"]["syncID"].stringValue) XCTAssertEqual(1, payload["engines"]["forms"]["version"].intValue) XCTAssertEqual("bookmarks", payload["declined"].arrayValue[0].stringValue) } } func testHistoryPayload() { let payloadJSON = "{\"id\":\"--DzSJTCw-zb\",\"histUri\":\"https://bugzilla.mozilla.org/show_bug.cgi?id=1154549\",\"title\":\"1154549 – Encapsulate synced profile data within an account-centric object\",\"visits\":[{\"date\":1429061233163240,\"type\":1}]}" let json = JSON(parseJSON: payloadJSON) if let payload = HistoryPayload.fromJSON(json) { XCTAssertEqual("--DzSJTCw-zb", payload["id"].stringValue) XCTAssertEqual("1154549 – Encapsulate synced profile data within an account-centric object", payload["title"].stringValue) XCTAssertEqual(1, payload.visits[0].type.rawValue) XCTAssertEqual(1429061233163240, payload.visits[0].date) let v = payload.visits[0] let j = v.toJSON() XCTAssertEqual(1, j["type"] as! Int) XCTAssertEqual(1429061233163240, j["date"] as! Int64) } else { XCTFail("Should have parsed.") } } func testHistoryPayloadWithNoURL() { let payloadJSON = "{\"id\":\"--DzSJTCw-zb\",\"histUri\":null,\"visits\":[{\"date\":1429061233163240,\"type\":1}]}" let json = JSON(parseJSON: payloadJSON) XCTAssertNil(HistoryPayload.fromJSON(json)) } func testHistoryPayloadWithNoTitle() { let payloadJSON = "{\"id\":\"--DzSJTCw-zb\",\"histUri\":\"https://foo.com/\",\"visits\":[{\"date\":1429061233163240,\"type\":1}]}" let json = JSON(parseJSON: payloadJSON) if let payload = HistoryPayload.fromJSON(json) { // Missing fields are null-valued in SwiftyJSON. XCTAssertTrue(payload["title"].isNull()) XCTAssertEqual("", payload.title) } else { XCTFail("Should have parsed.") } } func testHistoryPayloadWithNullTitle() { let payloadJSON = "{\"id\":\"--DzSJTCw-zb\",\"histUri\":\"https://foo.com/\",\"title\":null,\"visits\":[{\"date\":1429061233163240,\"type\":1}]}" let json = JSON(parseJSON: payloadJSON) if let payload = HistoryPayload.fromJSON(json) { XCTAssertEqual("", payload.title) } else { XCTFail("Should have parsed.") } } func testLoginPayload() { let input = JSON([ "id": "abcdefabcdef", "hostname": "http://foo.com/", "username": "foo", "password": "bar", "usernameField": "field", "passwordField": "bar", // No formSubmitURL. "httpRealm": "", ]) // fromJSON returns nil if not valid. XCTAssertNotNil(LoginPayload.fromJSON(input)) } func testSeparators() { // Mistyped parentid. let invalidSeparator = JSON(["type": "separator", "arentid": "toolbar", "parentName": "Bookmarks Toolbar", "pos": 3]) let sep = BookmarkType.payloadFromJSON(invalidSeparator) XCTAssertTrue(sep is SeparatorPayload) XCTAssertFalse(sep!.isValid()) // This one's right. let validSeparator = JSON(["id": "abcabcabcabc", "type": "separator", "parentid": "toolbar", "parentName": "Bookmarks Toolbar", "pos": 3]) let separator = BookmarkType.payloadFromJSON(validSeparator)! XCTAssertTrue(separator is SeparatorPayload) XCTAssertTrue(separator.isValid()) XCTAssertEqual(3, separator["pos"].intValue) } func testFolders() { let validFolder = JSON([ "id": "abcabcabcabc", "type": "folder", "parentid": "toolbar", "parentName": "Bookmarks Toolbar", "title": "Sóme stüff", "description": "", "children": ["foo", "bar"], ]) let folder = BookmarkType.payloadFromJSON(validFolder)! XCTAssertTrue(folder is FolderPayload) XCTAssertTrue(folder.isValid()) XCTAssertEqual((folder as! FolderPayload).children, ["foo", "bar"]) } // swiftlint:disable line_length func testMobileBookmarksFolder() { let children = ["M87np9Vfh_2s", "-JxRyqNte-ue", "6lIQzUtbjE8O", "eOg3jPSslzXl", "1WJIi9EjQErp", "z5uRo45Rvfbd", "EK3lcNd0sUFN", "gFD3GTljgu12", "eRZGsbN1ew9-", "widfEdgGn9de", "l7eTOR4Uf6xq", "vPbxG-gpN4Rb", "4dwJ8CototFe", "zK-kw9Ii6ScW", "eDmDU-gtEFW6", "lKjqWQaL_syt", "ETVDvWgGT31Q", "3Z_bMIHPSZQ8", "Fqu4_bJOk7fT", "Uo_5K1QrA67j", "gDTXNg4m1AJZ", "zpds8P-9xews", "87zjNtVGPtEp", "ZJru8Sn3qhW7", "txVnzBBBOgLP", "JTnRqFaj_oNa", "soaMlfmM4kjR", "g8AcVBjo6IRf", "uPUDaiG4q637", "rfq2bUud_w4d", "XBGxsiuUG2UD", "-VQRnJlyAvMs", "6wu7TScKdTU7", "ZeFji2hLVpLj", "HpCn_TVizMWX", "IPR5HZwRdlwi", "00JFOGuWnhWB", "P1jb3qKt32Vg", "D6MQJ43V1Ir5", "qWSoXFteRfsq", "o2avfYqEdomL", "xRS0U0YnjK9G", "VgOgzE_xfP4w", "SwP3rMJGvoO3", "Hf2jEgI_-PWa", "AyhmBi7Cv598", "-PaMuzTJXxVk", "JMhYrg8SlY5K", "SQeySEjzyplL", "GTAwd2UkEQEe", "x3RsZj5Ilebr", "sRZWZqPi74FP", "amHR50TpygA6", "XSk782ceVNN6", "ipiMyYQzeypI", "ph2k3Nqfhau4", "m5JKC3hAEQ0H", "yTVerkmQbNxk", "7taA6FbbbUbH", "PZvpbSRuJLPs", "C8atoa25U94F", "KOfNJk_ISLc6", "Bt74lBG9tJq6", "BuHoY2rUhuKA", "XTmoWKnwfIPl", "ZATwa3oTD1m0", "e8TczN5It6Am", "6kCUYs8hQtKg", "jDD8s5aiKoex", "QmpmcrYwLU29", "nCRcekynuJ08", "resttaI4J9tu", "EKSX3HV55VU3", "2-yCz0EIsVls", "sSeeGw3VbBY-", "qfpCrU34w9y0", "RKDgzPWecD6m", "5SgXEKu_dICW", "R143WAeB5E5r", "8Ns4-NiKG62r", "4AHuZDvop5XX", "YCP1OsO1goFF", "CYYaU1mQ_N6t", "UGkzEOMK8cuU", "1RzZOarkzQBa", "qSW2Z3cZSI9c", "ooPlKEAfQsnn", "jIUScoKLiXQt", "bjNTKugzRRL1", "hR24ZVnHUZcs", "3j2IDAZgUyYi", "xnWcy-sQDJRu", "UCcgJqGk3bTV", "WSSRWeptH9tq", "4ugv47OGD2E2", "XboCZgUx-x3x", "HrmWqiqsuLrm", "OjdxvRJ3Jb6j"] let json = JSON([ "id": "UjAHxFOGEqU8", "type": "folder", "parentName": "", "title": "mobile", "description": JSON.null, "children": children, "parentid": "places", ]) let bookmark = BookmarkType.payloadFromJSON(json) XCTAssertTrue(bookmark is FolderPayload) XCTAssertTrue(bookmark?.isValid() ?? false) } // swiftlint:enable line_length func testLivemarkMissingFields() { let json = JSON([ "id": "M5bwUKK8hPyF", "type": "livemark", "siteUri": "http://www.bbc.co.uk/go/rss/int/news/-/news/", "feedUri": "http://fxfeeds.mozilla.com/en-US/firefox/headlines.xml", "parentName": "Bookmarks Toolbar", "parentid": "toolbar", "children": ["3Qr13GucOtEh"]]) let bookmark = BookmarkType.payloadFromJSON(json) XCTAssertTrue(bookmark is LivemarkPayload) let livemark = bookmark as! LivemarkPayload XCTAssertTrue(livemark.isValid()) let siteURI = "http://www.bbc.co.uk/go/rss/int/news/-/news/" let feedURI = "http://fxfeeds.mozilla.com/en-US/firefox/headlines.xml" XCTAssertEqual(feedURI, livemark.feedURI) XCTAssertEqual(siteURI, livemark.siteURI) let m = (livemark as MirrorItemable).toMirrorItem(Date.now()) XCTAssertEqual("http://fxfeeds.mozilla.com/en-US/firefox/headlines.xml", m.feedURI) XCTAssertEqual("http://www.bbc.co.uk/go/rss/int/news/-/news/", m.siteURI) } func testDeletedRecord() { let json = JSON([ "id": "abcdefghijkl", "deleted": true, "type": "bookmark", ]) guard let payload = BookmarkType.payloadFromJSON(json) else { XCTFail() return } XCTAssertFalse(payload is BookmarkPayload) // Only BookmarkBasePayload. XCTAssertTrue(payload.isValid()) } func testUnknownRecordType() { // It'll return a base payload that's invalid because its type is unknown. let json = JSON([ "parentid": "mobile", "tags": [], "title": "Dispozitivul meu", "id": "pQSMHiA7fD0Z", "type": "something", "parentName": "mobile", ]) XCTAssertNil(BookmarkType.payloadFromJSON(json)) let payload = BookmarkType.somePayloadFromJSON(json) XCTAssertFalse(payload.isValid()) // Not valid because type is unknown. } func testInvalidRecordWithType() { // It should still return the right payload type, even if it's not valid. let json = JSON([ "parentid": "mobile", "bmkUri": JSON.null, "tags": [], "title": "Dispozitivul meu", "id": "pQSMHiA7fD0Z", "type": "bookmark", "parentName": "mobile", ]) guard let payload = BookmarkType.payloadFromJSON(json) else { XCTFail() return } XCTAssertFalse(payload.isValid()) XCTAssertTrue(payload is BookmarkPayload) } func testLivemark() { let json = JSON([ "id": "M5bwUKK8hPyF", "type": "livemark", "siteUri": "http://www.bbc.co.uk/go/rss/int/news/-/news/", "feedUri": "http://fxfeeds.mozilla.com/en-US/firefox/headlines.xml", "parentName": "Bookmarks Toolbar", "parentid": "toolbar", "title": "Latest Headlines", "description": "", "children": ["7oBdEZB-8BMO", "SUd1wktMNCTB", "eZe4QWzo1BcY", "YNBhGwhVnQsN", "92Aw2SMEkFg0", "uw0uKqrVFwd-", "x7mx2P3--8FJ", "d-jVF8UuC9Ye", "DV1XVtKLEiZ5", "g4mTaTjr837Z", "1Zi5W3lwBw8T", "FEYqlUHtbBWS", "qQd2u7LjosCB", "VUs2djqYfbvn", "KuhYnHocu7eg", "u2gcg9ILRg-3", "hfK_RP-EC7Ol", "Aq5qsa4E5msH", "6pZIbxuJTn-K", "k_fp0iN3yYMR", "59YD3iNOYO8O", "01afpSdAk2iz", "Cq-kjXDEPIoP", "HtNTjt9UwWWg", "IOU8QRSrTR--", "HJ5lSlBx6d1D", "j2dz5R5U6Khc", "5GvEjrNR0yJl", "67ozIBF5pNVP", "r5YB0cUx6C_w", "FtmFDBNxDQ6J", "BTACeZq9eEtw", "ll4ozQ-_VNJe", "HpImsA4_XuW7", "nJvCUQPLSXwA", "94LG-lh6TUYe", "WHn_QoOL94Os", "l-RvjgsZYlej", "LipQ8abcRstN", "74TiLvarE3n_", "8fCiLQpQGK1P", "Z6h4WkbwfQFa", "GgAzhqakoS6g", "qyt92T8vpMsK", "RyOgVCe2EAOE", "bgSEhW3w6kk5", "hWODjHKGD7Ph", "Cky673aqOHbT", "gZCYT7nx3Nwu", "iJzaJxxrM58L", "rUHCRv68aY5L", "6Jc1hNJiVrV9", "lmNgoayZ-ym8", "R1lyXsDzlfOd", "pinrXwDnRk6g", "Sn7TmZV01vMM", "qoXyU6tcS1dd", "TRLanED-QfBK", "xHbhMeX_FYEA", "aPqacdRlAtaW", "E3H04Wn2RfSi", "eaSIMI6kSrcz", "rtkRxFoG5Vqi", "dectkUglV0Dz", "B4vUE0BE15No", "qgQFW5AQrgB0", "SxAXvwOhu8Zi", "0S6cRPOg-5Z2", "zcZZBGeLnaWW", "B0at8hkQqVZQ", "sgPtgGulbP66", "lwtwGHSCPYaQ", "mNTdpgoRZMbW", "-L8Vci6CbkJY", "bVzudKSQERc1", "Gxl9lb4DXsmL", "3Qr13GucOtEh"]]) let bookmark = BookmarkType.payloadFromJSON(json) XCTAssertTrue(bookmark is LivemarkPayload) let livemark = bookmark as! LivemarkPayload XCTAssertTrue(livemark.isValid()) let siteURI = "http://www.bbc.co.uk/go/rss/int/news/-/news/" let feedURI = "http://fxfeeds.mozilla.com/en-US/firefox/headlines.xml" XCTAssertEqual(feedURI, livemark.feedURI) XCTAssertEqual(siteURI, livemark.siteURI) let m = (livemark as MirrorItemable).toMirrorItem(Date.now()) XCTAssertEqual("http://fxfeeds.mozilla.com/en-US/firefox/headlines.xml", m.feedURI) XCTAssertEqual("http://www.bbc.co.uk/go/rss/int/news/-/news/", m.siteURI) } func testMobileBookmark() { let json = JSON([ "id": "jIUScoKLiXQt", "type": "bookmark", "title": "Join the Engineering Leisure Class — Medium", "parentName": "mobile", "bmkUri": "https://medium.com/@chrisloer/join-the-engineering-leisure-class-b3083c09a78e", "tags": [], "keyword": JSON.null, "description": JSON.null, "loadInSidebar": false, "parentid": "mobile", ]) let bookmark = BookmarkType.payloadFromJSON(json) XCTAssertTrue(bookmark is BookmarkPayload) XCTAssertTrue(bookmark?.isValid() ?? false) } func testQuery() { let str = "{\"title\":\"Downloads\",\"parentName\":\"\",\"bmkUri\":\"place:transition=7&sort=4\",\"id\":\"7gdp9S1okhKf\",\"parentid\":\"rq6WHyfHkoUV\",\"type\":\"query\"}" let query = BookmarkType.payloadFromJSON(JSON(parseJSON: str)) XCTAssertTrue(query is BookmarkQueryPayload) let mirror = query?.toMirrorItem(Date.now()) let roundtrip = mirror?.asPayload() XCTAssertTrue(roundtrip! is BookmarkQueryPayload) } func testBookmarks() { let validBookmark = JSON([ "id": "abcabcabcabc", "type": "bookmark", "parentid": "menu", "parentName": "Bookmarks Menu", "title": "Anøther", "bmkUri": "http://terrible.sync/naming", "description": "", "tags": [], "keyword": "", ]) let bookmark = BookmarkType.payloadFromJSON(validBookmark) XCTAssertTrue(bookmark is BookmarkPayload) let query = JSON(parseJSON: "{\"id\":\"ShCZLGEFQMam\",\"type\":\"query\",\"title\":\"Downloads\",\"parentName\":\"\",\"bmkUri\":\"place:transition=7&sort=4\",\"tags\":[],\"keyword\":null,\"description\":null,\"loadInSidebar\":false,\"parentid\":\"T6XK5oJMU8ih\"}") guard let q = BookmarkType.payloadFromJSON(query) else { XCTFail("Failed to generate payload from json: \(query)") return } XCTAssertTrue(q is BookmarkQueryPayload) let item = q.toMirrorItem(Date.now()) XCTAssertEqual(6, item.type.rawValue) XCTAssertEqual("ShCZLGEFQMam", item.guid) let places = JSON(parseJSON: "{\"id\":\"places\",\"type\":\"folder\",\"title\":\"\",\"description\":null,\"children\":[\"menu________\",\"toolbar_____\",\"tags________\",\"unfiled_____\",\"jKnyPDrBQSDg\",\"T6XK5oJMU8ih\"],\"parentid\":\"2hYxKgBwvkEH\"}") guard let p = BookmarkType.payloadFromJSON(places) else { XCTFail("Failed to generate payload from json: \(places)") return } XCTAssertTrue(p is FolderPayload) // Items keep their GUID until they're written into the mirror table. XCTAssertEqual("places", p.id) let pMirror = p.toMirrorItem(Date.now()) XCTAssertEqual(2, pMirror.type.rawValue) // The mirror item has a translated GUID. XCTAssertEqual(BookmarkRoots.RootGUID, pMirror.guid) } }
mpl-2.0
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/NCFetchedCollection.swift
2
1361
// // NCFetchedCollection.swift // Neocom // // Created by Artem Shimanski on 30.11.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import Foundation import CoreData public class NCFetchedCollection<Element : NSFetchRequestResult> { public let entityName: String public let predicateFormat: String public let argumentArray:[Any] public let managedObjectContext: NSManagedObjectContext public let request: NSFetchRequest<Element> public init(entityName: String, predicateFormat: String, argumentArray:[Any], managedObjectContext: NSManagedObjectContext) { self.entityName = entityName self.predicateFormat = predicateFormat self.argumentArray = argumentArray self.managedObjectContext = managedObjectContext self.request = NSFetchRequest<Element>(entityName: entityName) } public subscript(index: Int) -> Element? { var argumentArray = self.argumentArray argumentArray.append(index) request.predicate = NSPredicate(format: self.predicateFormat, argumentArray: argumentArray) return (try? managedObjectContext.fetch(request))?.last } public subscript(key: String) -> Element? { var argumentArray = self.argumentArray argumentArray.append(key) request.predicate = NSPredicate(format: self.predicateFormat, argumentArray: argumentArray) return (try? managedObjectContext.fetch(request))?.last } }
lgpl-2.1
SwiftKitz/Appz
Appz/AppzTests/AppsTests/IMovieTests.swift
1
723
// // IMovieTests.swift // Appz // // Created by Mariam AlJamea on 1/28/17. // Copyright © 2017 kitz. All rights reserved. // import XCTest @testable import Appz class IMovieTests: XCTestCase { let appCaller = ApplicationCallerMock() func testConfiguration() { let iMovie = Applications.IMovie() XCTAssertEqual(iMovie.scheme, "iMovie:") XCTAssertEqual(iMovie.fallbackURL, "") } func testOpen() { let action = Applications.IMovie.Action.open XCTAssertEqual(action.paths.app.pathComponents, ["app"]) XCTAssertEqual(action.paths.app.queryParameters, [:]) XCTAssertEqual(action.paths.web, Path()) } }
mit
almazrafi/Metatron
Sources/Types/Media.swift
1
2233
// // Media.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 public protocol Media: class { // MARK: Instance Properties var title: String {get set} var artists: [String] {get set} var album: String {get set} var genres: [String] {get set} var releaseDate: TagDate {get set} var trackNumber: TagNumber {get set} var discNumber: TagNumber {get set} var coverArt: TagImage {get set} var copyrights: [String] {get set} var comments: [String] {get set} var lyrics: TagLyrics {get set} // MARK: var duration: Double {get} var bitRate: Int {get} var sampleRate: Int {get} var channels: Int {get} // MARK: var filePath: String {get} var isReadOnly: Bool {get} // MARK: Instance Methods @discardableResult func save() -> Bool } public protocol MediaFormat: class { // MARK: Instance Methods func createMedia(fromStream: Stream) throws -> Media func createMedia(fromFilePath: String, readOnly: Bool) throws -> Media func createMedia(fromData: [UInt8], readOnly: Bool) throws -> Media }
mit
welbesw/easypost-swift
Example/EasyPostApi/RatesViewController.swift
1
3627
// // RatesViewController.swift // EasyPostApi // // Created by William Welbes on 10/6/15. // Copyright © 2015 CocoaPods. All rights reserved. // import UIKit import EasyPostApi class RatesViewController: UITableViewController { var shipment:EasyPostShipment! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func didTapCancelButton(_ sender:AnyObject?) { self.dismiss(animated: true, completion: nil) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return the number of rows return shipment.rates.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "rateCell", for: indexPath) as! RateCell // Configure the cell... let rate = self.shipment.rates[(indexPath as NSIndexPath).row] cell.carrierLabel.text = rate.carrier cell.serviceLabel.text = rate.service cell.rateLabel.text = rate.rate return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) //Buy the postage that has been selected let rate = self.shipment.rates[(indexPath as NSIndexPath).row] if let rateId = rate.id { let alertController = UIAlertController(title: "Buy Postage", message: "Do you want to buy this postage for \(rate.rate!)", preferredStyle: UIAlertController.Style.alert) alertController.addAction(UIAlertAction(title: "Buy", style: UIAlertAction.Style.default, handler: { (action) -> Void in EasyPostApi.sharedInstance.buyShipment(self.shipment.id!, rateId: rateId, completion: { (result) -> () in //Handle results DispatchQueue.main.async(execute: { () -> Void in if(result.isSuccess) { print("Successfully bought shipment.") if let buyResponse = result.value { if let postageLabel = buyResponse.postageLabel { if let labelUrl = postageLabel.labelUrl { print("Label url: \(labelUrl)") } } } self.dismiss(animated: true, completion: nil) } else { print("Error buying shipment: \(result.error?.localizedDescription ?? "")") } }) }) })) self.present(alertController, animated: true, completion: nil) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
WeltN24/PiedPiper
Tests/PiedPiperTests/Future+ReduceTests.swift
1
5998
import Quick import Nimble import PiedPiper extension MutableCollection where Self.Index == Int { mutating func shuffle() -> Self { if count < 2 { return self } for i in startIndex ..< endIndex - 1 { let j = Int.random(in: 0..<endIndex - i) + i if i != j { self.swapAt(i, j) } } return self } } class FutureSequenceReduceTests: QuickSpec { override func spec() { describe("Reducing a list of Futures") { var promises: [Promise<Int>]! var reducedFuture: Future<Int>! var successValue: Int? var failureValue: Error? var wasCanceled: Bool! var originalPromisesCanceled: [Bool]! beforeEach { let numberOfPromises = 5 originalPromisesCanceled = (0..<numberOfPromises).map { _ in false } promises = (0..<numberOfPromises).map { idx in Promise().onCancel { originalPromisesCanceled[idx] = true } } wasCanceled = false successValue = nil failureValue = nil reducedFuture = promises .map { $0.future } .reduce(5, combine: +) reducedFuture.onCompletion { result in switch result { case .success(let value): successValue = value case .error(let error): failureValue = error case .cancelled: wasCanceled = true } } } context("when one of the original futures fails") { let expectedError = TestError.anotherError beforeEach { promises.first?.succeed(10) promises[1].fail(expectedError) } it("should fail the reduced future") { expect(failureValue).notTo(beNil()) } it("should fail with the right error") { expect(failureValue as? TestError).to(equal(expectedError)) } it("should not cancel the reduced future") { expect(wasCanceled).to(beFalse()) } it("should not succeed the reduced future") { expect(successValue).to(beNil()) } } context("when one of the original futures is canceled") { beforeEach { promises.first?.succeed(10) promises[1].cancel() } it("should not fail the reduced future") { expect(failureValue).to(beNil()) } it("should cancel the reduced future") { expect(wasCanceled).to(beTrue()) } it("should not succeed the reduced future") { expect(successValue).to(beNil()) } } context("when all the original futures succeed") { var expectedResult: Int! context("when they succeed in the same order") { beforeEach { expectedResult = 5 promises.enumerated().forEach { (iteration, promise) in promise.succeed(iteration) expectedResult = expectedResult + iteration } } it("should not fail the reduced future") { expect(failureValue).to(beNil()) } it("should not cancel the reduced future") { expect(wasCanceled).to(beFalse()) } it("should succeed the reduced future") { expect(successValue).notTo(beNil()) } it("should succeed with the right value") { expect(successValue).to(equal(expectedResult)) } } } context("when canceling the reduced future") { context("when no promise was done") { beforeEach { reducedFuture.cancel() } it("should cancel all the running promises") { expect(originalPromisesCanceled).to(allPass({ $0 == true})) } } context("when some promise was done") { let nonRunningPromiseIndex = 1 beforeEach { promises[nonRunningPromiseIndex].succeed(10) reducedFuture.cancel() } it("should cancel only the non running promises") { expect(originalPromisesCanceled.filter({ $0 == true }).count).to(equal(promises.count - 1)) } it("should not cancel the non running promises") { expect(originalPromisesCanceled[nonRunningPromiseIndex]).to(beFalse()) } } } } describe("Reducing a list of Futures, independently of the order they succeed") { var promises: [Promise<String>]! var reducedFuture: Future<String>! var successValue: String? var expectedResult: String! beforeEach { promises = [ Promise(), Promise(), Promise(), Promise(), Promise() ] successValue = nil reducedFuture = promises .map { $0.future } .reduce("BEGIN-", combine: +) reducedFuture.onSuccess { successValue = $0 } let sequenceOfIndexes = Array(0..<promises.count).map({ "\($0)" }).joined(separator: "") expectedResult = "BEGIN-\(sequenceOfIndexes)" var arrayOfIndexes = Array(promises.enumerated()) repeat { arrayOfIndexes = arrayOfIndexes.shuffle() } while arrayOfIndexes.map({ $0.0 }) == Array(0..<promises.count) arrayOfIndexes.forEach { (originalIndex, promise) in promise.succeed("\(originalIndex)") } } it("should succeed the reduced future") { expect(successValue).notTo(beNil()) } it("should succeed with the right value") { expect(successValue).to(equal(expectedResult)) } } } }
mit
CocoaheadsSaar/Treffen
Treffen1/UI_Erstellung_ohne_Storyboard/AutolayoutTests/AutolayoutTests/MainStackView.swift
1
1722
// // MainStackView.swift // AutolayoutTests // // Created by Markus Schmitt on 13.01.16. // Copyright © 2016 Insecom - Markus Schmitt. All rights reserved. // import UIKit class MainStackView: UIView { var textLabel: UILabel var textField: UITextField var textStackView: UIStackView override init(frame: CGRect) { // views textLabel = UILabel(frame: .zero) textLabel.translatesAutoresizingMaskIntoConstraints = false textLabel.text = "Testlabel" let textSize = textLabel.intrinsicContentSize().width textField = UITextField(frame: .zero) textField.borderStyle = .Line textField.translatesAutoresizingMaskIntoConstraints = false textStackView = UIStackView(arrangedSubviews: [textLabel, textField]) textStackView.translatesAutoresizingMaskIntoConstraints = false textStackView.axis = .Horizontal textStackView.spacing = 10 textStackView.distribution = .Fill super.init(frame: frame) backgroundColor = .whiteColor() addSubview(textStackView) let views = ["textStackView" : textStackView] var layoutConstraints = [NSLayoutConstraint]() layoutConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textStackView]-|", options: [], metrics: nil, views: views) layoutConstraints.append(textLabel.widthAnchor.constraintEqualToConstant(textSize)) NSLayoutConstraint.activateConstraints(layoutConstraints) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
yarrcc/Phonograph
Phonograph/PhonographOutputQueue.swift
1
3581
import AudioToolbox import Foundation public typealias PhonographOutputQueueCallback = (bufferSizeMax: Int) -> NSData public class PhonographOutputQueue { class PhonographOutputQueueUserData { let callback: PhonographOutputQueueCallback let bufferStub: NSData init(callback: PhonographOutputQueueCallback, bufferStub: NSData) { self.callback = callback self.bufferStub = bufferStub } } private var audioQueueRef: AudioQueueRef = nil private let userData: PhonographOutputQueueUserData public init(var asbd: AudioStreamBasicDescription, callback: PhonographOutputQueueCallback, buffersCount: UInt32 = 3, bufferSize: UInt32 = 9600) throws { // TODO: Try to remove unwrap. self.userData = PhonographOutputQueueUserData(callback: callback, bufferStub: NSMutableData(length: Int(bufferSize))!) let userDataUnsafe = UnsafeMutablePointer<Void>(Unmanaged.passUnretained(self.userData).toOpaque()) let code = AudioQueueNewOutput(&asbd, audioQueueOutputCallback, userDataUnsafe, nil, nil, 0, &audioQueueRef) if code != noErr { throw PhonographError.GenericError(code) } for _ in 0..<buffersCount { var bufferRef = AudioQueueBufferRef() let code = AudioQueueAllocateBuffer(audioQueueRef, bufferSize, &bufferRef) if code != noErr { throw PhonographError.GenericError(code) } audioQueueOutputCallback(userDataUnsafe, audioQueueRef, bufferRef) } } deinit { do { try dispose() } catch { // TODO: Probably handle this exception. } } public func dispose() throws { let code = AudioQueueDispose(audioQueueRef, true) if code != noErr { throw PhonographError.GenericError(code) } audioQueueRef = nil } public func start() throws { let code = AudioQueueStart(audioQueueRef, nil) if code != noErr { throw PhonographError.GenericError(code) } } public func stop() throws { let code = AudioQueueStop(audioQueueRef, true) if code != noErr { throw PhonographError.GenericError(code) } } private let audioQueueOutputCallback: AudioQueueOutputCallback = { (inUserData, inAQ, inBuffer) in let userData = Unmanaged<PhonographOutputQueueUserData>.fromOpaque(COpaquePointer(inUserData)).takeUnretainedValue() // TODO: Think about cast. let capacity = Int(inBuffer.memory.mAudioDataBytesCapacity) let dataFromCallback = userData.callback(bufferSizeMax: capacity) // Audio queue will stop requesting buffers if output buffer will not contain bytes. // Use empty buffer filled with zeroes. let data = dataFromCallback.length > 0 ? dataFromCallback : userData.bufferStub let dataInputRaw = UnsafeMutablePointer<Int8>(data.bytes) let dataOutputRaw = UnsafeMutablePointer<Int8>(inBuffer.memory.mAudioData) dataOutputRaw.assignFrom(dataInputRaw, count: data.length) // TODO: Think about cast. inBuffer.memory.mAudioDataByteSize = UInt32(data.length) // TODO: Handle error. AudioQueueEnqueueBuffer(inAQ, inBuffer, 0, nil) } }
mit
alblue/swift
test/SILGen/c_function_pointers.swift
2
2775
// RUN: %target-swift-emit-silgen -enable-sil-ownership -verify %s | %FileCheck %s func values(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(c) (Int) -> Int { return arg } // CHECK-LABEL: sil hidden @$s19c_function_pointers6valuesyS2iXCS2iXCF // CHECK: bb0(%0 : @trivial $@convention(c) (Int) -> Int): // CHECK: return %0 : $@convention(c) (Int) -> Int @discardableResult func calls(_ arg: @convention(c) (Int) -> Int, _ x: Int) -> Int { return arg(x) } // CHECK-LABEL: sil hidden @$s19c_function_pointers5callsyS3iXC_SitF // CHECK: bb0(%0 : @trivial $@convention(c) @noescape (Int) -> Int, %1 : @trivial $Int): // CHECK: [[RESULT:%.*]] = apply %0(%1) // CHECK: return [[RESULT]] @discardableResult func calls_no_args(_ arg: @convention(c) () -> Int) -> Int { return arg() } func global(_ x: Int) -> Int { return x } func no_args() -> Int { return 42 } // CHECK-LABEL: sil hidden @$s19c_function_pointers0B19_to_swift_functionsyySiF func pointers_to_swift_functions(_ x: Int) { // CHECK: bb0([[X:%.*]] : @trivial $Int): func local(_ y: Int) -> Int { return y } // CHECK: [[GLOBAL_C:%.*]] = function_ref @$s19c_function_pointers6globalyS2iFTo // CHECK: [[CVT:%.*]] = convert_function [[GLOBAL_C]] // CHECK: apply {{.*}}([[CVT]], [[X]]) calls(global, x) // CHECK: [[LOCAL_C:%.*]] = function_ref @$s19c_function_pointers0B19_to_swift_functionsyySiF5localL_yS2iFTo // CHECK: [[CVT:%.*]] = convert_function [[LOCAL_C]] // CHECK: apply {{.*}}([[CVT]], [[X]]) calls(local, x) // CHECK: [[CLOSURE_C:%.*]] = function_ref @$s19c_function_pointers0B19_to_swift_functionsyySiFS2iXEfU_To // CHECK: [[CVT:%.*]] = convert_function [[CLOSURE_C]] // CHECK: apply {{.*}}([[CVT]], [[X]]) calls({ $0 + 1 }, x) calls_no_args(no_args) // CHECK: [[NO_ARGS_C:%.*]] = function_ref @$s19c_function_pointers7no_argsSiyFTo // CHECK: [[CVT:%.*]] = convert_function [[NO_ARGS_C]] // CHECK: apply {{.*}}([[CVT]]) } func unsupported(_ a: Any) -> Int { return 0 } func pointers_to_bad_swift_functions(_ x: Int) { calls(unsupported, x) // expected-error{{C function pointer signature '(Any) -> Int' is not compatible with expected type '@convention(c) (Int) -> Int'}} } // CHECK-LABEL: sil private @$s19c_function_pointers22StructWithInitializersV3fn1yyXCvpfiyycfU_ : $@convention(thin) () -> () { // CHECK-LABEL: sil private [thunk] @$s19c_function_pointers22StructWithInitializersV3fn1yyXCvpfiyycfU_To : $@convention(c) () -> () { struct StructWithInitializers { let fn1: @convention(c) () -> () = {} init(a: ()) {} init(b: ()) {} } func pointers_to_nested_local_functions_in_generics<T>(x: T) -> Int{ func foo(y: Int) -> Int { return y } return calls(foo, 0) }
apache-2.0
AndreMuis/FiziksFunhouse
FiziksFunhouse/Library/Float+Random.swift
1
295
// // FFHFloat+Random.swift // FiziksFunhouse // // Created by Andre Muis on 5/5/16. // Copyright © 2016 Andre Muis. All rights reserved. // import Foundation extension Float { static func randomFrom0to1() -> Float { return Float(arc4random()) / Float(UINT32_MAX) } }
mit
nakau1/NerobluCore
NerobluCore/NBButton.swift
1
13304
// ============================================================================= // PHOTTY // Copyright (C) 2015 NeroBlu. All rights reserved. // ============================================================================= import UIKit public enum NBButtonLayout { case None case VerticalImageText(interval:CGFloat) case LeftAlign(edge:CGFloat, interval:CGFloat) } // MARK: - NBButton - /// カスタムなボタンクラス /// /// このボタンクラスは以下の機能があります /// * ハイライト背景色・文字色(highlightedBackgroundColor: XIBから設定可能) /// * 枠線のみのボタン(linedFrame: XIBから設定可能) /// * 角丸(cornerRadius: XIBから設定可能) @IBDesignable public class NBButton : UIButton { private var originalBackgroundColor: UIColor? private var originalBorderColor: UIColor? // MARK: 角丸 /// 角丸の半径 @IBInspectable public var cornerRadius : Float = 0.0 { didSet { let v = self.cornerRadius self.layer.cornerRadius = CGFloat(v) } } // MARK: 枠線 /// 枠線の太さ @IBInspectable public var borderWidth : Float = 0.0 { didSet { let v = self.borderWidth self.layer.borderWidth = CGFloat(v) } } /// 枠線の色 @IBInspectable public var borderColor : UIColor? { didSet { let v = self.borderColor self.originalBorderColor = v self.layer.borderColor = v?.CGColor } } // MARK: ハイライト /// 通常文字色 @IBInspectable public var normalTitleColor : UIColor? = nil { didSet { let v = self.normalTitleColor self.setTitleColor(v, forState: .Normal) } } /// 通常背景色 /// setTitleColor(_:forState:)を使用せずに設定できる @IBInspectable public var normalBackgroundColor : UIColor? = nil { didSet { let v = self.normalBackgroundColor self.originalBackgroundColor = v self.backgroundColor = v } } /// ハイライト時の文字色 @IBInspectable public var highlightedTitleColor : UIColor? = nil { didSet { let v = self.highlightedTitleColor self.setTitleColor(v, forState: .Highlighted) } } /// ハイライト時の背景色 @IBInspectable public var highlightedBackgroundColor : UIColor? = nil /// ハイライト時の枠線の色 @IBInspectable public var highlightedBorderColor : UIColor? override public var highlighted: Bool { get { return super.highlighted } set(v) { super.highlighted = v let nb = self.originalBackgroundColor, hb = self.highlightedBackgroundColor, cb = v ? hb : nb self.backgroundColor = cb let nl = self.originalBorderColor, hl = self.highlightedBorderColor, cl = v ? hl : nl self.layer.borderColor = cl?.CGColor } } // MARK: 定形レイアウト /// 定形レイアウト種別 public var fixedLayout: NBButtonLayout = .None { didSet { self.applyFixedLayout() } } override public var frame: CGRect { didSet { self.applyFixedLayout() } } private struct SizeSet { var bw: CGFloat = 0 // buttonWidth var bh: CGFloat = 0 // buttonHeight var iw: CGFloat = 0 // imageWidth var ih: CGFloat = 0 // imageHeight var tw: CGFloat = 0 // textWidth var th: CGFloat = 0 // textHeight init?(button: UIButton) { guard let imageView = button.imageView, let titleLabel = button.titleLabel else { return nil } self.bw = crW(button.bounds) self.bh = crH(button.bounds) self.iw = crW(imageView.bounds) self.ih = crH(imageView.bounds) self.tw = crW(titleLabel.bounds) self.th = crH(titleLabel.bounds) } } public func applyFixedLayout() { guard let size = SizeSet(button: self) else { return } switch self.fixedLayout { case .VerticalImageText: self.updateEdgeInsetsVerticalImageText(size) case .LeftAlign: self.updateEdgeInsetsLeftAlign(size) default:break } } private func updateEdgeInsetsVerticalImageText(s: SizeSet) { var interval:CGFloat = 0 switch self.fixedLayout { case .VerticalImageText(let i): interval = i default:return // dead code } let verticalMergin = (s.bh - (s.th + interval + s.ih)) / 2.0 let imageHorizonMergin = (s.bw - s.iw) / 2.0 // content var t:CGFloat = 0, l:CGFloat = 0, b:CGFloat = 0, r:CGFloat = 0 self.contentEdgeInsets = UIEdgeInsetsMake(t, l, b, r) // image t = verticalMergin l = imageHorizonMergin b = verticalMergin + s.th + (interval / 2.0) r = imageHorizonMergin - s.tw self.imageEdgeInsets = UIEdgeInsetsMake(t, l, b, r) // text t = verticalMergin + s.ih + (interval / 2.0) l = -s.iw b = verticalMergin r = 0 self.titleEdgeInsets = UIEdgeInsetsMake(t, l, b, r) } private func updateEdgeInsetsLeftAlign(s: SizeSet) { var edge:CGFloat = 0, interval:CGFloat = 0, l:CGFloat = 0 switch self.fixedLayout { case .LeftAlign(let e, let i): edge = e; interval = i default:return // dead code } // content l = s.bw - s.tw - s.iw - edge self.contentEdgeInsets = UIEdgeInsetsMake(0, -l, 0, 0) // text l = interval self.titleEdgeInsets = UIEdgeInsetsMake(0, l, 0, 0) } // MARK: 初期化 /// インスタン生成時の共通処理 internal func commonInitialize() { self.originalBackgroundColor = self.backgroundColor } override public init (frame : CGRect) { super.init(frame : frame); commonInitialize() } convenience public init () { self.init(frame:CGRect.zero) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); commonInitialize() } } // MARK: - UIButton Extension - public extension UIButton { /// タイトルラベルのフォント public var titleFont: UIFont? { get { return self.titleLabel?.font } set(v) { guard let titleLabel = self.titleLabel else { return } titleLabel.font = v } } } // MARK: - NBLongPressableButton - /// NBLongPressableButton用デリゲートプロトコル @objc public protocol NBLongPressableButtonDelegate { /// 継続的な長押しイベントが発生した時(押しっぱなし中に一定間隔で呼ばれる) /// - parameter longPressableButton: ボタンの参照 /// - parameter times: イベント発生回数(1から始まる通し番号) optional func longPressableButtonDidHoldPress(longPressableButton: NBLongPressableButton, times: UInt64) /// 継続的な長押しが始まった時 /// - parameter longPressableButton: ボタンの参照 optional func longPressableButtonDidStartLongPress(longPressableButton: NBLongPressableButton) /// 継続的な長押しが終わった時 /// - parameter longPressableButton: ボタンの参照 optional func longPressableButtonDidStopLongPress(longPressableButton: NBLongPressableButton) } /// 継続的長押しが可能なボタンクラス @IBDesignable public class NBLongPressableButton : NBButton { /// デリゲート @IBOutlet public weak var delegate: NBLongPressableButtonDelegate? /// 長押しを感知するまでに要する秒数 @IBInspectable public var longPressRecognizeDuration : Double = 1.2 // as CFTimeInterval /// 1段階目の長押し継続を感知するまでに要する秒数 @IBInspectable public var primaryIntervalOfContinuousEvent : Double = 0.1 /// 1段階目の長押し継続を繰り返す回数 @IBInspectable public var primaryTimesOfContinuousEvent : Int = 10 /// 2段階目の長押し継続を感知するまでに要する秒数 @IBInspectable public var secondaryIntervalOfContinuousEvent : Double = 0.05 /// 2段階目の長押し継続を繰り返す回数 @IBInspectable public var secondaryTimesOfContinuousEvent : Int = 50 /// 3段階目の長押し継続を感知するまでに要する秒数 @IBInspectable public var finalyIntervalOfContinuousEvent : Double = 0.01 enum ContinuousEventPhase { case Primary, Secondary, Finaly } private let longPressMinimumPressDuration: Double = 1.0 private var longPressRecognizer: UILongPressGestureRecognizer? private var longPressTimer: NSTimer? private var touchesStarted: CFTimeInterval? private var touchesEnded: Bool = false private var eventPhase: ContinuousEventPhase = .Primary private var eventTimes: Int = 0 private var eventTotalTimes: UInt64 = 0 internal override func commonInitialize() { super.commonInitialize() let lpr = UILongPressGestureRecognizer(target: self, action: Selector("didRecognizeLongPress:")) lpr.cancelsTouchesInView = false lpr.minimumPressDuration = self.longPressRecognizeDuration self.addGestureRecognizer(lpr) } @objc private func didRecognizeLongPress(recognizer: UILongPressGestureRecognizer) { if recognizer.state == .Began { self.didBeginPressButton() } else if recognizer.state == .Ended { self.didEndPressButton() } } private func didBeginPressButton() { if self.touchesStarted != nil { return } self.setNeedsDisplay() self.touchesStarted = CACurrentMediaTime() self.touchesEnded = false let delta = Int64(Double(NSEC_PER_SEC) * self.longPressMinimumPressDuration) let delay = dispatch_time(DISPATCH_TIME_NOW, delta) dispatch_after(delay, dispatch_get_main_queue()) { [weak self] in if let strongSelf = self where strongSelf.touchesEnded { strongSelf.didEndPressButton() } } self.delegate?.longPressableButtonDidStartLongPress?(self) self.startLongPressTimer() } private func didEndPressButton() { if let touchesStarted = self.touchesStarted where (CACurrentMediaTime() - touchesStarted) >= Double(self.longPressMinimumPressDuration) { self.touchesStarted = nil self.stopLongPressTimer() self.delegate?.longPressableButtonDidStopLongPress?(self) } else { self.touchesEnded = true } } private func startLongPressTimer() { self.eventPhase = .Primary self.eventTimes = 0 self.eventTotalTimes = 0 self.longPressTimer = NSTimer.scheduledTimerWithTimeInterval(self.intervalOfContinuousEvent, target: self, selector: Selector("didFireLongPressTimer:"), userInfo: nil, repeats: false ) } @objc private func didFireLongPressTimer(timer: NSTimer) { if self.eventTotalTimes < UINT64_MAX { self.eventTotalTimes++ } self.delegate?.longPressableButtonDidHoldPress?(self, times: self.eventTotalTimes) if self.eventPhase != .Finaly && ++self.eventTimes >= self.timesOfContinuousEvent { self.updateToNextContinuousEventPhase() self.eventTimes = 0 } self.longPressTimer = NSTimer.scheduledTimerWithTimeInterval(self.intervalOfContinuousEvent, target: self, selector: Selector("didFireLongPressTimer:"), userInfo: nil, repeats: false ) } private func stopLongPressTimer() { if let timer = self.longPressTimer where timer.valid { timer.invalidate() } self.longPressTimer = nil } private var intervalOfContinuousEvent: NSTimeInterval { switch self.eventPhase { case .Primary: return self.primaryIntervalOfContinuousEvent case .Secondary: return self.secondaryIntervalOfContinuousEvent case .Finaly: return self.finalyIntervalOfContinuousEvent } } private var timesOfContinuousEvent: Int { switch self.eventPhase { case .Primary: return self.primaryTimesOfContinuousEvent case .Secondary: return self.secondaryTimesOfContinuousEvent case .Finaly: return -1 } } private func updateToNextContinuousEventPhase() { if self.eventPhase == .Primary { self.eventPhase = .Secondary } else if self.eventPhase == .Secondary { self.eventPhase = .Finaly } } }
apache-2.0
anthonyohare/SwiftScientificLibrary
Sources/SwiftScientificLibrary/extensions/Int.swift
1
984
import Foundation // Extensions to Int to allow casting from floating points and complex numbers. extension Int { /// Create an integer from a floating point variable, useful for casting complex numbers /// to integers. /// /// - Parameter value: The number to be cast to integer. public init(floatLiteral value: FloatLiteralType) { self = Int(value) } /// Create an integer from a complex number, useful for casting complex numbers to integers. /// /// - Parameter value: The number to be cast to integer. /// - Throws: IntegerCastError if the number cannot be cast. public init(_ value: Complex) throws { if value.imag != 0 { throw Error.integerCastError } // Check if the real part is an integer, fail if not if value.real.truncatingRemainder(dividingBy: 1) != 0 { throw Error.integerCastError } self = Int(value.real) } }
mit
Tanner1638/SAD_Final
CuppitProject/Cuppit/GameScene.swift
1
17535
// // GameScene.swift // Cuppit // // Created by Austin Sands on 11/5/16. // Copyright © 2016 Austin Sands. All rights reserved. // import SpriteKit struct PhysicsCatagory { static let enemyCatagory : UInt32 = 0x1 << 0 static let cupCategory : UInt32 = 0x1 << 1 static let scoreCategory: UInt32 = 0x1 << 2 } //create score and highscore variables var score = 0 var highScore = 0 class GameScene: SKScene, SKPhysicsContactDelegate { var rotatorValue: Float = 0 var EnemyTimer = Timer() var gameStarted = false var cup: SKSpriteNode! var scoreNode = SKSpriteNode() var ScoreLbl = SKLabelNode(fontNamed: "Gameplay") var HighScoreLbl = SKLabelNode(fontNamed: "Gameplay") var slider: UISlider! var lastTouch: CGPoint? = nil var ableToPlay = true var pausePlayBTN: SKSpriteNode! var nodeSpeed = 12.0 var timeDuration = 0.8 let pauseTexture = SKTexture(imageNamed: "Pause Filled-50") let playTexture = SKTexture(imageNamed: "Play Filled-50") let homeTexture = SKTexture(imageNamed: "Home-48") var homeBtn: SKSpriteNode! override func didMove(to view: SKView) { //stuff to setup scene SceneSetup() Cup() Scores() ScoreNode() PausePlayButton() HomeBtn() } func SceneSetup(){ score = 0 self.physicsWorld.contactDelegate = self self.anchorPoint = CGPoint(x: 0, y: 0) //self.backgroundColor = UIColor(red: 0.1373, green: 0.1373, blue: 0.1373, alpha: 1.0) self.backgroundColor = UIColor.black self.isPaused = false let starBackground = SKEmitterNode(fileNamed: "StarBackground")! starBackground.particlePositionRange.dx = self.frame.size.width starBackground.particlePositionRange.dy = self.frame.size.height starBackground.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2) starBackground.zPosition = 0.5 self.addChild(starBackground) } func Cup(){ //create the cup let cupTexture = SKTexture(imageNamed: "CuppitC") cup = SKSpriteNode(texture: cupTexture) cup.size = CGSize(width: 180, height: 180) cup.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2) cup.physicsBody = SKPhysicsBody(texture: cupTexture, size: CGSize(width: cup.size.width, height: cup.size.height)) cup.physicsBody?.affectedByGravity = false cup.physicsBody?.isDynamic = false cup.physicsBody?.allowsRotation = true cup.physicsBody?.categoryBitMask = PhysicsCatagory.cupCategory cup.physicsBody?.contactTestBitMask = PhysicsCatagory.enemyCatagory cup.physicsBody?.collisionBitMask = PhysicsCatagory.enemyCatagory cup.zRotation = CGFloat(rotatorValue) cup.name = "cup" cup.zPosition = 5 cup.setScale(1.0) self.addChild(cup) cup.run(pulseAnimation()) cup.physicsBody?.usesPreciseCollisionDetection = true cup.physicsBody?.restitution = 1.0 } func Scores(){ //save highscore let HighscoreDefault = UserDefaults.standard if HighscoreDefault.value(forKey: "Highscore") != nil { highScore = HighscoreDefault.value(forKey: "Highscore") as! Int HighScoreLbl.text = "\(highScore)" } HighScoreLbl.fontSize = 60 HighScoreLbl.position = CGPoint(x: self.frame.size.width - 15, y: self.frame.height - 15) HighScoreLbl.fontColor = SKColor(red: 1, green: 0.9804, blue: 0, alpha: 1.0) HighScoreLbl.text = "\(highScore)" HighScoreLbl.zPosition = 5 HighScoreLbl.horizontalAlignmentMode = .right HighScoreLbl.verticalAlignmentMode = .top self.addChild(HighScoreLbl) ScoreLbl.fontSize = 110 ScoreLbl.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.height - ((self.frame.height - cup.position.y) / 2)) ScoreLbl.fontColor = SKColor(red: 0, green: 0.4784, blue: 0.9294, alpha: 1.0) ScoreLbl.text = "\(score)" ScoreLbl.horizontalAlignmentMode = .center ScoreLbl.verticalAlignmentMode = .center ScoreLbl.zPosition = 5 self.addChild(ScoreLbl) } func ScoreNode(){ scoreNode.size = CGSize(width: 10, height: 10) scoreNode.color = SKColor.clear scoreNode.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2) scoreNode.name = "scoreNode" scoreNode.physicsBody = SKPhysicsBody(rectangleOf: scoreNode.size) scoreNode.physicsBody?.affectedByGravity = false scoreNode.physicsBody?.isDynamic = false scoreNode.physicsBody?.allowsRotation = false scoreNode.physicsBody?.categoryBitMask = PhysicsCatagory.scoreCategory scoreNode.physicsBody?.contactTestBitMask = PhysicsCatagory.enemyCatagory scoreNode.physicsBody?.collisionBitMask = PhysicsCatagory.enemyCatagory scoreNode.zPosition = 1 self.addChild(scoreNode) } func PausePlayButton(){ pausePlayBTN = SKSpriteNode(texture: pauseTexture) pausePlayBTN.size = CGSize(width: 60, height: 60) pausePlayBTN.anchorPoint = CGPoint(x: 0.0, y: 1.0) pausePlayBTN.position = CGPoint(x: 10, y: self.frame.height - 10) pausePlayBTN.name = "Pause" pausePlayBTN.zPosition = 5 self.addChild(pausePlayBTN) } func HomeBtn() { homeBtn = SKSpriteNode(texture: homeTexture) homeBtn.size = CGSize(width: 60, height: 60) homeBtn.anchorPoint = CGPoint(x: 0.0, y: 1.0) homeBtn.position = CGPoint(x: pausePlayBTN.position.x + 60, y: self.frame.height - 10) homeBtn.name = "Home" homeBtn.zPosition = 5 self.addChild(homeBtn) } func GameOver(){ scoreNode.removeFromParent() self.removeAllActions() EnemyTimer.invalidate() gameStarted = false cup.removeAllActions() self.run(SKAction.sequence([SKAction.wait(forDuration: 1.0), SKAction.run { let GameOverScene = GameScene(fileNamed: "GameOverScene") GameOverScene?.scaleMode = .aspectFill GameOverScene?.size = (self.view?.bounds.size)! self.view?.presentScene(GameOverScene!, transition: SKTransition.push(with: .up, duration: 0.5)) }])) } func pulseAnimation() -> SKAction { let duration = 1.0 let pulseOut = SKAction.scale(to: 1.2, duration: duration) let pulseIn = SKAction.scale(to: 1.0, duration: duration) let pulse = SKAction.sequence([pulseOut, pulseIn]) return SKAction.repeatForever(pulse) } func Enemies(){ let Enemy = SKSpriteNode(imageNamed: "EnemyCool") Enemy.size = CGSize(width: 30, height: 30) //Physics Enemy.physicsBody = SKPhysicsBody(circleOfRadius: Enemy.size.width / 2) Enemy.physicsBody?.categoryBitMask = PhysicsCatagory.enemyCatagory Enemy.physicsBody?.contactTestBitMask = PhysicsCatagory.cupCategory | PhysicsCatagory.scoreCategory Enemy.physicsBody?.collisionBitMask = PhysicsCatagory.cupCategory | PhysicsCatagory.scoreCategory Enemy.physicsBody?.affectedByGravity = false Enemy.physicsBody?.isDynamic = true Enemy.zPosition = 1 Enemy.name = "Enemy" Enemy.physicsBody?.friction = 0 Enemy.physicsBody?.angularDamping = 0 Enemy.physicsBody?.linearDamping = 0 Enemy.physicsBody?.usesPreciseCollisionDetection = true Enemy.physicsBody?.restitution = 1.0 let trailNode = SKNode() trailNode.zPosition = 3 addChild(trailNode) let trail = SKEmitterNode(fileNamed: "TrailForEnemy")! trail.targetNode = trailNode Enemy.addChild(trail) let RandomPosNmbr = arc4random() % 4 //8 switch RandomPosNmbr{ case 0: Enemy.position.x = -100 let PositionY = arc4random_uniform(UInt32(frame.size.height)) Enemy.position.y = CGFloat(PositionY) var dx = CGFloat(cup.position.x - Enemy.position.x) var dy = CGFloat(cup.position.y - Enemy.position.y) let magnitude = sqrt(dx * dx + dy * dy) dx /= magnitude dy /= magnitude self.addChild(Enemy) let vector = CGVector(dx: CGFloat(nodeSpeed) * dx, dy: CGFloat(nodeSpeed) * dy) Enemy.physicsBody?.applyImpulse(vector) break case 1: Enemy.position.y = -100 let PositionX = arc4random_uniform(UInt32(frame.size.width)) Enemy.position.x = CGFloat(PositionX) var dx = CGFloat(cup.position.x - Enemy.position.x) var dy = CGFloat(cup.position.y - Enemy.position.y) let magnitude = sqrt(dx * dx + dy * dy) dx /= magnitude dy /= magnitude self.addChild(Enemy) let vector = CGVector(dx: CGFloat(nodeSpeed) * dx, dy: CGFloat(nodeSpeed) * dy) Enemy.physicsBody?.applyImpulse(vector) break case 2: Enemy.position.y = frame.size.height + 100 let PositionX = arc4random_uniform(UInt32(frame.size.width)) Enemy.position.x = CGFloat(PositionX) var dx = CGFloat(cup.position.x - Enemy.position.x) var dy = CGFloat(cup.position.y - Enemy.position.y) let magnitude = sqrt(dx * dx + dy * dy) dx /= magnitude dy /= magnitude self.addChild(Enemy) let vector = CGVector(dx: CGFloat(nodeSpeed) * dx, dy: CGFloat(nodeSpeed) * dy) Enemy.physicsBody?.applyImpulse(vector) break case 3: Enemy.position.x = frame.size.width + 100 let PositionY = arc4random_uniform(UInt32(frame.size.height)) Enemy.position.y = CGFloat(PositionY) var dx = CGFloat(cup.position.x - Enemy.position.x) var dy = CGFloat(cup.position.y - Enemy.position.y) let magnitude = sqrt(dx * dx + dy * dy) dx /= magnitude dy /= magnitude self.addChild(Enemy) let vector = CGVector(dx: CGFloat(nodeSpeed) * dx, dy: CGFloat(nodeSpeed) * dy) Enemy.physicsBody?.applyImpulse(vector) break default: break } } func didBegin(_ contact: SKPhysicsContact) { if contact.bodyA.node != nil && contact.bodyB.node != nil{ let firstBody = contact.bodyA.node as! SKSpriteNode let secondBody = contact.bodyB.node as! SKSpriteNode if ((firstBody.name == "cup") && (secondBody.name == "Enemy")){ collisionMain(secondBody) } else if ((firstBody.name == "Enemy") && (secondBody.name == "cup")){ collisionMain(firstBody) } else if ((firstBody.name == "scoreNode") && (secondBody.name == "Enemy")){ collisionScore(secondBody) } else if ((firstBody.name == "Enemy") && (secondBody.name == "scoreNode")){ collisionScore(firstBody) } } } func collisionMain(_ Enemy : SKSpriteNode){ func explodeBall(_ node: SKNode) { let emitter = SKEmitterNode(fileNamed: "ExplodeParticle")! emitter.position = node.position emitter.zPosition = 10 addChild(emitter) emitter.run(SKAction.sequence([SKAction.wait(forDuration: 1.0), SKAction.removeFromParent()])) node.removeFromParent() } func explodeCup(_ node: SKNode) { let emitter = SKEmitterNode(fileNamed: "CupExplodeParticle")! emitter.position = node.position emitter.zPosition = 10 addChild(emitter) emitter.run(SKAction.sequence([SKAction.wait(forDuration: 1.0), SKAction.removeFromParent()])) node.removeFromParent() } explodeCup(cup) explodeBall(Enemy) ableToPlay = false Enemy.removeAllActions() GameOver() } func collisionScore(_ Enemy : SKSpriteNode){ Enemy.removeAllActions() Enemy.removeFromParent() if gameStarted { if score <= 8 { timeDuration = 1.2 } else { timeDuration = 0.8 } nodeSpeed += 0.5 score += 1 ScoreLbl.text = "\(score)" if score > highScore { let HighscoreDefault = UserDefaults.standard highScore = score HighscoreDefault.set(highScore, forKey: "Highscore") HighScoreLbl.text = "\(highScore)" } } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if gameStarted == false && ableToPlay { cup.removeAllActions() cup.run(SKAction.scale(to: 1.0, duration: 0.5)) EnemyTimer = Timer.scheduledTimer(timeInterval: timeDuration, target: self, selector: #selector(GameScene.Enemies), userInfo: nil, repeats: true) gameStarted = true } handleTouches(touches) for touch in touches { let location = touch.location(in: self) let nodes = self.nodes(at: location) for node in nodes { if node.name == "Pause" { self.isPaused = true pausePlayBTN.name = "Play" pausePlayBTN.texture = playTexture EnemyTimer.invalidate() } else if node.name == "Play" { self.isPaused = false pausePlayBTN.name = "Pause" pausePlayBTN.texture = pauseTexture EnemyTimer = Timer.scheduledTimer(timeInterval: timeDuration, target: self, selector: #selector(GameScene.Enemies), userInfo: nil, repeats: true) } else if node.name == "Home" { score = 0 self.removeAllActions() let MenuScene = GameScene(fileNamed: "MenuScene") MenuScene?.scaleMode = .aspectFill MenuScene?.size = (self.view?.bounds.size)! self.view?.presentScene(MenuScene!, transition: SKTransition.push(with: .up, duration: 0.5)) } } } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { handleTouches(touches) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { handleTouches(touches) } fileprivate func handleTouches(_ touches: Set<UITouch>) { for touch in touches { let touchLocation = touch.location(in: self) lastTouch = touchLocation } } override func didSimulatePhysics() { if let _ = cup { updateCup() } } fileprivate func shouldMove(currentPosition: CGPoint, touchPosition: CGPoint) -> Bool { return abs(currentPosition.x - touchPosition.x) > cup!.frame.width / 2 || abs(currentPosition.y - touchPosition.y) > cup!.frame.height / 2 } func updateCup(){ if let touch = lastTouch { let currentPosition = cup!.position if shouldMove(currentPosition: currentPosition, touchPosition: touch) { let angle = atan2(currentPosition.y - touch.y, currentPosition.x - touch.x) + CGFloat(M_PI) let rotateAction = SKAction.rotate(toAngle: angle - CGFloat(M_PI*0.5), duration: 0) cup.run(rotateAction) } } } }
mit
Natoto/arcgis-runtime-samples-ios
AsynchronousGPSample/swift/AsynchronousGP/AsyncGPParameters.swift
4
1705
// Copyright 2014 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm import Foundation import ArcGIS class AsyncGPParameters { var featureSet:AGSFeatureSet? var windDirection:NSDecimalNumber var materialType:String var dayOrNightIncident:String var largeOrSmallSpill:String init() { windDirection = NSDecimalNumber(double: 90) materialType = "Anhydrous ammonia" dayOrNightIncident = "Day" largeOrSmallSpill = "Large" } func parametersArray() -> [AGSGPParameterValue] { //create parameters var paramLoc = AGSGPParameterValue(name: "Incident_Point", type: .FeatureRecordSetLayer, value: self.featureSet!) var paramDegree = AGSGPParameterValue(name: "Wind_Bearing__direction_blowing_to__0_-_360_", type: .Double, value: self.windDirection.doubleValue) var paramMaterial = AGSGPParameterValue(name: "Material_Type", type: .String, value: self.materialType) var paramTime = AGSGPParameterValue(name: "Day_or_Night_incident", type: .String, value: self.dayOrNightIncident) var paramType = AGSGPParameterValue(name: "Large_or_Small_spill", type: .String, value: self.largeOrSmallSpill) var params:[AGSGPParameterValue] = [paramLoc, paramDegree, paramTime, paramType, paramMaterial] return params } }
apache-2.0
dreamsxin/swift
validation-test/compiler_crashers_fixed/27737-swift-parentype-get.swift
11
464
// 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 // RUN: not %target-swift-frontend %s -parse struct Q{ struct B<T where H:a{ struct S{var _=[{} class A let c{{{} A{
apache-2.0
sajnabjohn/WebPage
WebPage/Classes/Reachability.swift
1
5538
// // Reachability.swift // Copyright © 2016 . All rights reserved. // import Foundation import SystemConfiguration public let ReachabilityDidChangeNotificationName = "ReachabilityDidChangeNotification" enum ReachabilityStatus { case notReachable case reachableViaWiFi case reachableViaWWAN } class Reachability: NSObject { private var networkReachability: SCNetworkReachability? private var notifying: Bool = false init?(hostAddress: sockaddr_in) { var address = hostAddress guard let defaultRouteReachability = withUnsafePointer(to: &address, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, $0) } }) else { return nil } networkReachability = defaultRouteReachability super.init() if networkReachability == nil { return nil } } static func networkReachabilityForInternetConnection() -> Reachability? { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) return Reachability(hostAddress: zeroAddress) } static func networkReachabilityForLocalWiFi() -> Reachability? { var localWifiAddress = sockaddr_in() localWifiAddress.sin_len = UInt8(MemoryLayout.size(ofValue: localWifiAddress)) localWifiAddress.sin_family = sa_family_t(AF_INET) // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0 (0xA9FE0000). localWifiAddress.sin_addr.s_addr = 0xA9FE0000 return Reachability(hostAddress: localWifiAddress) } func startNotifier() -> Bool { guard notifying == false else { return false } var context = SCNetworkReachabilityContext() context.info = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) guard let reachability = networkReachability, SCNetworkReachabilitySetCallback(reachability, { (target: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) in if let currentInfo = info { let infoObject = Unmanaged<AnyObject>.fromOpaque(currentInfo).takeUnretainedValue() if infoObject is Reachability { let networkReachability = infoObject as! Reachability NotificationCenter.default.post(name: Notification.Name(rawValue: ReachabilityDidChangeNotificationName), object: networkReachability) } } }, &context) == true else { return false } guard SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue) == true else { return false } notifying = true return notifying } func stopNotifier() { if let reachability = networkReachability, notifying == true { SCNetworkReachabilityUnscheduleFromRunLoop(reachability, CFRunLoopGetCurrent(), CFRunLoopMode.defaultMode.rawValue ) notifying = false } } private var flags: SCNetworkReachabilityFlags { var flags = SCNetworkReachabilityFlags(rawValue: 0) if let reachability = networkReachability, withUnsafeMutablePointer(to: &flags, { SCNetworkReachabilityGetFlags(reachability, UnsafeMutablePointer($0)) }) == true { return flags } else { return [] } } var currentReachabilityStatus: ReachabilityStatus { if flags.contains(.reachable) == false { // The target host is not reachable. return .notReachable } else if flags.contains(.isWWAN) == true { // WWAN connections are OK if the calling application is using the CFNetwork APIs. return .reachableViaWWAN } else if flags.contains(.connectionRequired) == false { // If the target host is reachable and no connection is required then we'll assume that you're on Wi-Fi... return .reachableViaWiFi } else if (flags.contains(.connectionOnDemand) == true || flags.contains(.connectionOnTraffic) == true) && flags.contains(.interventionRequired) == false { // The connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs and no [user] intervention is needed return .reachableViaWiFi } else { return .notReachable } } var isReachable: Bool { switch currentReachabilityStatus { case .notReachable: return false case .reachableViaWiFi, .reachableViaWWAN: return true } } deinit { stopNotifier() } }
mit
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Gutenberg/EditHomepageViewController.swift
1
1716
import Foundation class EditHomepageViewController: GutenbergViewController { required init( post: AbstractPost, loadAutosaveRevision: Bool = false, replaceEditor: @escaping ReplaceEditorCallback, editorSession: PostEditorAnalyticsSession? = nil, navigationBarManager: PostEditorNavigationBarManager? = nil ) { let navigationBarManager = navigationBarManager ?? HomepageEditorNavigationBarManager() super.init(post: post, loadAutosaveRevision: loadAutosaveRevision, replaceEditor: replaceEditor, editorSession: editorSession, navigationBarManager: navigationBarManager) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private(set) lazy var homepageEditorStateContext: PostEditorStateContext = { return PostEditorStateContext(post: post, delegate: self, action: .continueFromHomepageEditing) }() override var postEditorStateContext: PostEditorStateContext { return homepageEditorStateContext } // If there are changes, offer to save them, otherwise continue will dismiss the editor with no changes. override func continueFromHomepageEditing() { if editorHasChanges { handlePublishButtonTap() } else { cancelEditing() } } } extension EditHomepageViewController: HomepageEditorNavigationBarManagerDelegate { var continueButtonText: String { return postEditorStateContext.publishButtonText } func navigationBarManager(_ manager: HomepageEditorNavigationBarManager, continueWasPressed sender: UIButton) { requestHTML(for: .continueFromHomepageEditing) } }
gpl-2.0
davetrux/1DevDayDetroit-2014
ios/Hello1DevDay/Hello1DevDay/AppDelegate.swift
1
2163
// // AppDelegate.swift // Hello1DevDay // // Created by David Truxall on 10/24/14. // Copyright (c) 2014 Hewlett-Packard Company. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
LeLuckyVint/MessageKit
Sources/Protocols/MessagesDataSource.swift
1
2409
/* MIT License Copyright (c) 2017 MessageKit 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 protocol MessagesDataSource: class { func currentSender() -> Sender func isFromCurrentSender(message: MessageType) -> Bool func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType func numberOfMessages(in messagesCollectionView: MessagesCollectionView) -> Int func avatar(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> Avatar func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? func cellBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? } public extension MessagesDataSource { func isFromCurrentSender(message: MessageType) -> Bool { return message.sender == currentSender() } func avatar(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> Avatar { return Avatar() } func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? { return nil } func cellBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? { return nil } }
mit
JQHee/JQProgressHUD
Source/JQWeakTimerObject.swift
2
1415
// // test.swift // JQProgressHUD // // Created by HJQ on 2017/7/2. // Copyright © 2017年 HJQ. All rights reserved. // import Foundation open class JQWeakTimerObject: NSObject { @objc public weak var targat: AnyObject? @objc public var selector: Selector? @objc public var timer: Timer? @objc public static func scheduledTimerWithTimeInterval(_ interval: TimeInterval, aTargat: AnyObject, aSelector: Selector, userInfo: AnyObject?, repeats: Bool) -> Timer { let weakObject = JQWeakTimerObject() weakObject.targat = aTargat weakObject.selector = aSelector weakObject.timer = Timer.scheduledTimer(timeInterval: interval, target: weakObject, selector: #selector(fire), userInfo: userInfo, repeats: repeats) return weakObject.timer! } @objc public func fire(_ ti: Timer) { if let _ = targat { _ = targat?.perform(selector!, with: ti.userInfo) } else { timer?.invalidate() } } }
apache-2.0
insidegui/WWDC
WWDC/TranscriptSearchController.swift
1
5042
// // TranscriptSearchController.swift // WWDC // // Created by Guilherme Rambo on 30/05/20. // Copyright © 2020 Guilherme Rambo. All rights reserved. // import Cocoa import ConfCore import RxSwift import RxCocoa import PlayerUI final class TranscriptSearchController: NSViewController { enum Style: Int { case fullWidth case corner } var style: Style = .corner { didSet { guard style != oldValue else { return } updateStyle() } } var showsNewWindowButton: Bool { get { !detachButton.isHidden } set { detachButton.isHidden = !newValue } } var didSelectOpenInNewWindow: () -> Void = { } var didSelectExportTranscript: () -> Void = { } private(set) var searchTerm = BehaviorRelay<String?>(value: nil) private lazy var detachButton: PUIButton = { let b = PUIButton(frame: .zero) b.image = #imageLiteral(resourceName: "window") b.target = self b.action = #selector(openInNewWindow) b.toolTip = "Open Transcript in New Window" b.setContentHuggingPriority(.defaultHigh, for: .horizontal) b.widthAnchor.constraint(equalToConstant: 18).isActive = true b.heightAnchor.constraint(equalToConstant: 14).isActive = true return b }() private lazy var exportButton: NSView = { let b = PUIButton(frame: .zero) b.image = #imageLiteral(resourceName: "share") b.target = self b.action = #selector(exportTranscript) b.toolTip = "Export Transcript" b.setContentHuggingPriority(.defaultHigh, for: .horizontal) b.translatesAutoresizingMaskIntoConstraints = false let container = NSView() container.translatesAutoresizingMaskIntoConstraints = false container.addSubview(b) NSLayoutConstraint.activate([ b.widthAnchor.constraint(equalToConstant: 14), b.heightAnchor.constraint(equalToConstant: 18), container.widthAnchor.constraint(equalToConstant: 14), container.heightAnchor.constraint(equalToConstant: 22), b.centerXAnchor.constraint(equalTo: container.centerXAnchor), b.centerYAnchor.constraint(equalTo: container.centerYAnchor, constant: -2) ]) return container }() private lazy var searchField: NSSearchField = { let f = NSSearchField() f.translatesAutoresizingMaskIntoConstraints = false f.setContentHuggingPriority(.defaultLow, for: .horizontal) return f }() private lazy var stackView: NSStackView = { let v = NSStackView(views: [self.searchField, self.exportButton, self.detachButton]) v.orientation = .horizontal v.spacing = 8 v.translatesAutoresizingMaskIntoConstraints = false return v }() private lazy var widthConstraint: NSLayoutConstraint = { view.widthAnchor.constraint(equalToConstant: 226) }() static let height: CGFloat = 40 override func loadView() { view = NSView() view.wantsLayer = true view.layer?.cornerCurve = .continuous view.layer?.backgroundColor = NSColor.roundedCellBackground.cgColor view.addSubview(stackView) NSLayoutConstraint.activate([ view.heightAnchor.constraint(equalToConstant: Self.height), stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor), stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10), stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10) ]) updateStyle() } private let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() let throttledSearch = searchField.rx.text.throttle(.milliseconds(500), scheduler: MainScheduler.instance) throttledSearch.bind(to: searchTerm) .disposed(by: disposeBag) // The skip(1) prevents us from clearing the search pasteboard on initial binding. throttledSearch.skip(1).ignoreNil().subscribe(onNext: { term in NSPasteboard(name: .find).clearContents() NSPasteboard(name: .find).setString(term, forType: .string) }).disposed(by: disposeBag) } @objc private func openInNewWindow() { didSelectOpenInNewWindow() } private func updateStyle() { widthConstraint.isActive = style == .corner view.layer?.cornerRadius = style == .corner ? 6 : 0 } override func viewDidAppear() { super.viewDidAppear() guard let pasteboardTerm = NSPasteboard(name: .find).string(forType: .string), pasteboardTerm != searchTerm.value else { return } searchField.stringValue = pasteboardTerm searchTerm.accept(pasteboardTerm) } @objc private func exportTranscript() { didSelectExportTranscript() } }
bsd-2-clause
XUJiahua/AnimatedSwift
AnimatedSwift/ViewController.swift
1
509
// // ViewController.swift // AnimatedSwift // // Created by XuJiahua on 15/12/18. // Copyright © 2015年 hellojohn. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
kstaring/swift
validation-test/compiler_crashers_fixed/01929-swift-constraints-constraintsystem-gettypeofmemberreference.swift
11
641
// 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 // RUN: not %target-swift-frontend %s -parse func b<U { init(true as a<T: T, U) -> String { } struct D : B<b: A, e : d where f, Any) { protocol a { case A<d.endIndex - range: A { return b.e? = Int>([0x31] = Int](bytes: $0) { } var e) } } let g = c(a() -> ()) -> { return ".advance() { class a(
apache-2.0
esttorhe/SwiftSSH2
SwiftSSH2Tests/Supporting Files/SwiftSSH2.playground/Contents.swift
1
473
// Native Frameworks import CFNetwork import Foundation //let hostaddr = "google.com" //let host = CFHostCreateWithName(kCFAllocatorDefault, hostaddr) //host.autorelease() //let error = UnsafeMutablePointer<CFStreamError>.alloc(1) //let tHost: CFHost! = host.takeRetainedValue() //if CFHostStartInfoResolution(tHost, CFHostInfoType.Addresses, error) { // let hbr = UnsafeMutablePointer<Boolean>() // addresses = CFHostGetAddressing(host, hbr) //} // //error.dealloc(1)
mit
Johennes/firefox-ios
UITests/HomePageSettingsUITests.swift
1
5272
/* 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 class HomePageSettingsUITests: KIFTestCase { private var webRoot: String! override func setUp() { super.setUp() webRoot = SimplePageServer.start() UIPasteboard.generalPasteboard().string = " " BrowserUtils.dismissFirstRunUI(tester()) } override func tearDown() { super.tearDown() BrowserUtils.resetToAboutHome(tester()) BrowserUtils.clearPrivateData(tester: tester()) } func testNavigation() { HomePageUtils.navigateToHomePageSettings(tester()) // if we can't find the home paget text view, then this will time out. tester().tapViewWithAccessibilityIdentifier("HomePageSetting") HomePageUtils.navigateFromHomePageSettings(tester()) } func testTyping() { HomePageUtils.navigateToHomePageSettings(tester()) tester().tapViewWithAccessibilityIdentifier("ClearHomePage") XCTAssertEqual("", HomePageUtils.homePageSetting(tester())) tester().tapViewWithAccessibilityIdentifier("HomePageSetting") let webPageString = "http://www.mozilla.com/typing" tester().enterTextIntoCurrentFirstResponder(webPageString) XCTAssertEqual(webPageString, HomePageUtils.homePageSetting(tester())) // check if it's saved HomePageUtils.navigateFromHomePageSettings(tester()) HomePageUtils.navigateToHomePageSettings(tester()) XCTAssertEqual(webPageString, HomePageUtils.homePageSetting(tester())) // teardown. tester().tapViewWithAccessibilityIdentifier("ClearHomePage") HomePageUtils.navigateFromHomePageSettings(tester()) } func testTypingBadURL() { HomePageUtils.navigateToHomePageSettings(tester()) tester().tapViewWithAccessibilityIdentifier("ClearHomePage") XCTAssertEqual("", HomePageUtils.homePageSetting(tester())) tester().tapViewWithAccessibilityIdentifier("HomePageSetting") let webPageString = "not a webpage" tester().enterTextIntoCurrentFirstResponder(webPageString) XCTAssertEqual(webPageString, HomePageUtils.homePageSetting(tester())) // check if it's saved HomePageUtils.navigateFromHomePageSettings(tester()) HomePageUtils.navigateToHomePageSettings(tester()) XCTAssertNotEqual(webPageString, HomePageUtils.homePageSetting(tester())) // teardown. tester().tapViewWithAccessibilityIdentifier("ClearHomePage") HomePageUtils.navigateFromHomePageSettings(tester()) } // This test will fail on simulator func testCurrentPage() { let webPageString = "\(webRoot)/numberedPage.html?page=1" tester().tapViewWithAccessibilityIdentifier("url") tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(webPageString)\n") tester().waitForWebViewElementWithAccessibilityLabel("Page 1") // now go to settings. //HomePageUtils.navigateToHomePageSettings(tester()) tester().waitForAnimationsToFinish() tester().tapViewWithAccessibilityLabel("Menu") // Below call is only needed for the emulator. In emulator, it does not see the settings in the next page tester().swipeViewWithAccessibilityLabel("Set Homepage", inDirection:KIFSwipeDirection.Left) tester().tapViewWithAccessibilityLabel("Settings") tester().tapViewWithAccessibilityIdentifier("HomePageSetting") tester().tapViewWithAccessibilityIdentifier("ClearHomePage") XCTAssertEqual("", HomePageUtils.homePageSetting(tester())) tester().tapViewWithAccessibilityIdentifier("UseCurrentTab") XCTAssertEqual(webPageString, HomePageUtils.homePageSetting(tester())) tester().tapViewWithAccessibilityIdentifier("ClearHomePage") HomePageUtils.navigateFromHomePageSettings(tester()) BrowserUtils.resetToAboutHome(tester()) } func testClipboard() { let webPageString = "https://www.mozilla.org/clipboard" UIPasteboard.generalPasteboard().string = webPageString HomePageUtils.navigateToHomePageSettings(tester()) tester().tapViewWithAccessibilityIdentifier("UseCopiedLink") XCTAssertEqual(webPageString, HomePageUtils.homePageSetting(tester())) tester().tapViewWithAccessibilityIdentifier("ClearHomePage") XCTAssertEqual("", HomePageUtils.homePageSetting(tester())) HomePageUtils.navigateFromHomePageSettings(tester()) } func testDisabledClipboard() { let webPageString = "not a url" UIPasteboard.generalPasteboard().string = webPageString HomePageUtils.navigateToHomePageSettings(tester()) tester().tapViewWithAccessibilityIdentifier("UseCopiedLink") XCTAssertNotEqual(webPageString, HomePageUtils.homePageSetting(tester())) tester().tapViewWithAccessibilityIdentifier("ClearHomePage") XCTAssertEqual("", HomePageUtils.homePageSetting(tester())) HomePageUtils.navigateFromHomePageSettings(tester()) } }
mpl-2.0
practicalswift/swift
test/decl/protocol/conforms/nscoding.swift
4
7588
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s -verify // RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s -disable-nskeyedarchiver-diagnostics 2>&1 | %FileCheck -check-prefix CHECK-NO-DIAGS %s // RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s -dump-ast > %t.ast // RUN: %FileCheck %s < %t.ast // REQUIRES: objc_interop // CHECK-NO-DIAGS-NOT: NSCoding // CHECK-NO-DIAGS-NOT: unstable import Foundation // Top-level classes // CHECK-NOT: class_decl{{.*}}"CodingA"{{.*}}@_staticInitializeObjCMetadata class CodingA : NSObject, NSCoding { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } // okay // Nested classes extension CodingA { // CHECK-NOT: class_decl{{.*}}"NestedA"{{.*}}@_staticInitializeObjCMetadata class NestedA : NSObject, NSCoding { // expected-error{{nested class 'CodingA.NestedA' has an unstable name when archiving via 'NSCoding'}} // expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{3-3=@objc(_TtCC8nscoding7CodingA7NestedA)}} // expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{3-3=@objc(<#prefixed Objective-C class name#>)}} required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } class NestedB : NSObject { // expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{3-3=@objc(_TtCC8nscoding7CodingA7NestedB)}} // expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{3-3=@objc(<#prefixed Objective-C class name#>)}} required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } // CHECK-NOT: class_decl{{.*}}"NestedC"{{.*}}@_staticInitializeObjCMetadata @objc(CodingA_NestedC) class NestedC : NSObject, NSCoding { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } // CHECK-NOT: class_decl{{.*}}"NestedD"{{.*}}@_staticInitializeObjCMetadata @objc(CodingA_NestedD) class NestedD : NSObject { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } } extension CodingA.NestedB: NSCoding { // expected-error{{nested class 'CodingA.NestedB' has an unstable name when archiving via 'NSCoding'}} } extension CodingA.NestedD: NSCoding { // okay } // Generic classes // CHECK-NOT: class_decl{{.*}}"CodingB"{{.*}}@_staticInitializeObjCMetadata class CodingB<T> : NSObject, NSCoding { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } extension CodingB { class NestedA : NSObject, NSCoding { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } } // Fileprivate classes. // CHECK-NOT: class_decl{{.*}}"CodingC"{{.*}}@_staticInitializeObjCMetadata fileprivate class CodingC : NSObject, NSCoding { // expected-error{{fileprivate class 'CodingC' has an unstable name when archiving via 'NSCoding'}} // expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{1-1=@objc(_TtC8nscodingP33_0B4E7641C0BD1F170280EEDD0D0C1F6C7CodingC)}} // expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{1-1=@objc(<#prefixed Objective-C class name#>)}} required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } // Private classes private class CodingD : NSObject, NSCoding { // expected-error{{private class 'CodingD' has an unstable name when archiving via 'NSCoding'}} // expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{1-1=@objc(_TtC8nscodingP33_0B4E7641C0BD1F170280EEDD0D0C1F6C7CodingD)}} // expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{1-1=@objc(<#prefixed Objective-C class name#>)}} required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } // Local classes. func someFunction() { class LocalCoding : NSObject, NSCoding { // expected-error{{local class 'LocalCoding' has an unstable name when archiving via 'NSCoding'}} // expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{3-3=@objc(_TtCF8nscoding12someFunctionFT_T_L_11LocalCoding)}} // expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{3-3=@objc(<#prefixed Objective-C class name#>)}} required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } } // Inherited conformances. // CHECK-NOT: class_decl{{.*}}"CodingE"{{.*}}@_staticInitializeObjCMetadata class CodingE<T> : CodingB<T> { required init(coder: NSCoder) { super.init(coder: coder) } override func encode(coder: NSCoder) { } } // @objc suppressions @objc(TheCodingF) fileprivate class CodingF : NSObject, NSCoding { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } @objc(TheCodingG) private class CodingG : NSObject, NSCoding { required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } extension CodingB { // CHECK-NOT: class_decl{{.*}}"GenericViaScope"{{.*}}@_staticInitializeObjCMetadata @objc(GenericViaScope) // expected-error {{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} class GenericViaScope : NSObject { } } // Inference of @_staticInitializeObjCMetadata. // CHECK-NOT: class_decl{{.*}}"SubclassOfCodingA"{{.*}}@_staticInitializeObjCMetadata class SubclassOfCodingA : CodingA { } // CHECK: class_decl{{.*}}"SubclassOfCodingE"{{.*}}@_staticInitializeObjCMetadata class SubclassOfCodingE : CodingE<Int> { } // Do not warn when simply inheriting from classes that conform to NSCoding. // The subclass may never be serialized. But do still infer static // initialization, just in case. // CHECK-NOT: class_decl{{.*}}"PrivateSubclassOfCodingA"{{.*}}@_staticInitializeObjCMetadata private class PrivateSubclassOfCodingA : CodingA { } // CHECK: class_decl{{.*}}"PrivateSubclassOfCodingE"{{.*}}@_staticInitializeObjCMetadata private class PrivateSubclassOfCodingE : CodingE<Int> { } // But do warn when inherited through a protocol. protocol AlsoNSCoding : NSCoding {} private class CodingH : NSObject, AlsoNSCoding { // expected-error{{private class 'CodingH' has an unstable name when archiving via 'NSCoding'}} // expected-note@-1{{for compatibility with existing archives, use '@objc' to record the Swift 3 runtime name}}{{1-1=@objc(_TtC8nscodingP33_0B4E7641C0BD1F170280EEDD0D0C1F6C7CodingH)}} // expected-note@-2{{for new classes, use '@objc' to specify a unique, prefixed Objective-C runtime name}}{{1-1=@objc(<#prefixed Objective-C class name#>)}} required init(coder: NSCoder) { } func encode(coder: NSCoder) { } } @NSKeyedArchiverClassName( "abc" ) // expected-error {{@NSKeyedArchiverClassName has been removed; use @objc instead}} {{2-26=objc}} {{28-29=}} {{32-33=}} class OldArchiverAttribute: NSObject {} @NSKeyedArchiverEncodeNonGenericSubclassesOnly // expected-error {{@NSKeyedArchiverEncodeNonGenericSubclassesOnly is no longer necessary}} {{1-48=}} class OldArchiverAttributeGeneric<T>: NSObject {} // Don't allow one to write @_staticInitializeObjCMetadata! @_staticInitializeObjCMetadata // expected-error{{unknown attribute '_staticInitializeObjCMetadata'}} class DontAllowStaticInits { }
apache-2.0
montehurd/apps-ios-wikipedia
WMF Framework/NavigationBar.swift
1
32451
@objc public enum NavigationBarDisplayType: Int { case backVisible case largeTitle case modal case hidden } @objc(WMFNavigationBar) public class NavigationBar: SetupView, FakeProgressReceiving, FakeProgressDelegate { fileprivate let statusBarUnderlay: UIView = UIView() fileprivate let titleBar: UIToolbar = UIToolbar() fileprivate let bar: UINavigationBar = UINavigationBar() fileprivate let underBarView: UIView = UIView() // this is always visible below the navigation bar fileprivate let extendedView: UIView = UIView() fileprivate let shadow: UIView = UIView() fileprivate let progressView: UIProgressView = UIProgressView() fileprivate let backgroundView: UIView = UIView() public var underBarViewPercentHiddenForShowingTitle: CGFloat? public var title: String? convenience public init() { self.init(frame: CGRect(x: 0, y: 0, width: 320, height: 44)) } override init(frame: CGRect) { super.init(frame: frame) assert(frame.size != .zero, "Non-zero frame size required to prevent iOS 13 constraint breakage") titleBar.frame = bounds } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public var isAdjustingHidingFromContentInsetChangesEnabled: Bool = true public var isShadowHidingEnabled: Bool = false // turn on/off shadow alpha adjusment public var isTitleShrinkingEnabled: Bool = false public var isInteractiveHidingEnabled: Bool = true // turn on/off any interactive adjustment of bar or view visibility @objc public var isShadowBelowUnderBarView: Bool = false { didSet { updateShadowConstraints() } } public var isShadowShowing: Bool = true { didSet { updateShadowHeightConstraintConstant() } } @objc public var isTopSpacingHidingEnabled: Bool = true @objc public var isBarHidingEnabled: Bool = true @objc public var isUnderBarViewHidingEnabled: Bool = false @objc public var isExtendedViewHidingEnabled: Bool = false @objc public var isExtendedViewFadingEnabled: Bool = true // fade out extended view as it hides public var shouldTransformUnderBarViewWithBar: Bool = false // hide/show underbar view when bar is hidden/shown // TODO: change this stupid name public var allowsUnderbarHitsFallThrough: Bool = false //if true, this only considers underBarView's subviews for hitTest, not self. Use if you need underlying view controller's scroll view to capture scrolling. public var allowsExtendedHitsFallThrough: Bool = false //if true, this only considers extendedView's subviews for hitTest, not self. Use if you need underlying view controller's scroll view to capture scrolling. private var theme = Theme.standard public var shadowColorKeyPath: KeyPath<Theme, UIColor> = \Theme.colors.chromeShadow /// back button presses will be forwarded to this nav controller @objc public weak var delegate: UIViewController? { didSet { updateNavigationItems() } } private var _displayType: NavigationBarDisplayType = .backVisible @objc public var displayType: NavigationBarDisplayType { get { return _displayType } set { guard newValue != _displayType else { return } _displayType = newValue isTitleShrinkingEnabled = _displayType == .largeTitle updateTitleBarConstraints() updateNavigationItems() updateAccessibilityElements() } } private func updateAccessibilityElements() { let titleElement = displayType == .largeTitle ? titleBar : bar accessibilityElements = [titleElement, extendedView, underBarView] } @objc public func updateNavigationItems() { var items: [UINavigationItem] = [] if displayType == .backVisible { if let vc = delegate, let nc = vc.navigationController { var indexToAppend: Int = 0 if let index = nc.viewControllers.firstIndex(of: vc), index > 0 { indexToAppend = index } else if let parentVC = vc.parent, let index = nc.viewControllers.firstIndex(of: parentVC), index > 0 { indexToAppend = index } if indexToAppend > 0 { items.append(nc.viewControllers[indexToAppend].navigationItem) } } } if let item = delegate?.navigationItem { items.append(item) } if displayType == .largeTitle, let navigationItem = items.last { configureTitleBar(with: navigationItem) } else { bar.setItems([], animated: false) bar.setItems(items, animated: false) } apply(theme: theme) } private var cachedTitleViewItem: UIBarButtonItem? private var titleView: UIView? private func configureTitleBar(with navigationItem: UINavigationItem) { var titleBarItems: [UIBarButtonItem] = [] titleView = nil if let titleView = navigationItem.titleView { if let cachedTitleViewItem = cachedTitleViewItem { titleBarItems.append(cachedTitleViewItem) } else { let titleItem = UIBarButtonItem(customView: titleView) titleBarItems.append(titleItem) cachedTitleViewItem = titleItem } } else if let title = navigationItem.title { let navigationTitleLabel = UILabel() navigationTitleLabel.text = title navigationTitleLabel.sizeToFit() navigationTitleLabel.font = UIFont.wmf_font(.boldTitle1) titleView = navigationTitleLabel let titleItem = UIBarButtonItem(customView: navigationTitleLabel) titleBarItems.append(titleItem) } titleBarItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)) if let item = navigationItem.leftBarButtonItem { let leftBarButtonItem = barButtonItem(from: item) titleBarItems.append(leftBarButtonItem) } if let item = navigationItem.rightBarButtonItem { let rightBarButtonItem = barButtonItem(from: item) titleBarItems.append(rightBarButtonItem) } titleBar.setItems(titleBarItems, animated: false) } // HAX: barButtonItem that we're getting from the navigationItem will not be shown on iOS 11 so we need to recreate it private func barButtonItem(from item: UIBarButtonItem) -> UIBarButtonItem { let barButtonItem: UIBarButtonItem if let title = item.title { barButtonItem = UIBarButtonItem(title: title, style: item.style, target: item.target, action: item.action) } else if let systemBarButton = item as? SystemBarButton, let systemItem = systemBarButton.systemItem { barButtonItem = SystemBarButton(with: systemItem, target: systemBarButton.target, action: systemBarButton.action) } else if let customView = item.customView { let customViewData = NSKeyedArchiver.archivedData(withRootObject: customView) if let copiedView = NSKeyedUnarchiver.unarchiveObject(with: customViewData) as? UIView { if let button = customView as? UIButton, let copiedButton = copiedView as? UIButton { for target in button.allTargets { guard let actions = button.actions(forTarget: target, forControlEvent: .touchUpInside) else { continue } for action in actions { copiedButton.addTarget(target, action: Selector(action), for: .touchUpInside) } } } barButtonItem = UIBarButtonItem(customView: copiedView) } else { assert(false, "unable to copy custom view") barButtonItem = item } } else if let image = item.image { barButtonItem = UIBarButtonItem(image: image, landscapeImagePhone: item.landscapeImagePhone, style: item.style, target: item.target, action: item.action) } else { assert(false, "barButtonItem must have title OR be of type SystemBarButton OR have image OR have custom view") barButtonItem = item } barButtonItem.isEnabled = item.isEnabled barButtonItem.isAccessibilityElement = item.isAccessibilityElement barButtonItem.accessibilityLabel = item.accessibilityLabel return barButtonItem } private var titleBarHeightConstraint: NSLayoutConstraint! private var underBarViewHeightConstraint: NSLayoutConstraint! private var shadowTopUnderBarViewBottomConstraint: NSLayoutConstraint! private var shadowTopExtendedViewBottomConstraint: NSLayoutConstraint! private var shadowHeightConstraint: NSLayoutConstraint! private var extendedViewHeightConstraint: NSLayoutConstraint! private var titleBarTopConstraint: NSLayoutConstraint! private var barTopConstraint: NSLayoutConstraint! public var barTopSpacing: CGFloat = 0 { didSet { titleBarTopConstraint.constant = barTopSpacing barTopConstraint.constant = barTopSpacing setNeedsLayout() } } var underBarViewTopBarBottomConstraint: NSLayoutConstraint! var underBarViewTopTitleBarBottomConstraint: NSLayoutConstraint! var underBarViewTopBottomConstraint: NSLayoutConstraint! override open func setup() { super.setup() translatesAutoresizingMaskIntoConstraints = false backgroundView.translatesAutoresizingMaskIntoConstraints = false statusBarUnderlay.translatesAutoresizingMaskIntoConstraints = false bar.translatesAutoresizingMaskIntoConstraints = false underBarView.translatesAutoresizingMaskIntoConstraints = false extendedView.translatesAutoresizingMaskIntoConstraints = false progressView.translatesAutoresizingMaskIntoConstraints = false progressView.alpha = 0 shadow.translatesAutoresizingMaskIntoConstraints = false titleBar.translatesAutoresizingMaskIntoConstraints = false addSubview(backgroundView) addSubview(extendedView) addSubview(underBarView) addSubview(bar) addSubview(titleBar) addSubview(progressView) addSubview(statusBarUnderlay) addSubview(shadow) updateAccessibilityElements() bar.delegate = self shadowHeightConstraint = shadow.heightAnchor.constraint(equalToConstant: 0.5) shadowHeightConstraint.priority = .defaultHigh shadow.addConstraint(shadowHeightConstraint) var updatedConstraints: [NSLayoutConstraint] = [] let statusBarUnderlayTopConstraint = topAnchor.constraint(equalTo: statusBarUnderlay.topAnchor) updatedConstraints.append(statusBarUnderlayTopConstraint) let statusBarUnderlayBottomConstraint = safeAreaLayoutGuide.topAnchor.constraint(equalTo: statusBarUnderlay.bottomAnchor) updatedConstraints.append(statusBarUnderlayBottomConstraint) let statusBarUnderlayLeadingConstraint = leadingAnchor.constraint(equalTo: statusBarUnderlay.leadingAnchor) updatedConstraints.append(statusBarUnderlayLeadingConstraint) let statusBarUnderlayTrailingConstraint = trailingAnchor.constraint(equalTo: statusBarUnderlay.trailingAnchor) updatedConstraints.append(statusBarUnderlayTrailingConstraint) titleBarHeightConstraint = titleBar.heightAnchor.constraint(equalToConstant: 44) titleBarHeightConstraint.priority = UILayoutPriority(rawValue: 999) titleBar.addConstraint(titleBarHeightConstraint) titleBarTopConstraint = titleBar.topAnchor.constraint(equalTo: statusBarUnderlay.bottomAnchor, constant: barTopSpacing) let titleBarLeadingConstraint = leadingAnchor.constraint(equalTo: titleBar.leadingAnchor) let titleBarTrailingConstraint = trailingAnchor.constraint(equalTo: titleBar.trailingAnchor) barTopConstraint = bar.topAnchor.constraint(equalTo: statusBarUnderlay.bottomAnchor, constant: barTopSpacing) let barLeadingConstraint = leadingAnchor.constraint(equalTo: bar.leadingAnchor) let barTrailingConstraint = trailingAnchor.constraint(equalTo: bar.trailingAnchor) underBarViewHeightConstraint = underBarView.heightAnchor.constraint(equalToConstant: 0) underBarView.addConstraint(underBarViewHeightConstraint) underBarViewTopBarBottomConstraint = bar.bottomAnchor.constraint(equalTo: underBarView.topAnchor) underBarViewTopTitleBarBottomConstraint = titleBar.bottomAnchor.constraint(equalTo: underBarView.topAnchor) underBarViewTopBottomConstraint = topAnchor.constraint(equalTo: underBarView.topAnchor) let underBarViewLeadingConstraint = leadingAnchor.constraint(equalTo: underBarView.leadingAnchor) let underBarViewTrailingConstraint = trailingAnchor.constraint(equalTo: underBarView.trailingAnchor) extendedViewHeightConstraint = extendedView.heightAnchor.constraint(equalToConstant: 0) extendedView.addConstraint(extendedViewHeightConstraint) let extendedViewTopConstraint = underBarView.bottomAnchor.constraint(equalTo: extendedView.topAnchor) let extendedViewLeadingConstraint = leadingAnchor.constraint(equalTo: extendedView.leadingAnchor) let extendedViewTrailingConstraint = trailingAnchor.constraint(equalTo: extendedView.trailingAnchor) let extendedViewBottomConstraint = extendedView.bottomAnchor.constraint(equalTo: bottomAnchor) let backgroundViewTopConstraint = topAnchor.constraint(equalTo: backgroundView.topAnchor) let backgroundViewLeadingConstraint = leadingAnchor.constraint(equalTo: backgroundView.leadingAnchor) let backgroundViewTrailingConstraint = trailingAnchor.constraint(equalTo: backgroundView.trailingAnchor) let backgroundViewBottomConstraint = extendedView.bottomAnchor.constraint(equalTo: backgroundView.bottomAnchor) let progressViewBottomConstraint = shadow.topAnchor.constraint(equalTo: progressView.bottomAnchor, constant: 1) let progressViewLeadingConstraint = leadingAnchor.constraint(equalTo: progressView.leadingAnchor) let progressViewTrailingConstraint = trailingAnchor.constraint(equalTo: progressView.trailingAnchor) let shadowLeadingConstraint = leadingAnchor.constraint(equalTo: shadow.leadingAnchor) let shadowTrailingConstraint = trailingAnchor.constraint(equalTo: shadow.trailingAnchor) shadowTopExtendedViewBottomConstraint = extendedView.bottomAnchor.constraint(equalTo: shadow.topAnchor) shadowTopUnderBarViewBottomConstraint = underBarView.bottomAnchor.constraint(equalTo: shadow.topAnchor) updatedConstraints.append(contentsOf: [titleBarTopConstraint, titleBarLeadingConstraint, titleBarTrailingConstraint, underBarViewTopTitleBarBottomConstraint, barTopConstraint, barLeadingConstraint, barTrailingConstraint, underBarViewTopBarBottomConstraint, underBarViewTopBottomConstraint, underBarViewLeadingConstraint, underBarViewTrailingConstraint, extendedViewTopConstraint, extendedViewLeadingConstraint, extendedViewTrailingConstraint, extendedViewBottomConstraint, backgroundViewTopConstraint, backgroundViewLeadingConstraint, backgroundViewTrailingConstraint, backgroundViewBottomConstraint, progressViewBottomConstraint, progressViewLeadingConstraint, progressViewTrailingConstraint, shadowTopUnderBarViewBottomConstraint, shadowTopExtendedViewBottomConstraint, shadowLeadingConstraint, shadowTrailingConstraint]) addConstraints(updatedConstraints) updateTitleBarConstraints() updateShadowConstraints() updateShadowHeightConstraintConstant() setNavigationBarPercentHidden(0, underBarViewPercentHidden: 0, extendedViewPercentHidden: 0, topSpacingPercentHidden: 0, animated: false) } public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateShadowHeightConstraintConstant() } private func updateShadowHeightConstraintConstant() { guard traitCollection.displayScale > 0 else { return } if !isShadowShowing { shadowHeightConstraint.constant = 0 } else { shadowHeightConstraint.constant = 1.0 / traitCollection.displayScale } } fileprivate var _topSpacingPercentHidden: CGFloat = 0 @objc public var topSpacingPercentHidden: CGFloat { get { return _topSpacingPercentHidden } set { setNavigationBarPercentHidden(_navigationBarPercentHidden, underBarViewPercentHidden: _underBarViewPercentHidden, extendedViewPercentHidden: _extendedViewPercentHidden, topSpacingPercentHidden: newValue, animated: false) } } fileprivate var _navigationBarPercentHidden: CGFloat = 0 @objc public var navigationBarPercentHidden: CGFloat { get { return _navigationBarPercentHidden } set { setNavigationBarPercentHidden(newValue, underBarViewPercentHidden: _underBarViewPercentHidden, extendedViewPercentHidden: _extendedViewPercentHidden, topSpacingPercentHidden: _topSpacingPercentHidden, animated: false) } } private var _underBarViewPercentHidden: CGFloat = 0 @objc public var underBarViewPercentHidden: CGFloat { get { return _underBarViewPercentHidden } set { setNavigationBarPercentHidden(_navigationBarPercentHidden, underBarViewPercentHidden: newValue, extendedViewPercentHidden: _extendedViewPercentHidden, topSpacingPercentHidden: _topSpacingPercentHidden, animated: false) } } fileprivate var _extendedViewPercentHidden: CGFloat = 0 @objc public var extendedViewPercentHidden: CGFloat { get { return _extendedViewPercentHidden } set { setNavigationBarPercentHidden(_navigationBarPercentHidden, underBarViewPercentHidden: _underBarViewPercentHidden, extendedViewPercentHidden: newValue, topSpacingPercentHidden: _topSpacingPercentHidden, animated: false) } } @objc dynamic public var visibleHeight: CGFloat = 0 @objc dynamic public var insetTop: CGFloat = 0 @objc public var hiddenHeight: CGFloat = 0 public var shadowAlpha: CGFloat { get { return shadow.alpha } set { shadow.alpha = newValue } } @objc public func setNavigationBarPercentHidden(_ navigationBarPercentHidden: CGFloat, underBarViewPercentHidden: CGFloat, extendedViewPercentHidden: CGFloat, topSpacingPercentHidden: CGFloat, shadowAlpha: CGFloat = -1, animated: Bool, additionalAnimations: (() -> Void)? = nil) { if (animated) { layoutIfNeeded() } if isTopSpacingHidingEnabled { _topSpacingPercentHidden = topSpacingPercentHidden } if isBarHidingEnabled { _navigationBarPercentHidden = navigationBarPercentHidden } if isUnderBarViewHidingEnabled { _underBarViewPercentHidden = underBarViewPercentHidden } if isExtendedViewHidingEnabled { _extendedViewPercentHidden = extendedViewPercentHidden } setNeedsLayout() //print("nb: \(navigationBarPercentHidden) ev: \(extendedViewPercentHidden)") let applyChanges = { let changes = { if shadowAlpha >= 0 { self.shadowAlpha = shadowAlpha } if (animated) { self.layoutIfNeeded() } additionalAnimations?() } if animated { UIView.animate(withDuration: 0.2, animations: changes) } else { changes() } } if let underBarViewPercentHiddenForShowingTitle = self.underBarViewPercentHiddenForShowingTitle { UIView.animate(withDuration: 0.2, animations: { self.delegate?.title = underBarViewPercentHidden >= underBarViewPercentHiddenForShowingTitle ? self.title : nil }, completion: { (_) in applyChanges() }) } else { applyChanges() } } private func updateTitleBarConstraints() { let isUsingTitleBarInsteadOfNavigationBar = displayType == .largeTitle underBarViewTopTitleBarBottomConstraint.isActive = isUsingTitleBarInsteadOfNavigationBar underBarViewTopBarBottomConstraint.isActive = !isUsingTitleBarInsteadOfNavigationBar && displayType != .hidden underBarViewTopBottomConstraint.isActive = displayType == .hidden bar.isHidden = isUsingTitleBarInsteadOfNavigationBar || displayType == .hidden titleBar.isHidden = !isUsingTitleBarInsteadOfNavigationBar || displayType == .hidden updateBarTopSpacing() setNeedsUpdateConstraints() } public override func safeAreaInsetsDidChange() { super.safeAreaInsetsDidChange() updateBarTopSpacing() } // collapse bar top spacing if there's no status bar private func updateBarTopSpacing() { guard displayType == .largeTitle else { barTopSpacing = 0 return } let isSafeAreaInsetsTopGreaterThanZero = safeAreaInsets.top > 0 barTopSpacing = isSafeAreaInsetsTopGreaterThanZero ? 30 : 0 titleBarHeightConstraint.constant = isSafeAreaInsetsTopGreaterThanZero ? 44 : 32 // it doesn't seem like there's a way to force update of bar metrics - as it stands the bar height gets stuck in whatever mode the app was launched in } private func updateShadowConstraints() { shadowTopUnderBarViewBottomConstraint.isActive = isShadowBelowUnderBarView shadowTopExtendedViewBottomConstraint.isActive = !isShadowBelowUnderBarView setNeedsUpdateConstraints() } var barHeight: CGFloat { return (displayType == .largeTitle ? titleBar.frame.height : bar.frame.height) } var underBarViewHeight: CGFloat { return underBarView.frame.size.height } var extendedViewHeight: CGFloat { return extendedView.frame.size.height } var topSpacingHideableHeight: CGFloat { return isTopSpacingHidingEnabled ? barTopSpacing : 0 } var barHideableHeight: CGFloat { return isBarHidingEnabled ? barHeight : 0 } var underBarViewHideableHeight: CGFloat { return isUnderBarViewHidingEnabled ? underBarViewHeight : 0 } var extendedViewHideableHeight: CGFloat { return isExtendedViewHidingEnabled ? extendedViewHeight : 0 } var hideableHeight: CGFloat { return topSpacingHideableHeight + barHideableHeight + underBarViewHideableHeight + extendedViewHideableHeight } public override func layoutSubviews() { super.layoutSubviews() let navigationBarPercentHidden = _navigationBarPercentHidden let extendedViewPercentHidden = _extendedViewPercentHidden let underBarViewPercentHidden = _underBarViewPercentHidden let topSpacingPercentHidden = safeAreaInsets.top > 0 ? _topSpacingPercentHidden : 1 // treat top spacing as hidden if there's no status bar so that the title is smaller let underBarViewHeight = underBarView.frame.height let barHeight = self.barHeight let extendedViewHeight = extendedView.frame.height visibleHeight = statusBarUnderlay.frame.size.height + barHeight * (1.0 - navigationBarPercentHidden) + extendedViewHeight * (1.0 - extendedViewPercentHidden) + underBarViewHeight * (1.0 - underBarViewPercentHidden) + (barTopSpacing * (1.0 - topSpacingPercentHidden)) let spacingTransformHeight = barTopSpacing * topSpacingPercentHidden let barTransformHeight = barHeight * navigationBarPercentHidden + spacingTransformHeight let extendedViewTransformHeight = extendedViewHeight * extendedViewPercentHidden let underBarTransformHeight = underBarViewHeight * underBarViewPercentHidden hiddenHeight = barTransformHeight + extendedViewTransformHeight + underBarTransformHeight let barTransform = CGAffineTransform(translationX: 0, y: 0 - barTransformHeight) let barScaleTransform = CGAffineTransform(scaleX: 1.0 - navigationBarPercentHidden * navigationBarPercentHidden, y: 1.0 - navigationBarPercentHidden * navigationBarPercentHidden) self.bar.transform = barTransform self.titleBar.transform = barTransform if isTitleShrinkingEnabled { let titleScale: CGFloat = 1.0 - 0.2 * topSpacingPercentHidden self.titleView?.transform = CGAffineTransform(scaleX: titleScale, y: titleScale) } for subview in self.bar.subviews { for subview in subview.subviews { subview.transform = barScaleTransform } } self.bar.alpha = min(backgroundAlpha, (1.0 - 2.0 * navigationBarPercentHidden).wmf_normalizedPercentage) self.titleBar.alpha = self.bar.alpha let totalTransform = CGAffineTransform(translationX: 0, y: 0 - hiddenHeight) self.backgroundView.transform = totalTransform let underBarTransform = CGAffineTransform(translationX: 0, y: 0 - barTransformHeight - underBarTransformHeight) self.underBarView.transform = underBarTransform self.underBarView.alpha = 1.0 - underBarViewPercentHidden self.extendedView.transform = totalTransform if isExtendedViewFadingEnabled { self.extendedView.alpha = min(backgroundAlpha, 1.0 - extendedViewPercentHidden) } else { self.extendedView.alpha = CGFloat(1).isLessThanOrEqualTo(extendedViewPercentHidden) ? 0 : backgroundAlpha } self.progressView.transform = isShadowBelowUnderBarView ? underBarTransform : totalTransform self.shadow.transform = isShadowBelowUnderBarView ? underBarTransform : totalTransform // HAX: something odd going on with iOS 11... insetTop = backgroundView.frame.origin.y if #available(iOS 12, *) { insetTop = visibleHeight } } @objc public func setProgressHidden(_ hidden: Bool, animated: Bool) { let changes = { self.progressView.alpha = min(hidden ? 0 : 1, self.backgroundAlpha) } if animated { UIView.animate(withDuration: 0.2, animations: changes) } else { changes() } } @objc public func setProgress(_ progress: Float, animated: Bool) { progressView.setProgress(progress, animated: animated) } @objc public var progress: Float { get { return progressView.progress } set { progressView.progress = newValue } } @objc public func addExtendedNavigationBarView(_ view: UIView) { guard extendedView.subviews.first == nil else { return } extendedViewHeightConstraint.isActive = false extendedView.wmf_addSubviewWithConstraintsToEdges(view) } @objc public func removeExtendedNavigationBarView() { guard let subview = extendedView.subviews.first else { return } subview.removeFromSuperview() extendedViewHeightConstraint.isActive = true } @objc public func addUnderNavigationBarView(_ view: UIView) { guard underBarView.subviews.first == nil else { return } underBarViewHeightConstraint.isActive = false underBarView.wmf_addSubviewWithConstraintsToEdges(view) } @objc public func removeUnderNavigationBarView() { guard let subview = underBarView.subviews.first else { return } subview.removeFromSuperview() underBarViewHeightConstraint.isActive = true } @objc public override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { if allowsUnderbarHitsFallThrough && underBarView.frame.contains(point) && !bar.frame.contains(point) { for subview in underBarView.subviews { let convertedPoint = self.convert(point, to: subview) if subview.point(inside: convertedPoint, with: event) { return true } } return false } if allowsExtendedHitsFallThrough && extendedView.frame.contains(point) && !bar.frame.contains(point) { for subview in extendedView.subviews { let convertedPoint = self.convert(point, to: subview) if subview.point(inside: convertedPoint, with: event) { return true } } return false } return point.y <= visibleHeight } public var backgroundAlpha: CGFloat = 1 { didSet { statusBarUnderlay.alpha = backgroundAlpha backgroundView.alpha = backgroundAlpha bar.alpha = backgroundAlpha titleBar.alpha = backgroundAlpha extendedView.alpha = backgroundAlpha if backgroundAlpha < progressView.alpha { progressView.alpha = backgroundAlpha } } } } extension NavigationBar: Themeable { public func apply(theme: Theme) { self.theme = theme backgroundColor = .clear statusBarUnderlay.backgroundColor = theme.colors.paperBackground backgroundView.backgroundColor = theme.colors.paperBackground titleBar.setBackgroundImage(theme.navigationBarBackgroundImage, forToolbarPosition: .any, barMetrics: .default) titleBar.isTranslucent = false titleBar.tintColor = theme.colors.chromeText titleBar.setShadowImage(theme.navigationBarShadowImage, forToolbarPosition: .any) titleBar.barTintColor = theme.colors.chromeBackground if let items = titleBar.items { for item in items { if let label = item.customView as? UILabel { label.textColor = theme.colors.chromeText } else if item.image == nil { item.tintColor = theme.colors.link } } } bar.setBackgroundImage(theme.navigationBarBackgroundImage, for: .default) bar.titleTextAttributes = theme.navigationBarTitleTextAttributes bar.isTranslucent = false bar.barTintColor = theme.colors.chromeBackground bar.shadowImage = theme.navigationBarShadowImage bar.tintColor = theme.colors.chromeText extendedView.backgroundColor = .clear underBarView.backgroundColor = .clear shadow.backgroundColor = theme[keyPath: shadowColorKeyPath] progressView.progressViewStyle = .bar progressView.trackTintColor = .clear progressView.progressTintColor = theme.colors.link } } extension NavigationBar: UINavigationBarDelegate { public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool { delegate?.navigationController?.popViewController(animated: true) return false } }
mit
STShenZhaoliang/iOS-GuidesAndSampleCode
精通Swift设计模式/Chapter 10/AbstractFactory/AbstractFactory/Floorplans.swift
1
472
protocol Floorplan { var seats:Int { get } var enginePosition:EngineOption { get }; } enum EngineOption : String { case FRONT = "Front"; case MID = "Mid"; } class ShortFloorplan: Floorplan { var seats = 2; var enginePosition = EngineOption.MID } class StandardFloorplan: Floorplan { var seats = 4; var enginePosition = EngineOption.FRONT; } class LongFloorplan: Floorplan { var seats = 8; var enginePosition = EngineOption.FRONT; }
mit
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/MaskShapeLayerVC.swift
1
6364
// // MaskShapeLayerVC.swift // UIScrollViewDemo // // Created by xiAo_Ju on 2018/10/27. // Copyright © 2018 伯驹 黄. All rights reserved. // import UIKit class MaskShapeLayerVC: UIViewController { var draftShapeLayer : CAShapeLayer? var squareShapeLayer : CAShapeLayer? var lineShapeLayer : CAShapeLayer? var shapeLayer : CAShapeLayer? let width : CGFloat = 240 let height : CGFloat = 240 lazy var containerLayer : CALayer = { () -> CALayer in let containerLayer = CALayer() containerLayer.frame = CGRect(x: self.view.center.x - self.width / 2, y: self.view.center.y - self.height / 2, width: self.width, height: self.height) self.view.layer.addSublayer(containerLayer) return containerLayer }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white // drawHeader() drawMask() } // MARK: - 绘制蒙版 private func drawMask() { let bgView = UIImageView(image: UIImage(named: "007.jpg")) bgView.frame = view.bounds view.addSubview(bgView) let maskView = UIView(frame: view.bounds) maskView.backgroundColor = UIColor.red.withAlphaComponent(0.3) maskView.alpha = 0.8 // view.addSubview(maskView) let bpath = UIBezierPath(roundedRect: CGRect(x: 10, y: 10, width: view.bounds.width - 20, height: view.bounds.height - 20), cornerRadius: 15) let circlePath = UIBezierPath(arcCenter: view.center, radius: 100, startAngle: 0, endAngle: .pi * 2, clockwise: false) bpath.append(circlePath) let shapeLayer = CAShapeLayer() shapeLayer.strokeColor = UIColor.red.cgColor shapeLayer.fillColor = UIColor.blue.cgColor shapeLayer.path = bpath.cgPath // view.layer.addSublayer(shapeLayer) bgView.layer.mask = shapeLayer } // MARK: - 图形动画 private func drawHeader() { // let draftPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: width, height: height), cornerRadius: 5) let cornerRadius : CGFloat = 20 let draftPath = UIBezierPath() draftPath.move(to: CGPoint(x: width - cornerRadius, y: 0)) draftPath.addLine(to: CGPoint(x: cornerRadius, y: 0)) draftPath.addArc(withCenter: CGPoint(x: cornerRadius, y: cornerRadius), radius: cornerRadius, startAngle: -.pi/2, endAngle: .pi, clockwise: false) draftPath.addLine(to: CGPoint(x: 0, y: height - cornerRadius)) draftPath.addArc(withCenter: CGPoint(x: cornerRadius, y: height - cornerRadius), radius: cornerRadius, startAngle: .pi, endAngle: .pi/2, clockwise: false) draftPath.addLine(to: CGPoint(x: width - cornerRadius, y: height)) draftPath.addArc(withCenter: CGPoint(x: width - cornerRadius, y: height - cornerRadius), radius: cornerRadius, startAngle: .pi/2, endAngle: 0, clockwise: false) draftPath.addLine(to: CGPoint(x: width, y: cornerRadius)) draftPath.addArc(withCenter: CGPoint(x: width - cornerRadius, y: cornerRadius), radius: cornerRadius, startAngle: 0, endAngle: -.pi/2, clockwise: false) let margin : CGFloat = 24 let smallSquareWH : CGFloat = 84 let squarePath = UIBezierPath(roundedRect: CGRect(x: margin, y: margin, width: smallSquareWH, height: smallSquareWH), cornerRadius: 2) let shortLineLeft : CGFloat = margin * 2 + smallSquareWH let shortLineRight : CGFloat = width - margin let space : CGFloat = smallSquareWH / 2 - 3 let linePath = UIBezierPath() for i in 0 ..< 3 { linePath.move(to: CGPoint(x: shortLineLeft, y: margin + 2 + space * CGFloat(i))) linePath.addLine(to: CGPoint(x: shortLineRight, y: margin + 2 + space * CGFloat(i))) } let longLineRight = width - margin for i in 0 ..< 3 { linePath.move(to: CGPoint(x: margin, y: margin * 2 + 2 + smallSquareWH + space * CGFloat(i))) linePath.addLine(to: CGPoint(x: longLineRight, y: margin * 2 + 2 + smallSquareWH + space * CGFloat(i))) } self.draftShapeLayer = CAShapeLayer() self.draftShapeLayer!.frame = CGRect(x: 0, y: 0, width: width, height: height) setupShapeLayer(shapeLayer: self.draftShapeLayer!, path: draftPath.cgPath) self.squareShapeLayer = CAShapeLayer() self.squareShapeLayer!.frame = CGRect(x: 0, y: 0, width: smallSquareWH, height: smallSquareWH) setupShapeLayer(shapeLayer: self.squareShapeLayer!, path: squarePath.cgPath) self.lineShapeLayer = CAShapeLayer() self.lineShapeLayer!.frame = CGRect(x: 0, y: 0, width: width, height: height) setupShapeLayer(shapeLayer: self.lineShapeLayer!, path: linePath.cgPath) addSlider() } private func addSlider() { let slider = UISlider(frame: CGRect(x: 20, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width - 40, height: 10)) slider.minimumValue = 0 slider.maximumValue = 1 slider.addTarget(self, action: #selector(sliderValueChanged(sender:)), for: UIControl.Event.valueChanged) view.addSubview(slider) } @objc private func sliderValueChanged(sender: UISlider) { guard let draftShapeLayer = self.draftShapeLayer else { return } guard let squareShapeLayer = self.squareShapeLayer else { return } guard let lineShapeLayer = self.lineShapeLayer else { return } draftShapeLayer.strokeEnd = CGFloat(sender.value) squareShapeLayer.strokeEnd = CGFloat(sender.value) lineShapeLayer.strokeEnd = CGFloat(sender.value) } // MARK: - 辅助方法 private func setupShapeLayer(shapeLayer : CAShapeLayer, path : CGPath) { shapeLayer.path = path shapeLayer.strokeColor = UIColor.gray.cgColor shapeLayer.fillColor = UIColor.white.cgColor shapeLayer.lineWidth = 2 shapeLayer.strokeStart = 0 shapeLayer.strokeEnd = 0 containerLayer.addSublayer(shapeLayer) } }
mit
zhangdadi/SwiftHttp
HDNetwork/HDNetwork/Network/HDNetDataThread.swift
1
6685
// // HDNetDataThread.swift // HDNetFramework // // Created by 张达棣 on 14-8-3. // Copyright (c) 2014年 HD. All rights reserved. // // 若发现bug请致电:z_dadi@163.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 /** * 全局的数据线程单例 */ struct DataThreadInitSingleton{ static func shareInstance() -> HDNetDataThread { struct Singleton{ static var predicate: dispatch_once_t = 0 static var instance: HDNetDataThread? } dispatch_once(&Singleton.predicate, { func gDataThreadInit() -> HDNetDataThread { var len: UInt = 0 var ncpu: UInt = 0 len = UInt(sizeofValue(ncpu)) // sysctlbyname("hw.ncpu", &ncpu, &len, nil, 0) if ncpu <= 1 { debugPrintln("network in main thread") return HDNetDataThread() } else { debugPrintln("network multithreaded") return HDNetDataThread() } } Singleton.instance = gDataThreadInit() }) return Singleton.instance! } //判断当前线程是否为数据线程 static func isDataThread() -> Bool { return NSThread.currentThread().isEqual(DataThreadInitSingleton.shareInstance()) } } //________________________________________________________________________________________ /** * 全局队列 */ struct QueueSingleton { static func shareInstance() -> HDNetRequestQueue { struct Singleton{ static var predicate: dispatch_once_t = 0 static var instance: HDNetRequestQueue? = nil } dispatch_once(&Singleton.predicate, { Singleton.instance = HDNetRequestQueue() }) return Singleton.instance! } } //_________________________________________________________________ /** * 数据线程 */ class HDNetDataThread: NSThread { typealias Call = () -> () typealias CallParm = (i: Int) -> () var onCall: Call? { set { _callList.append(newValue!) } get { return nil } } func setOnCallParm(callParm: CallParm, parm: Int) { _callParmList.append(callParm) _parmList.append(parm); } var _callList = [Call]() var _callParmList = [CallParm]() var _parmList = [Int]() init(sender: HDNetDataThread) { } convenience override init() { self.init(sender: self) self.start() } override func main() { // 数据线程优先级调低(界面线程应该是0.5) NSThread.setThreadPriority(0.3) var i = 0 while true { if _callList.count > 0 { _callList[0]() let v = _callList.removeAtIndex(0) } if _callParmList.count > 0 { _callParmList[0](i: _parmList[0]) let v = _callList.removeAtIndex(0) let p = _parmList.removeAtIndex(0); } NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as! NSDate) } } } //_________________________________________________________________ /** * 多点回调 */ //class HDNetCallNode: NSObject { // weak var _data: HDNetCtrlDelegate? // var _next: HDNetCallNode? // // func push(data: HDNetCtrlDelegate) { // pop(data) // var temp = self // while temp._next != nil { // temp = temp._next! // } // var newNode = HDNetCallNode() // newNode._data = data // temp._next = newNode // } // // func pop(index:Int) { // var lastTemp: HDNetCallNode? = self // var temp: HDNetCallNode? = self._next // var i = 0 // while lastTemp?._next != nil && i <= index { // if i == index { // lastTemp?._next = temp?._next // temp?._data = nil // temp = nil // } // lastTemp = lastTemp?._next // temp = temp?._next // ++i // } // } // // func pop(data: HDNetCtrlDelegate) { // var lastTemp: HDNetCallNode? = self // var temp: HDNetCallNode? = self._next // // while lastTemp?._next != nil { // if data === temp?._data { // lastTemp?._next = temp?._next // temp?._data = nil // temp = nil // } // lastTemp = lastTemp?._next // temp = temp?._next // } // } // // func callUpdate(sender: HDNetDataModel) { // var temp = self // var i = 0 // while temp._next != nil { // temp = temp._next! // if temp._data != nil { // temp._data?.netCtrlUpdate?(sender) // } else { // pop(i) // } // ++i // } // } // // func callProgress(sender: HDNetDataModel) { // var temp = self // while temp._next != nil { // temp = temp._next! // temp._data?.netCtrlProgress?(sender) // } // } // // func _find(data:HDNetCtrlDelegate) -> Bool { // var temp = self // while temp._next != nil { // temp = temp._next! // if temp._data === data { // return true // } // } // return false // } //}
mit
realami/Msic
weekTwo/weekTwo/Views/ActionTableViewCell.swift
1
310
// // ActionTableViewCell.swift // weekTwo // // Created by Cyan on 28/10/2017. // Copyright © 2017 Cyan. All rights reserved. // import UIKit class ActionTableViewCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
mit
PezHead/tiny-tennis-scoreboard
TableTennisAPI/TableTennisAPI/ImageStore.swift
1
2963
// // ImageStore.swift // Tiny Tennis // // Created by David Bireta on 10/20/16. // Copyright © 2016 David Bireta. All rights reserved. // /// Provides access to all images. /// Currently this is just champion avatars. class ImageStore { static let shared = ImageStore() /// Upon initialization, an "Images" directory will be created. fileprivate init() { if let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { let imagesDirPath = documentsPath.appendingPathComponent("Images", isDirectory: true) do { // Per Apple recommendations, always try to create the folder instead of checking if it already exists first. try FileManager.default.createDirectory(at: imagesDirPath, withIntermediateDirectories: false, attributes: nil) } catch let error as NSError { // Ignore "directory already exists" error if error.code != 516 { print("Error creating /Images directory: \(error)") } } } } /// Returns an avatar for a given champion. This will look for images in the following order: /// * Check to see if a downloaded image has been cached in the 'Documents/Images' directory /// * Check to see if there is an image in the bundle matching the champion's nickname /// * Attempt to download (and subsequently cache) and image using the `avatar` property /// /// - parameter champion: The `Champion` for which the image is being requested. /// /// - returns: Matching avatar image if found, else returns the "default.png" image. func avatar(for champion: Champion) -> UIImage { var avatarImage = UIImage(named: "default")! if let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { let imagesDirPath = documentsPath.appendingPathComponent("Images", isDirectory: true) let imagePath = imagesDirPath.appendingPathComponent("\(champion.id).jpg") if let image = UIImage(contentsOfFile: imagePath.path) { avatarImage = image } else if champion.avatar == "" { if let lastName = champion.lastName, let image = UIImage(named: lastName) { avatarImage = image } } else if let avatarURL = URL(string: champion.avatar), let imageData = try? Data(contentsOf: avatarURL), let image = UIImage(data: imageData) { // "Cache" it to disk do { try imageData.write(to: imagePath, options: .atomic) } catch let error { print("Error caching image to disk: \(error)") } avatarImage = image } } return avatarImage } }
mit
embryoconcepts/TIY-Assignments
03a -- MissionBriefing/MissionBriefing/MissionBriefingViewController.swift
1
3153
// // ViewController.swift // MissionBriefing // // Created by Jennifer Hamilton on 10/7/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit class MissionBriefingViewController: UIViewController, UITextFieldDelegate { // Place IBOutlet properties below @IBOutlet var nameTextField: UITextField! @IBOutlet var passwordTextField: UITextField! @IBOutlet var authenticateButton: UIButton! @IBOutlet var greetingLabel: UILabel! @IBOutlet var missionTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() // # 3 nameTextField.text = "" passwordTextField.text = "" greetingLabel.text = "" missionTextView.text = "" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Action Handlers @IBAction func buttonTapped(sender: UIButton) { authenticateAgent() } // MARK: - UITextField Delegate func textFieldShouldReturn(textField: UITextField) -> Bool { return authenticateAgent() } // MARK: - Private func authenticateAgent() -> Bool { var rc = false if nameTextField.text != "" { let name = nameTextField.text // #4 if passwordTextField.text != "" { rc = true nameTextField.resignFirstResponder() let nameComponents = name!.characters.split(" ").map { String($0) } let lastName = nameComponents[1].capitalizedString // #5 greetingLabel.text = "Good evening, Agent \(lastName)" // #6 FIXME: fix, not displaying missionTextView.text = "This mission will be an arduous one, fraught with peril. You will cover much strange and unfamiliar territory. Should you choose to accept this mission, Agent \(lastName), you will certainly be disavowed, but you will be doing your country a great service. This message will self destruct in 5 seconds." // #7 view.backgroundColor = UIColor(red: 0.585, green: 0.78, blue: 0.188, alpha: 1.0) } else { greetingLabel.text = "Please enter your password." agentFailureToAuthenticate() } } else { // #8 greetingLabel.text = "Please enter your agent name." agentFailureToAuthenticate() } return rc } func agentFailureToAuthenticate() { view.backgroundColor = UIColor(red: 0.78, green: 0.188, blue: 0.188, alpha: 1.0) // TODO: self-destruct sequence } } // 6. The mission briefing textview needs to be populated with the briefing from HQ, but it must also include the last // name of the agent that logged in. Perhaps you could use the text in the textfield to get the agent's last name. // How would you inject that last name into the paragraph of the mission briefing?
cc0-1.0
omarojo/MyC4FW
Pods/C4/C4/UI/Layer.swift
2
4245
// Copyright © 2014 C4 // // 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 QuartzCore /// A subclass of CALayer that has a rotation property. public class Layer: CALayer { static let rotationKey = "rotation" private var _rotation = 0.0 /// The value of the receiver's current rotation state. /// This value is cumulative, and can represent values beyong +/- π public dynamic var rotation: Double { return _rotation } /// Initializes a new Layer public override init() { super.init() } /// Initializes a new Layer from a specified layer of any other type. /// - parameter layer: Another CALayer public override init(layer: Any) { super.init(layer: layer) if let layer = layer as? Layer { _rotation = layer._rotation } } /// Initializes a new Layer from data in a given unarchiver. /// - parameter coder: An unarchiver object. public required init?(coder: NSCoder) { super.init(coder: coder) } /// Sets a value for a given key. /// - parameter value: The value for the property identified by key. /// - parameter key: The name of one of the receiver's properties public override func setValue(_ value: Any?, forKey key: String) { super.setValue(value, forKey: key) if key == Layer.rotationKey { _rotation = value as? Double ?? 0.0 } } /// This method searches for the given action object of the layer. Actions define dynamic behaviors for a layer. For example, the animatable properties of a layer typically have corresponding action objects to initiate the actual animations. When that property changes, the layer looks for the action object associated with the property name and executes it. You can also associate custom action objects with your layer to implement app-specific actions. /// - parameter key: The identifier of the action. /// - returns: the action object assigned to the specified key. public override func action(forKey key: String) -> CAAction? { if key == Layer.rotationKey { let animation = CABasicAnimation(keyPath: key) animation.configureOptions() if let layer = presentation() { animation.fromValue = layer.value(forKey: key) } return animation } return super.action(forKey: key) } /// Returns a Boolean indicating whether changes to the specified key require the layer to be redisplayed. /// - parameter key: A string that specifies an attribute of the layer. /// - returns: A Boolean indicating whether changes to the specified key require the layer to be redisplayed. public override class func needsDisplay(forKey key: String) -> Bool { if key == Layer.rotationKey { return true } return super.needsDisplay(forKey: key) } /// Reloads the content of this layer. /// Do not call this method directly. public override func display() { guard let presentation = presentation() else { return } setValue(presentation._rotation, forKeyPath: "transform.rotation.z") } }
mit
spark/photon-tinker-ios
Photon-Tinker/PinFunctionView.swift
1
4381
// // Created by Raimundas Sakalauskas on 2019-05-07. // Copyright (c) 2019 Particle. All rights reserved. // import Foundation protocol PinFunctionViewDelegate: class { func pinFunctionSelected(pin: DevicePin, function: DevicePinFunction?) } class PinFunctionView: UIView { private let selectedColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3) private let unselectedColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.15) @IBOutlet var pinLabel:ParticleLabel! @IBOutlet var analogReadButton:ParticleCustomButton! @IBOutlet var analogWriteButton:ParticleCustomButton! @IBOutlet var digitalReadButton:ParticleCustomButton! @IBOutlet var digitalWriteButton:ParticleCustomButton! var pin:DevicePin? weak var delegate:PinFunctionViewDelegate? override func awakeFromNib() { super.awakeFromNib() layer.masksToBounds = false layer.cornerRadius = 5 layer.applySketchShadow(color: UIColor(rgb: 0x000000), alpha: 0.3, x: 0, y: 2, blur: 4, spread: 0) pinLabel.setStyle(font: ParticleStyle.BoldFont, size: ParticleStyle.LargeSize, color: ParticleStyle.PrimaryTextColor) analogReadButton.layer.borderColor = DevicePinFunction.getColor(function: .analogRead).cgColor digitalReadButton.layer.borderColor = DevicePinFunction.getColor(function: .digitalRead).cgColor digitalWriteButton.layer.borderColor = DevicePinFunction.getColor(function: .digitalWrite).cgColor analogWriteButton.layer.borderColor = DevicePinFunction.getColor(function: .analogWriteDAC).cgColor analogReadButton.setTitle(DevicePinFunction.analogRead.getName(), for: .normal) digitalReadButton.setTitle(DevicePinFunction.digitalRead.getName(), for: .normal) digitalWriteButton.setTitle(DevicePinFunction.digitalWrite.getName(), for: .normal) analogWriteButton.setTitle(DevicePinFunction.analogWriteDAC.getName(), for: .normal) setupButton(analogReadButton) setupButton(digitalReadButton) setupButton(digitalWriteButton) setupButton(analogWriteButton) } private func setupButton(_ button: ParticleCustomButton!) { button.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.RegularSize, color: ParticleStyle.PrimaryTextColor) button.layer.cornerRadius = 3 button.layer.borderWidth = 2 button.backgroundColor = UIColor(rgb: 0xFFFFFF) } override func layoutSubviews() { super.layoutSubviews() } func setPin(_ pin: DevicePin?) { self.pin = pin guard let pin = self.pin else { return } pinLabel.text = pin.label analogReadButton.isHidden = true digitalReadButton.isHidden = true digitalWriteButton.isHidden = true analogWriteButton.isHidden = true if pin.functions.contains(.analogRead) { analogReadButton.isHidden = false } if pin.functions.contains(.digitalRead) { digitalReadButton.isHidden = false } if pin.functions.contains(.digitalWrite) { digitalWriteButton.isHidden = false } if (pin.functions.contains(.analogWritePWM) || pin.functions.contains(.analogWriteDAC)) { analogWriteButton.isHidden = false if pin.functions.contains(.analogWriteDAC) { analogWriteButton.layer.borderColor = DevicePinFunction.getColor(function: .analogWriteDAC).cgColor } else { analogWriteButton.layer.borderColor = DevicePinFunction.getColor(function: .analogWritePWM).cgColor } } pinLabel.sizeToFit() } @IBAction func functionSelected(_ sender: UIButton) { var function:DevicePinFunction? = nil if sender == analogReadButton { function = .analogRead } else if sender == analogWriteButton { if self.pin!.functions.contains(.analogWriteDAC) { function = .analogWriteDAC } else { function = .analogWritePWM } } else if sender == digitalReadButton { function = .digitalRead } else if sender == digitalWriteButton { function = .digitalWrite } self.delegate?.pinFunctionSelected(pin: self.pin!, function: function) } }
apache-2.0
wagnersouz4/replay
Replay/Replay/Components/Grid/Source/Views/GridTableViewCell.swift
1
2504
// // GridTableViewCell.swift // Replay // // Created by Wagner Souza on 28/03/17. // Copyright © 2017 Wagner Souza. All rights reserved. // import UIKit enum GridOrientation { case portrait, landscape } class GridTableViewCell: UITableViewCell { fileprivate var collectionView: GridCollectionView! fileprivate var layout: UICollectionViewFlowLayout! fileprivate var orientation: GridOrientation override func awakeFromNib() { super.awakeFromNib() } init(reuseIdentifier: String?, orientation: GridOrientation) { self.orientation = orientation super.init(style: .default, reuseIdentifier: reuseIdentifier) setupCollectionView() } override func layoutSubviews() { super.layoutSubviews() collectionView.frame = contentView.bounds } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: Collection View private extension GridTableViewCell { func setupCollectionView() { layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal /// Initializing the colletionView collectionView = GridCollectionView(frame: .zero, collectionViewLayout: layout) collectionView.register(GridCollectionViewCell.nib, forCellWithReuseIdentifier: GridCollectionViewCell.identifier) /// ColectionView Custom settings collectionView.backgroundColor = .background collectionView.isPrefetchingEnabled = true collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.isDirectionalLockEnabled = true collectionView.decelerationRate = UIScrollViewDecelerationRateFast contentView.addSubview(collectionView) } } // MARK: Setting collection data source, delegate and section extension GridTableViewCell { /// This method will be called in the TableViewController's tableView(_:willDisplay:forRowAt:) func setCollectionView(dataSource: UICollectionViewDataSource, delegate: UICollectionViewDelegate?, section: Int) { if collectionView.section == nil { collectionView.section = section } if collectionView.dataSource == nil { collectionView.dataSource = dataSource } if collectionView.delegate == nil { collectionView.delegate = delegate } } }
mit
alikaragoz/DaisyChain
Examples/Showcase/Showcase/BrokenChainViewController.swift
1
1383
// // BrokenChainViewController.swift // Showcase // // Created by Ali Karagoz on 16/12/15. // Copyright © 2015 Ali Karagoz. All rights reserved. // import Foundation import UIKit import DaisyChain class BrokenChainViewController: UIViewController { @IBOutlet weak var shape: UIView! @IBOutlet weak var centerYConstraint: NSLayoutConstraint! let chain = DaisyChain() override func viewDidLoad() { super.viewDidLoad() shape.layer.cornerRadius = 50.0 } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.animate() } func animate() { chain.animateWithDuration( 0.6, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.2, options: .CurveEaseInOut, animations: { self.centerYConstraint.constant = 150.0 self.view.layoutIfNeeded() }, completion: nil) chain.animateWithDuration( 0.6, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.2, options: .CurveEaseInOut, animations: { self.centerYConstraint.constant = -150.0 self.view.layoutIfNeeded() }, completion: { _ in self.animate() }) } @IBAction func breakChain(sender: UIButton) { chain.broken = true shape.backgroundColor = UIColor.redColor() } }
mit
DonMag/ScratchPad
Swift3/scratchy/XC8.playground/Pages/Arrays.xcplaygroundpage/Contents.swift
1
1890
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) var imageList = ["flower", "balloon", "cat", "dog"] var t = imageList[2] var i = imageList.count // two-dimensional array // should be your Event object... mArray = [[Event]]() var mArray = [[String]]() // simulate your allEvents array var allEvents = ["a 1", "a 2", "a 3", "b 1", "b 2", "c 1", "c 2", "d 1", "d 2", "d 3", "d 4"] // get first "Day" // yours will be something like: currentDay = getDateFrom(allEvents[0]) var currentDay = "\(allEvents[0].characters.first)" // init empty array // yours will be Event objects... currentEvents = [Event]() var currentEvents = [String]() for event in allEvents { // yours will be something like: thisDay = getDateFrom(event) var thisDay = "\(event.characters.first)" if thisDay != currentDay || event == allEvents.last { mArray.append(currentEvents) currentDay = thisDay // reset currentEvents array: currentEvents = [Event]() currentEvents = [String]() } currentEvents.append(event) } print(mArray) mArray = [[String]]() // get first "Day" // yours will be something like: currentDay = getDateFrom(allEvents[0]) currentDay = "\(allEvents[0].characters.first)" // init empty array // yours will be Event objects... currentEvents = [Event]() currentEvents = [String]() for event in allEvents { // yours will be something like: thisDay = getDateFrom(event) var thisDay = "\(event.characters.first)" if thisDay != currentDay { mArray.append(currentEvents) currentDay = thisDay // reset currentEvents array: currentEvents = [Event]() currentEvents = [String]() currentEvents.append(event) } else if event == allEvents.last { currentEvents.append(event) mArray.append(currentEvents) } else { currentEvents.append(event) } } print(mArray)
mit
austinzheng/swift
validation-test/compiler_crashers_fixed/28427-swift-lexer-lexstringliteral.swift
65
419
// 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 // RUN: not %target-swift-frontend %s -typecheck struct c:protocol<{"
apache-2.0
austinzheng/swift
validation-test/compiler_crashers_fixed/01582-swift-constraints-solution-computesubstitutions.swift
65
480
// 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 // RUN: not %target-swift-frontend %s -typecheck protocol a { init() { }(T> d<T>Bool) typealias C = e: T! { } } let start = { (a()
apache-2.0
blockchain/My-Wallet-V3-iOS
Modules/Platform/Tests/PlatformUIKitTests/Components/PrefillButtons/PrefillButtonsReducerTests.swift
1
3292
// Copyright © Blockchain Luxembourg S.A. All rights reserved. @testable import PlatformUIKit import BigInt import Combine import ComposableArchitecture import MoneyKit import XCTest final class PrefillButtonsReducerTests: XCTestCase { private var mockMainQueue: ImmediateSchedulerOf<DispatchQueue>! private var testStore: TestStore< PrefillButtonsState, PrefillButtonsState, PrefillButtonsAction, PrefillButtonsAction, PrefillButtonsEnvironment >! private let lastPurchase = FiatValue(amount: 900, currency: .USD) private let maxLimit = FiatValue(amount: 120000, currency: .USD) override func setUpWithError() throws { try super.setUpWithError() mockMainQueue = DispatchQueue.immediate } func test_stateValues() { let state = PrefillButtonsState( baseValue: FiatValue(amount: 1000, currency: .USD), maxLimit: maxLimit ) XCTAssertEqual(state.baseValue, FiatValue(amount: 1000, currency: .USD)) XCTAssertEqual(state.suggestedValues[0], FiatValue(amount: 1000, currency: .USD)) XCTAssertEqual(state.suggestedValues[1], FiatValue(amount: 2000, currency: .USD)) XCTAssertEqual(state.suggestedValues[2], FiatValue(amount: 4000, currency: .USD)) } func test_stateValues_overMaxLimit() { let state = PrefillButtonsState( baseValue: FiatValue(amount: 110000, currency: .USD), maxLimit: maxLimit ) XCTAssertEqual(state.baseValue, FiatValue(amount: 110000, currency: .USD)) XCTAssertEqual(state.suggestedValues[0], FiatValue(amount: 110000, currency: .USD)) XCTAssertEqual(state.suggestedValues.count, 1) } func test_roundingLastPurchase_after_onAppear() { testStore = TestStore( initialState: .init(), reducer: prefillButtonsReducer, environment: PrefillButtonsEnvironment( mainQueue: mockMainQueue.eraseToAnyScheduler(), lastPurchasePublisher: .just(lastPurchase), maxLimitPublisher: .just(maxLimit), onValueSelected: { _ in } ) ) testStore.send(.onAppear) let expected = FiatValue(amount: 1000, currency: .USD) testStore.receive(.updateBaseValue(expected)) { state in state.baseValue = expected } testStore.receive(.updateMaxLimit(maxLimit)) { [maxLimit] state in state.maxLimit = maxLimit } } func test_select_triggersEnvironmentClosure() { let e = expectation(description: "Closure should be triggered") testStore = TestStore( initialState: .init(), reducer: prefillButtonsReducer, environment: PrefillButtonsEnvironment( lastPurchasePublisher: .just(lastPurchase), maxLimitPublisher: .just(maxLimit), onValueSelected: { value in XCTAssertEqual(value.currency, .USD) XCTAssertEqual(value.amount, BigInt(123)) e.fulfill() } ) ) testStore.send(.select(.init(amount: 123, currency: .USD))) waitForExpectations(timeout: 1) } }
lgpl-3.0
modocache/swift
stdlib/public/SDK/Dispatch/Data.swift
3
10947
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable { public typealias Iterator = DispatchDataIterator public typealias Index = Int public typealias Indices = DefaultRandomAccessIndices<DispatchData> public static let empty: DispatchData = DispatchData(data: _swift_dispatch_data_empty()) public enum Deallocator { /// Use `free` case free /// Use `munmap` case unmap /// A custom deallocator case custom(DispatchQueue?, @convention(block) () -> Void) fileprivate var _deallocator: (DispatchQueue?, @convention(block) () -> Void) { switch self { case .free: return (nil, _dispatch_data_destructor_free()) case .unmap: return (nil, _dispatch_data_destructor_munmap()) case .custom(let q, let b): return (q, b) } } } fileprivate var __wrapped: __DispatchData /// Initialize a `Data` with copied memory content. /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. public init(bytes buffer: UnsafeBufferPointer<UInt8>) { __wrapped = _swift_dispatch_data_create( buffer.baseAddress!, buffer.count, nil, _dispatch_data_destructor_default()) as! __DispatchData } /// Initialize a `Data` without copying the bytes. /// /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer. public init(bytesNoCopy bytes: UnsafeBufferPointer<UInt8>, deallocator: Deallocator = .free) { let (q, b) = deallocator._deallocator __wrapped = _swift_dispatch_data_create( bytes.baseAddress!, bytes.count, q, b) as! __DispatchData } internal init(data: __DispatchData) { __wrapped = data } public var count: Int { return __dispatch_data_get_size(__wrapped) } public func withUnsafeBytes<Result, ContentType>( body: (UnsafePointer<ContentType>) throws -> Result) rethrows -> Result { var ptr: UnsafeRawPointer? var size = 0 let data = __dispatch_data_create_map(__wrapped, &ptr, &size) let contentPtr = ptr!.bindMemory( to: ContentType.self, capacity: size / MemoryLayout<ContentType>.stride) defer { _fixLifetime(data) } return try body(contentPtr) } public func enumerateBytes( block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Int, _ stop: inout Bool) -> Void) { _swift_dispatch_data_apply(__wrapped) { (_, offset: Int, ptr: UnsafeRawPointer, size: Int) in let bytePtr = ptr.bindMemory(to: UInt8.self, capacity: size) let bp = UnsafeBufferPointer(start: bytePtr, count: size) var stop = false block(bp, offset, &stop) return stop ? 0 : 1 } } /// Append bytes to the data. /// /// - parameter bytes: A pointer to the bytes to copy in to the data. /// - parameter count: The number of bytes to copy. public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) { let data = _swift_dispatch_data_create(bytes, count, nil, _dispatch_data_destructor_default()) as! __DispatchData self.append(DispatchData(data: data)) } /// Append data to the data. /// /// - parameter data: The data to append to this data. public mutating func append(_ other: DispatchData) { let data = __dispatch_data_create_concat(__wrapped, other.__wrapped) __wrapped = data } /// Append a buffer of bytes to the data. /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { buffer.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: buffer.count * MemoryLayout<SourceType>.stride) { self.append($0, count: buffer.count * MemoryLayout<SourceType>.stride) } } private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: CountableRange<Index>) { var copiedCount = 0 __dispatch_data_apply(__wrapped) { (data: __DispatchData, offset: Int, ptr: UnsafeRawPointer, size: Int) in let limit = Swift.min((range.endIndex - range.startIndex) - copiedCount, size) memcpy(pointer + copiedCount, ptr, limit) copiedCount += limit return copiedCount < (range.endIndex - range.startIndex) } } /// Copy the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter count: The number of bytes to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) { _copyBytesHelper(to: pointer, from: 0..<count) } /// Copy a subset of the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter range: The range in the `Data` to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: CountableRange<Index>) { _copyBytesHelper(to: pointer, from: range) } /// Copy the contents of the data into a buffer. /// /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer. /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called. /// - parameter buffer: A buffer to copy the data into. /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied. /// - returns: Number of bytes copied into the destination buffer. public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: CountableRange<Index>? = nil) -> Int { let cnt = count guard cnt > 0 else { return 0 } let copyRange : CountableRange<Index> if let r = range { guard !r.isEmpty else { return 0 } precondition(r.startIndex >= 0) precondition(r.startIndex < cnt, "The range is outside the bounds of the data") precondition(r.endIndex >= 0) precondition(r.endIndex <= cnt, "The range is outside the bounds of the data") copyRange = r.startIndex..<(r.startIndex + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count)) } else { copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt) } guard !copyRange.isEmpty else { return 0 } _copyBytesHelper(to: buffer.baseAddress!, from: copyRange) return copyRange.count } /// Sets or returns the byte at the specified index. public subscript(index: Index) -> UInt8 { var offset = 0 let subdata = __dispatch_data_copy_region(__wrapped, index, &offset) var ptr: UnsafeRawPointer? var size = 0 let map = __dispatch_data_create_map(subdata, &ptr, &size) defer { _fixLifetime(map) } return ptr!.load(fromByteOffset: index - offset, as: UInt8.self) } public subscript(bounds: Range<Int>) -> RandomAccessSlice<DispatchData> { return RandomAccessSlice(base: self, bounds: bounds) } /// Return a new copy of the data in a specified range. /// /// - parameter range: The range to copy. public func subdata(in range: CountableRange<Index>) -> DispatchData { let subrange = __dispatch_data_create_subrange( __wrapped, range.startIndex, range.endIndex - range.startIndex) return DispatchData(data: subrange) } public func region(location: Int) -> (data: DispatchData, offset: Int) { var offset: Int = 0 let data = __dispatch_data_copy_region(__wrapped, location, &offset) return (DispatchData(data: data), offset) } public var startIndex: Index { return 0 } public var endIndex: Index { return count } public func index(before i: Index) -> Index { return i - 1 } public func index(after i: Index) -> Index { return i + 1 } /// An iterator over the contents of the data. /// /// The iterator will increment byte-by-byte. public func makeIterator() -> DispatchData.Iterator { return DispatchDataIterator(_data: self) } } public struct DispatchDataIterator : IteratorProtocol, Sequence { /// Create an iterator over the given DispatchData public init(_data: DispatchData) { var ptr: UnsafeRawPointer? self._count = 0 self._data = __dispatch_data_create_map( _data as __DispatchData, &ptr, &self._count) self._ptr = ptr self._position = _data.startIndex // The only time we expect a 'nil' pointer is when the data is empty. assert(self._ptr != nil || self._count == self._position) } /// Advance to the next element and return it, or `nil` if no next /// element exists. public mutating func next() -> DispatchData._Element? { if _position == _count { return nil } let element = _ptr.load(fromByteOffset: _position, as: UInt8.self) _position = _position + 1 return element } internal let _data: __DispatchData internal var _ptr: UnsafeRawPointer! internal var _count: Int internal var _position: DispatchData.Index } extension DispatchData { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> __DispatchData { return unsafeBitCast(__wrapped, to: __DispatchData.self) } public static func _forceBridgeFromObjectiveC(_ input: __DispatchData, result: inout DispatchData?) { result = DispatchData(data: input) } public static func _conditionallyBridgeFromObjectiveC(_ input: __DispatchData, result: inout DispatchData?) -> Bool { result = DispatchData(data: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: __DispatchData?) -> DispatchData { var result: DispatchData? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } @_silgen_name("_swift_dispatch_data_empty") internal func _swift_dispatch_data_empty() -> __DispatchData @_silgen_name("_swift_dispatch_data_destructor_free") internal func _dispatch_data_destructor_free() -> _DispatchBlock @_silgen_name("_swift_dispatch_data_destructor_munmap") internal func _dispatch_data_destructor_munmap() -> _DispatchBlock @_silgen_name("_swift_dispatch_data_destructor_default") internal func _dispatch_data_destructor_default() -> _DispatchBlock
apache-2.0
nearspeak/iOS-SDK
NearspeakKitTests/NearspeakKitTests.swift
1
915
// // NearspeakKitTests.swift // NearspeakKitTests // // Created by Patrick Steiner on 23.04.15. // Copyright (c) 2015 Mopius. All rights reserved. // import UIKit import XCTest class NearspeakKitTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
lgpl-3.0
AdaptiveMe/adaptive-arp-darwin
adaptive-arp-rt/Source/Sources.Impl/VideoDelegate.swift
1
3944
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:carlos@adaptive.me> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:ferran.vila.conesa@gmail.com> * See source code files for contributors. Release: * @version v2.0.2 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation import AdaptiveArpApi #if os(iOS) import UIKit #endif /** Interface for Managing the Video operations Auto-generated implementation of IVideo specification. */ public class VideoDelegate : BaseMediaDelegate, IVideo { /// Logger variable let logger : ILogging = AppRegistryBridge.sharedInstance.getLoggingBridge() let loggerTag : String = "VideoDelegate" #if os(iOS) /// Application variable var application:UIApplication? = nil #endif /** Default Constructor. */ public override init() { super.init() #if os(iOS) self.application = (AppRegistryBridge.sharedInstance.getPlatformContext().getContext() as! UIApplication) #endif } /** Play url video stream @param url of the video @since ARP1.0 */ public func playStream(url : String) { if checkURl(url) { if (BaseViewController.ViewCurrent.getView() != nil) { #if os(iOS) (BaseViewController.ViewCurrent.getView()! as! BaseViewController).showInternalMedia(NSURL(string: url)!, showAnimated: true) #endif } else { logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "The current View Controller has no presented view") } } } /** Private method to check if an application is able to open an url @param url Url to check @return The result of the operation */ private func checkURl(url: String) -> Bool { // Check if the string is empty if url.isEmpty { return false } // Check the correct format of the number if !Utils.validateUrl(url) { logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "The url: \(url) has an incorrect format") return false } let url: NSURL = NSURL(string: url)! #if os(iOS) // Check if it is possible to open the url if !application!.canOpenURL(url) { logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "The application cannot open this type of url: \(url)") return false } #endif #if os(OSX) // There is no way to check the url validity for OSX #endif return true } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
abertelrud/swift-package-manager
Sources/PackageCollections/PackageIndex+Configuration.swift
2
5349
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2022 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 // //===----------------------------------------------------------------------===// import Foundation import TSCBasic public struct PackageIndexConfiguration: Equatable { public var url: URL? public var searchResultMaxItemsCount: Int public var cacheDirectory: AbsolutePath public var cacheTTLInSeconds: Int public var cacheMaxSizeInMegabytes: Int // TODO: rdar://87575573 remove feature flag public internal(set) var enabled = ProcessInfo.processInfo.environment["SWIFTPM_ENABLE_PACKAGE_INDEX"] == "1" public init( url: URL? = nil, searchResultMaxItemsCount: Int? = nil, disableCache: Bool = false, cacheDirectory: AbsolutePath? = nil, cacheTTLInSeconds: Int? = nil, cacheMaxSizeInMegabytes: Int? = nil ) { self.url = url self.searchResultMaxItemsCount = searchResultMaxItemsCount ?? 50 self.cacheDirectory = (try? cacheDirectory.map(resolveSymlinks)) ?? (try? localFileSystem.swiftPMCacheDirectory.appending(components: "package-metadata")) ?? .root self.cacheTTLInSeconds = disableCache ? -1 : (cacheTTLInSeconds ?? 3600) self.cacheMaxSizeInMegabytes = cacheMaxSizeInMegabytes ?? 10 } } public struct PackageIndexConfigurationStorage { private let path: AbsolutePath private let fileSystem: FileSystem private let encoder: JSONEncoder private let decoder: JSONDecoder public init(path: AbsolutePath, fileSystem: FileSystem) { self.path = path self.fileSystem = fileSystem self.encoder = JSONEncoder.makeWithDefaults() self.decoder = JSONDecoder.makeWithDefaults() } public func load() throws -> PackageIndexConfiguration { guard self.fileSystem.exists(self.path) else { return .init() } let data: Data = try self.fileSystem.readFileContents(self.path) guard data.count > 0 else { return .init() } let container = try decoder.decode(StorageModel.Container.self, from: data) return try PackageIndexConfiguration(container.index) } public func save(_ configuration: PackageIndexConfiguration) throws { if !self.fileSystem.exists(self.path.parentDirectory) { try self.fileSystem.createDirectory(self.path.parentDirectory, recursive: true) } let container = StorageModel.Container(configuration) let buffer = try encoder.encode(container) try self.fileSystem.writeFileContents(self.path, bytes: ByteString(buffer), atomically: true) } @discardableResult public func update(with handler: (inout PackageIndexConfiguration) throws -> Void) throws -> PackageIndexConfiguration { let configuration = try self.load() var updatedConfiguration = configuration try handler(&updatedConfiguration) if updatedConfiguration != configuration { try self.save(updatedConfiguration) } return updatedConfiguration } } private enum StorageModel { struct Container: Codable { var index: Index init(_ from: PackageIndexConfiguration) { self.index = .init( url: from.url?.absoluteString, searchResultMaxItemsCount: from.searchResultMaxItemsCount, cacheDirectory: from.cacheDirectory.pathString, cacheTTLInSeconds: from.cacheTTLInSeconds, cacheMaxSizeInMegabytes: from.cacheMaxSizeInMegabytes ) } } struct Index: Codable { let url: String? let searchResultMaxItemsCount: Int? let cacheDirectory: String? let cacheTTLInSeconds: Int? let cacheMaxSizeInMegabytes: Int? } } // MARK: - Utility private extension PackageIndexConfiguration { init(_ from: StorageModel.Index) throws { let url: URL? switch from.url { case .none: url = nil case .some(let urlString): url = URL(string: urlString) guard url != nil else { throw SerializationError.invalidURL(urlString) } } let cacheDirectory: AbsolutePath? switch from.cacheDirectory { case .none: cacheDirectory = nil case .some(let path): cacheDirectory = try? AbsolutePath(validating: path) guard cacheDirectory != nil else { throw SerializationError.invalidPath(path) } } self.init( url: url, searchResultMaxItemsCount: from.searchResultMaxItemsCount, cacheDirectory: cacheDirectory, cacheTTLInSeconds: from.cacheTTLInSeconds, cacheMaxSizeInMegabytes: from.cacheMaxSizeInMegabytes ) } } private enum SerializationError: Error { case invalidURL(String) case invalidPath(String) }
apache-2.0
ale-sisto/TouchLoginDemo
TouchLoginDemoTests/TouchLoginDemoTests.swift
1
933
// // TouchLoginDemoTests.swift // TouchLoginDemoTests // // Created by Ale on 10/12/14. // Copyright (c) 2014 Alessandro Sisto, Marco Donati. All rights reserved. // import UIKit import XCTest class TouchLoginDemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
uasys/swift
test/SILGen/reabstract.swift
1
2761
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s func takeFn<T>(_ f : (T) -> T?) {} func liftOptional(_ x : Int) -> Int? { return x } func test0() { takeFn(liftOptional) } // CHECK: sil hidden @_T010reabstract5test0yyF : $@convention(thin) () -> () { // CHECK: [[T0:%.*]] = function_ref @_T010reabstract6takeFn{{[_0-9a-zA-Z]*}}F // Emit a generalized reference to liftOptional. // TODO: just emit a globalized thunk // CHECK-NEXT: reabstract.liftOptional // CHECK-NEXT: [[T1:%.*]] = function_ref @_T010reabstract12liftOptional{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: [[T2:%.*]] = thin_to_thick_function [[T1]] // CHECK-NEXT: reabstraction thunk // CHECK-NEXT: [[T3:%.*]] = function_ref [[THUNK:@.*]] : // CHECK-NEXT: [[T4:%.*]] = partial_apply [[T3]]([[T2]]) // CHECK-NEXT: apply [[T0]]<Int>([[T4]]) // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: sil shared [transparent] [serializable] [reabstraction_thunk] [[THUNK]] : $@convention(thin) (@in Int, @owned @callee_owned (Int) -> Optional<Int>) -> @out Optional<Int> { // CHECK: [[T0:%.*]] = load [trivial] %1 : $*Int // CHECK-NEXT: [[T1:%.*]] = apply %2([[T0]]) // CHECK-NEXT: store [[T1]] to [trivial] %0 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil hidden @_T010reabstract10testThrowsyypF // CHECK: function_ref @_T0ytytIxir_Ix_TR // CHECK: function_ref @_T0ytyts5Error_pIxirzo_sAA_pIxzo_TR func testThrows(_ x: Any) { _ = x as? () -> () _ = x as? () throws -> () } // Make sure that we preserve inout-ness when lowering types with maximum // abstraction level -- <rdar://problem/21329377> class C {} struct Box<T> { let t: T } func notFun(_ c: inout C, i: Int) {} func testInoutOpaque(_ c: C, i: Int) { var c = c let box = Box(t: notFun) box.t(&c, i) } // CHECK-LABEL: sil hidden @_T010reabstract15testInoutOpaqueyAA1CC_Si1itF // CHECK: function_ref @_T010reabstract6notFunyAA1CCz_Si1itF // CHECK: thin_to_thick_function {{%[0-9]+}} // CHECK: function_ref @_T010reabstract1CCSiIxly_ACSiytIxlir_TR // CHECK: partial_apply // CHECK: store // CHECK: load // CHECK: function_ref @_T010reabstract1CCSiytIxlir_ACSiIxly_TR // CHECK: partial_apply // CHECK: apply // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T010reabstract1CCSiIxly_ACSiytIxlir_TR : $@convention(thin) (@inout C, @in Int, @owned @callee_owned (@inout C, Int) -> ()) -> @out () { // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T010reabstract1CCSiytIxlir_ACSiIxly_TR : $@convention(thin) (@inout C, Int, @owned @callee_owned (@inout C, @in Int) -> @out ()) -> () {
apache-2.0
akolov/FlingChallenge
FlingChallengeKit/FlingChallengeKit/DataController.swift
1
4405
// // DataController.swift // FlingChallengeKit // // Created by Alexander Kolov on 5/8/16. // Copyright © 2016 Alexander Kolov. All rights reserved. // import Foundation import CoreData final public class DataController { public init() throws { struct Static { static var onceToken: dispatch_once_t = 0 } try dispatch_once_throws(&Static.onceToken) { try dispatch_sync_main { try DataController.initializeCoreDataStack() } } } public static let applicationDocumentsDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count - 1] }() public lazy var mainQueueManagedObjectContext: NSManagedObjectContext = { return DataController._mainQueueManagedObjectContext }() public lazy var privateManagedObjectContext: NSManagedObjectContext = { return DataController._privateQueueManagedObjectContext }() public func withPrivateContext(closure: (NSManagedObjectContext) throws -> Void) throws { try privateManagedObjectContext.performBlockAndWaitThrowable { try closure(self.privateManagedObjectContext) if self.privateManagedObjectContext.hasChanges { try self.privateManagedObjectContext.save() } } try self.mainQueueManagedObjectContext.performBlockAndWaitThrowable { if self.mainQueueManagedObjectContext.hasChanges { try self.mainQueueManagedObjectContext.save() } } } public func destroyPersistentStore() throws { try DataController.persistentStoreCoordinator?.destroyPersistentStoreAtURL( DataController.persistentStoreURL, withType: NSSQLiteStoreType, options: DataController.persistentStoreOptions ) try DataController.persistentStoreCoordinator?.addPersistentStoreWithType( NSSQLiteStoreType, configuration: nil, URL: DataController.persistentStoreURL, options: DataController.persistentStoreOptions ) } } // MARK: Private private extension DataController { private static func initializeCoreDataStack() throws { assert(NSThread.isMainThread(), "\(#function) must be executed on main thread") guard let bundle = NSBundle(identifier: "com.alexkolov.FlingChallengeKit") else { throw FlingChallengeError.InitializationError(description: "Could not find framework bundle") } guard let modelURL = bundle.URLForResource("Fling", withExtension: "momd") else { throw FlingChallengeError.InitializationError(description: "Could not find model in main bundle") } guard let model = NSManagedObjectModel(contentsOfURL: modelURL) else { throw FlingChallengeError.InitializationError(description: "Could not load model from URL: \(modelURL)") } let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: persistentStoreURL, options: persistentStoreOptions) persistentStoreCoordinator = coordinator let context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) context.persistentStoreCoordinator = coordinator _mainQueueManagedObjectContext = context let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) privateContext.parentContext = _mainQueueManagedObjectContext privateContext.mergePolicy = NSMergePolicy(mergeType: .MergeByPropertyObjectTrumpMergePolicyType) _privateQueueManagedObjectContext = privateContext } private static let persistentStoreURL: NSURL = { return DataController.applicationDocumentsDirectory.URLByAppendingPathComponent(persistentStoreName) }() private static let persistentStoreOptions = [ NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true ] private static let persistentStoreName = "FlingChallenge.sqlite" private static var managedObjectModel: NSManagedObjectModel? private static var persistentStoreCoordinator: NSPersistentStoreCoordinator? private static var _mainQueueManagedObjectContext: NSManagedObjectContext! private static var _privateQueueManagedObjectContext: NSManagedObjectContext! }
mit
cwwise/CWWeChat
CWWeChat/ChatModule/CWChatClient/CWChatClientOptions.swift
2
797
// // CWChatClientOptions.swift // CWWeChat // // Created by wei chen on 2017/2/14. // Copyright © 2017年 chenwei. All rights reserved. // import Foundation // 配置信息 public class CWChatClientOptions: NSObject { public static var `default`: CWChatClientOptions = { let options = CWChatClientOptions(host: "cwwise.com", domain: "cwwise.com") return options }() /// 端口号 var port: UInt16 = 5222 /// XMPP服务器 ip地址 默认为本地localhost var host: String /// XMPP聊天 域 var domain: String /// 来源 app iOS 安卓等等 var resource: String init(host: String, domain: String) { self.host = host self.domain = domain self.resource = "ios" super.init() } }
mit
Sajjon/Zeus
Zeus/SwiftReflection.swift
1
5108
// // SwiftReflection.swift // SwiftReflection // // Created by Cyon Alexander (Ext. Netlight) on 01/09/16. // Copyright © 2016 com.cyon. All rights reserved. // import Foundation import ObjectiveC.runtime /* Please note that the class you are inspecting have to inherit from NSObject. This tool can find the name and type of properties of type NSObject, e.g. NSString (or just "String" with Swift 3 syntax), NSDate (or just "NSDate" with Swift 3 syntax), NSNumber etc. It also works with optionals and implicit optionals for said types, e.g. String?, String!, Date!, Date? etc... This tool can also find name and type of "primitive data types" such as Bool, Int, Int32, _HOWEVER_ it does not work if said primitive have optional type, e.g. Int? <--- DOES NOT WORK */ public func getTypesOfProperties(in clazz: NSObject.Type) -> Dictionary<String, Any>? { var count = UInt32() guard let properties = class_copyPropertyList(clazz, &count) else { log.error("Failed to retrieve property list for object of type: '\(clazz)'"); return nil } var types: Dictionary<String, Any> = [:] for i in 0..<Int(count) { guard let property: objc_property_t = properties[i], let name = getNameOf(property: property) else { continue } let type = getTypeOf(property: property) types[name] = type } free(properties) return types } public func getTypesOfProperties(ofObject object: NSObject) -> Dictionary<String, Any>? { let clazz: NSObject.Type = type(of: object) return getTypesOfProperties(in: clazz) } public func typeOf(property propertyName: String, for object: NSObject) -> Any? { let type = type(of: object) return typeOf(property: propertyName, in: type) } public func typeOf(property propertyName: String, in clazz: NSObject.Type) -> Any? { guard let propertyTypes = getTypesOfProperties(in: clazz), let type = propertyTypes[propertyName] else { return nil } print("Property named: '\(propertyName)' has type: \(type)") return type } public func isProperty(named propertyName: String, ofType targetType: Any, for object: NSObject) -> Bool { let type = type(of: object) return isProperty(named: propertyName, ofType: targetType, in: type) } public func isProperty(named propertyName: String, ofType targetType: Any, in clazz: NSObject.Type) -> Bool { let propertyType = typeOf(property: propertyName, in: clazz) let match = propertyType == targetType return match } fileprivate func ==(rhs: Any, lhs: Any) -> Bool { var rhsType: String = "\(rhs)".withoutOptional var lhsType: String = "\(lhs)".withoutOptional let same = rhsType == lhsType return same } fileprivate func ==(rhs: NSObject.Type, lhs: Any) -> Bool { let rhsType: String = "\(rhs)".withoutOptional let lhsType: String = "\(lhs)".withoutOptional let same = rhsType == lhsType return same } fileprivate func ==(rhs: Any, lhs: NSObject.Type) -> Bool { let rhsType: String = "\(rhs)".withoutOptional let lhsType: String = "\(lhs)".withoutOptional let same = rhsType == lhsType return same } fileprivate func getTypeOf(property: objc_property_t) -> Any { guard let attributesAsNSString: NSString = NSString(utf8String: property_getAttributes(property)) else { return Any.self } let attributes = attributesAsNSString as String let slices = attributes.components(separatedBy: "\"") guard slices.count > 1 else { return getPrimitiveDataType(withAttributes: attributes) } let objectClassName = slices[1] let objectClass = NSClassFromString(objectClassName) as! NSObject.Type return objectClass } fileprivate func getPrimitiveDataType(withAttributes attributes: String) -> Any { guard let letter = attributes.substring(from: 1, to: 2), let type = primitiveDataTypes[letter] else { return Any.self } return type } fileprivate func getNameOf(property: objc_property_t) -> String? { guard let name: NSString = NSString(utf8String: property_getName(property)) else { return nil } return name as String } fileprivate let primitiveDataTypes: Dictionary<String, Any> = [ "c" : Int8.self, "s" : Int16.self, "i" : Int32.self, "q" : Int.self, //also: Int64, NSInteger, only true on 64 bit platforms "S" : UInt16.self, "I" : UInt32.self, "Q" : UInt.self, //also UInt64, only true on 64 bit platforms "B" : Bool.self, "d" : Double.self, "f" : Float.self, "{" : Decimal.self ] private extension String { func substring(from fromIndex: Int, to toIndex: Int) -> String? { let substring = self[self.index(self.startIndex, offsetBy: fromIndex)..<self.index(self.startIndex, offsetBy: toIndex)] return substring } /// Extracts "NSDate" from the string "Optional(NSDate)" var withoutOptional: String { guard self.contains("Optional(") && self.contains(")") else { return self } let afterOpeningParenthesis = self.components(separatedBy: "(")[1] let wihtoutOptional = afterOpeningParenthesis.components(separatedBy: ")")[0] return wihtoutOptional } }
apache-2.0
breadwallet/breadwallet-ios
breadwallet/src/CloudBackup/SelectBackupView.swift
1
3933
// // SelectBackupView.swift // breadwallet // // Created by Adrian Corscadden on 2020-07-30. // Copyright © 2020 Breadwinner AG. All rights reserved. // // See the LICENSE file at the project root for license information. // import SwiftUI enum SelectBackupError: Error { case didCancel } @available(iOS 13.6, *) typealias SelectBackupResult = Result<CloudBackup, Error> @available(iOS 13.6, *) struct SelectBackupView: View { let backups: [CloudBackup] let callback: (SelectBackupResult) -> Void @SwiftUI.State private var selectedBackup: CloudBackup? var body: some View { ZStack { Rectangle() .fill(Color(Theme.primaryBackground)) VStack { Text(S.CloudBackup.selectTitle) .foregroundColor(Color(Theme.primaryText)) .lineLimit(nil) .font(Font(Theme.h2Title)) ForEach(0..<backups.count) { i in BackupCell(backup: self.backups[i], isOn: self.binding(for: i)) .padding(4.0) } self.okButton() } }.edgesIgnoringSafeArea(.all) .navigationBarItems(trailing: EmptyView()) } private func okButton() -> some View { Button(action: { self.callback(.success(self.selectedBackup!)) }, label: { ZStack { RoundedRectangle(cornerRadius: 4.0) .fill(Color(UIColor.primaryButton)) .opacity(self.selectedBackup == nil ? 0.3 : 1.0) Text(S.Button.continueAction) .foregroundColor(Color(Theme.primaryText)) .font(Font(Theme.h3Title)) } }) .frame(height: 44.0) .cornerRadius(4.0) .disabled(self.selectedBackup == nil) .padding(EdgeInsets(top: 8.0, leading: 32.0, bottom: 32.0, trailing: 32.0)) } private func binding(for index: Int) -> Binding<Bool> { Binding<Bool>( get: { guard let selectedBackup = self.selectedBackup else { return false } return self.backups[index].identifier == selectedBackup.identifier }, set: { if $0 { self.selectedBackup = self.backups[index] } } ) } } @available(iOS 13.6, *) struct BackupCell: View { let backup: CloudBackup @SwiftUI.Binding var isOn: Bool private let gradient = Gradient(colors: [Color(UIColor.gradientStart), Color(UIColor.gradientEnd)]) var body: some View { HStack { RadioButton(isOn: $isOn) .frame(width: 44.0, height: 44.0) VStack(alignment: .leading) { Text(dateString) .foregroundColor(Color(Theme.primaryText)) .font(Font(Theme.body1)) .padding(EdgeInsets(top: 8.0, leading: 8.0, bottom: 0.0, trailing: 8.0)) Text("\(backup.deviceName)") .foregroundColor(Color(Theme.secondaryText)) .font(Font(Theme.body1)) .padding(EdgeInsets(top: 0.0, leading: 8.0, bottom: 8.0, trailing: 8.0)) } } } var dateString: String { let df = DateFormatter() df.dateFormat = "MMM d yyyy HH:mm:ss" return "\(df.string(from: backup.createTime))" } } @available(iOS 13.6, *) struct RestoreCloudBackupView_Previews: PreviewProvider { static var previews: some View { SelectBackupView(backups: [ CloudBackup(phrase: "this is a phrase", identifier: "key", pin: "12345"), CloudBackup(phrase: "this is another phrase", identifier: "key", pin: "12345"), CloudBackup(phrase: "this is yet another phrase", identifier: "key", pin: "12345") ], callback: {_ in }) } }
mit
david-mcqueen/Pulser
Heart Rate Monitor - Audio/Classes/UserSettings.swift
1
2288
// // UserSettings.swift // Heart Rate Monitor - Audio // // Created by DavidMcQueen on 28/03/2015. // Copyright (c) 2015 David McQueen. All rights reserved. // import Foundation class UserSettings { var AnnounceAudio: Bool; var AnnounceAudioZoneChange: Bool; var AudioIntervalMinutes: Double; var AudioIntervalSeconds: Double; var SaveHealthkit: Bool; var HealthkitIntervalMinutes: Double; var UserZones: [Zone]; var CurrentZone: HeartRateZone; var AnnounceAudioShort: Bool; init(){ //Default user settings AnnounceAudio = true; AnnounceAudioZoneChange = true; AudioIntervalMinutes = 1.0; AudioIntervalSeconds = 0.0; SaveHealthkit = false; HealthkitIntervalMinutes = 1.0; UserZones = []; CurrentZone = HeartRateZone.Rest; AnnounceAudioShort = false; } func shouldAnnounceAudio()->Bool{ return AnnounceAudio && AnnounceAudioZoneChange; } func getAudioIntervalMinutesFloat()->Float{ return convertDoubleToFloat(self.AudioIntervalMinutes); } func getAudioIntervalSecondsFloat()->Float { return convertDoubleToFloat(self.AudioIntervalSeconds); } func getHealthkitIntervalasFloat()->Float{ return convertDoubleToFloat(self.HealthkitIntervalMinutes); } private func convertDoubleToFloat(input: Double)->Float{ return Float(input); } func getAudioIntervalSeconds()->Double{ return convertMinuteToSeconds(self.AudioIntervalMinutes) + self.AudioIntervalSeconds } func getHealthkitIntervalSeconds()->Double{ return convertMinuteToSeconds(self.HealthkitIntervalMinutes) } func allZonesToString()->String{ var zonesAsString: String = ""; for zone in UserZones{ zonesAsString += "\(singleZoneToString(zone))\n" } return zonesAsString; } private func singleZoneToString(inputZone: Zone)->String{ return "Zone \(inputZone.getZoneType().rawValue) - Min: \(inputZone.Lower) - Max: \(inputZone.Upper)" } private func convertMinuteToSeconds(minutes: Double)->Double{ return minutes * 60; } }
gpl-3.0
rallahaseh/RALocalization
Example/RALocalization/ViewController.swift
1
2901
// // ViewController.swift // RALocalization // // Created by rallahaseh on 10/17/2017. // Copyright (c) 2017 rallahaseh. All rights reserved. // import UIKit import RALocalization class ViewController: UIViewController { @IBOutlet weak var label: UILabel! @IBOutlet weak var button: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // self.button.titleLabel?.text = NSLocalizedString("changeLanguage", comment: "Change Language") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func changeLanguage(_ sender: UIButton) { var transition: UIViewAnimationOptions = .transitionFlipFromLeft let actionSheet = UIAlertController(title: nil, message: "Switch Language", preferredStyle: UIAlertControllerStyle.actionSheet) let availableLanguages = ["English", "אנגלית", "العربية"] for language in availableLanguages { let displayName = language let languageAction = UIAlertAction(title: displayName, style: .default, handler: { (alert: UIAlertAction!) -> Void in if language == "English" { RALanguage.setLanguage(language: .english) transition = .transitionFlipFromRight UIView.appearance().semanticContentAttribute = .forceLeftToRight } else if language == "العربية" { RALanguage.setLanguage(language: .arabic) UIView.appearance().semanticContentAttribute = .forceRightToLeft } else { transition = .transitionCurlUp RALanguage.setLanguage(language: .hebrew) UIView.appearance().semanticContentAttribute = .forceRightToLeft } let rootVC: UIWindow = ((UIApplication.shared.delegate?.window)!)! rootVC.rootViewController = self.storyboard?.instantiateViewController(withIdentifier: "root") let mainWindow = (UIApplication.shared.delegate?.window!)! mainWindow.backgroundColor = UIColor(hue: 0.6477, saturation: 0.6314, brightness: 0.6077, alpha: 0.8) UIView.transition(with: mainWindow, duration: 0.55001, options: transition, animations: { () -> Void in }) { (finished) -> Void in} }) actionSheet.addAction(languageAction) } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { (alert: UIAlertAction) -> Void in }) actionSheet.addAction(cancelAction) self.present(actionSheet, animated: true, completion: nil) } }
mit
PaddlerApp/paddler-ios
Paddler/View Controllers/LoginViewController.swift
1
465
// // LoginViewController.swift // Paddler // // Created by YingYing Zhang on 10/10/17. // Copyright © 2017 Paddler. All rights reserved. // import UIKit import Firebase import GoogleSignIn class LoginViewController: UIViewController, GIDSignInUIDelegate { @IBOutlet weak var loginWithGoogleButton: GIDSignInButton! override func viewDidLoad() { super.viewDidLoad() GIDSignIn.sharedInstance().uiDelegate = self } }
apache-2.0
LeoMobileDeveloper/PullToRefreshKit
Demo/Demo/DianpingRefreshHeader.swift
1
2049
// // DianpingRefreshHeader.swift // PullToRefreshKit // // Created by huangwenchen on 16/7/15. // Copyright © 2016年 Leo. All rights reserved. // import Foundation import UIKit import PullToRefreshKit class DianpingRefreshHeader:UIView,RefreshableHeader{ let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) imageView.frame = CGRect(x: 0, y: 0, width: 60, height: 60) addSubview(imageView) } override func layoutSubviews() { super.layoutSubviews() imageView.center = CGPoint(x: self.bounds.width/2.0, y: self.bounds.height/2.0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - RefreshableHeader - func heightForHeader() -> CGFloat { return 60.0 } //监听百分比变化 func percentUpdateDuringScrolling(_ percent:CGFloat){ imageView.isHidden = (percent == 0) let adjustPercent = max(min(1.0, percent),0.0) let scale = 0.2 + (1.0 - 0.2) * adjustPercent; imageView.transform = CGAffineTransform(scaleX: scale, y: scale) let mappedIndex = Int(adjustPercent * 60) let imageName = "dropdown_anim__000\(mappedIndex)" let image = UIImage(named: imageName) imageView.image = image } //松手即将刷新的状态 func didBeginRefreshingState(){ let images = ["dropdown_loading_01","dropdown_loading_02","dropdown_loading_03"].map { (name) -> UIImage in return UIImage(named:name)! } imageView.animationImages = images imageView.animationDuration = Double(images.count) * 0.15 imageView.startAnimating() } //刷新结束,将要隐藏header func didBeginHideAnimation(_ result:RefreshResult){} //刷新结束,完全隐藏header func didCompleteHideAnimation(_ result:RefreshResult){ imageView.animationImages = nil imageView.stopAnimating() imageView.isHidden = true } }
mit
powerytg/Accented
Accented/UI/Home/Themes/Card/Renderers/StreamCardPhotoCell.swift
1
5819
// // StreamCardPhotoCell.swift // Accented // // Created by You, Tiangong on 8/25/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit class StreamCardPhotoCell: StreamPhotoCellBaseCollectionViewCell { private var titleLabel = UILabel() private var descLabel = UILabel() private var subtitleLabel = UILabel() private var footerView = UIImageView() private var cardBackgroundLayer = CALayer() private var currentTheme : AppTheme { return ThemeManager.sharedInstance.currentTheme } override func initialize() { // Background (only available in light card theme) contentView.layer.insertSublayer(cardBackgroundLayer, at: 0) cardBackgroundLayer.backgroundColor = UIColor.white.cgColor cardBackgroundLayer.shadowColor = UIColor.black.cgColor cardBackgroundLayer.shadowOpacity = 0.12 cardBackgroundLayer.cornerRadius = 2 cardBackgroundLayer.shadowRadius = 6 // Title titleLabel.textColor = currentTheme.titleTextColor titleLabel.font = StreamCardLayoutSpec.titleFont titleLabel.numberOfLines = StreamCardLayoutSpec.titleLabelLineCount titleLabel.textAlignment = .center titleLabel.lineBreakMode = .byTruncatingMiddle contentView.addSubview(titleLabel) // Subtitle subtitleLabel.textColor = UIColor(red: 147 / 255.0, green: 147 / 255.0, blue: 147 / 255.0, alpha: 1.0) subtitleLabel.font = StreamCardLayoutSpec.subtitleFont subtitleLabel.numberOfLines = StreamCardLayoutSpec.subtitleLineCount subtitleLabel.textAlignment = .center subtitleLabel.lineBreakMode = .byTruncatingMiddle contentView.addSubview(subtitleLabel) // Photo renderer.clipsToBounds = true renderer.contentMode = .scaleAspectFill contentView.addSubview(renderer) // Descriptions descLabel.textColor = currentTheme.standardTextColor descLabel.font = ThemeManager.sharedInstance.currentTheme.descFont descLabel.numberOfLines = StreamCardLayoutSpec.descLineCount descLabel.textAlignment = .center descLabel.lineBreakMode = .byTruncatingTail contentView.addSubview(descLabel) // Bottom line and footer if ThemeManager.sharedInstance.currentTheme is DarkCardTheme { footerView.image = UIImage(named: "DarkJournalFooter") } else { footerView.image = UIImage(named: "LightJournalFooter") } footerView.sizeToFit() contentView.addSubview(footerView) } override func layoutSubviews() { super.layoutSubviews() if photo == nil { return } if bounds.width == 0 || bounds.height == 0 { isHidden = true return } // Content view isHidden = false contentView.frame = bounds let photoModel = photo! let w = self.contentView.bounds.width var nextY : CGFloat = StreamCardLayoutSpec.topPadding // Background if currentTheme is LightCardTheme { cardBackgroundLayer.isHidden = false cardBackgroundLayer.frame = contentView.bounds } else { cardBackgroundLayer.isHidden = true } // Photo let aspectRatio = photoModel.width / photoModel.height let desiredHeight = w / aspectRatio var f = renderer.frame f.origin.x = StreamCardLayoutSpec.photoLeftPadding f.origin.y = nextY f.size.width = w - StreamCardLayoutSpec.photoLeftPadding - StreamCardLayoutSpec.photoRightPadding f.size.height = min(desiredHeight, StreamCardLayoutSpec.maxPhotoHeight) renderer.frame = f renderer.photo = photoModel nextY += f.height + StreamCardLayoutSpec.photoVPadding // Title label titleLabel.textColor = currentTheme.cardTitleColor titleLabel.text = photoModel.title layoutLabel(titleLabel, width: w, originY: nextY, padding: StreamCardLayoutSpec.titleHPadding) nextY += titleLabel.frame.height + StreamCardLayoutSpec.titleVPadding // Subtitle label subtitleLabel.text = photoModel.user.firstName layoutLabel(subtitleLabel, width: w, originY: nextY, padding: StreamCardLayoutSpec.subtitleHPadding) nextY += subtitleLabel.frame.height + StreamCardLayoutSpec.photoVPadding // Description descLabel.textColor = currentTheme.cardDescColor if let descData = photoModel.desc?.data(using: String.Encoding.utf8) { do { let descText = try NSAttributedString(data: descData, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil) descLabel.text = descText.string } catch _ { descLabel.text = nil } } else { descLabel.text = nil } layoutLabel(descLabel, width: w, originY: nextY, padding: StreamCardLayoutSpec.descHPadding) // Footer nextY = descLabel.frame.maxY + StreamCardLayoutSpec.footerTopPadding f = footerView.frame f.origin.x = w / 2 - f.width / 2 f.origin.y = nextY footerView.frame = f } private func layoutLabel(_ label : UILabel, width : CGFloat, originY : CGFloat, padding : CGFloat) { var f = label.frame f.origin.y = originY f.size.width = width - padding * 2 label.frame = f label.sizeToFit() f = label.frame f.origin.x = width / 2 - f.width / 2 label.frame = f } }
mit
LawrenceHan/iOS-project-playground
Swift_A_Big_Nerd_Ranch_Guide/MonsterTown property/MonsterTown/main.swift
1
928
// // main.swift // MonsterTown // // Created by Hanguang on 3/1/16. // Copyright © 2016 Hanguang. All rights reserved. // import Foundation var myTown = Town(region: "West", population: 0, stoplights: 6) myTown?.printTownDescription() let ts = myTown?.townSize print(ts) myTown?.changePopulation(100000) print("Size: \(myTown?.townSize); population: \(myTown?.population)") var fredTheZombie: Zombie? = Zombie(limp: false, fallingApart: false, town: myTown, monsterName: "Fred") fredTheZombie?.terrorizeTown() fredTheZombie?.changeName("Fred the Zombie", walksWithLimp: false) var convenientZombie = Zombie(limp: true, fallingApart: false) fredTheZombie?.town?.printTownDescription() print("Victim pool: \(fredTheZombie?.victimPool)") fredTheZombie?.victimPool = 500 print("Victim pool: \(fredTheZombie?.victimPool)") print(Zombie.spookyNoise) if Zombie.isTeerifying { print("Run away!") } fredTheZombie = nil
mit
BrantSteven/SinaProject
BSweibo/BSweibo/class/Tools/NetWorkingTool.swift
1
2144
// // NetWorkingTool.swift // AfnetWorking // // Created by 上海旅徒电子商务有限公司 on 16/9/20. // Copyright © 2016年 白霜. All rights reserved. // import UIKit import AFNetworking class NetWorkingTool: AFHTTPSessionManager { enum requestType:Int { case GET case POST } // swift 单例 let 线程安全 // static let shareInstance : NetWorkingTool = NetWorkingTool() //为了添加text/html的数据格式 可以使用闭包创建对象 static let shareInstance : NetWorkingTool = { let tool = NetWorkingTool(baseURL: NSURL(string: RequestUrl) as URL?) //(重设)设置AFN能够接收的数据类型 // tool.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript","text/html","text/plain") as? Set<String> //(在原有的基础上)添加AFN能够接收的数据类型 tool.responseSerializer.acceptableContentTypes?.insert("text/html") tool.responseSerializer.acceptableContentTypes?.insert("text/plain") return tool }() } //MARK: - 封装请求方法 //Json序列化不支持格式 text/html extension NetWorkingTool{ func request (requestType:requestType,urlString:String,parameters:[String:AnyObject],finished:@escaping (_ requestResult:AnyObject?,_ requestError:Error?)->()){ //1.定义一个成功的回调 let successCallBack = { (tark:URLSessionDataTask, result:Any?) in bsLog(message: result) finished(result as AnyObject?, nil) } //2.定义失败的回调 let failureCallBack = { (task:URLSessionDataTask?, error:Error) in bsLog(message: error) finished(nil, error as Error?) } if requestType == .GET { get(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack) }else{ post(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack) } } }
mit
kaich/CKAlertView
CKAlertView/Classes/Core/CKAlertView+MajorAction.swift
1
5041
// // CKAlertView+MajorAction.swift // Pods // // Created by mac on 16/10/12. // // import Foundation public extension CKAlertView { /// 显示突出主功能按钮的弹出框(主功能按钮长,取消按钮和其他按钮居其下方) /// /// - parameter alertTitle: 标题 /// - parameter alertMessages: 主体,$代表段落的结尾 /// - parameter cancelButtonTitle: 取消按钮标题 /// - parameter majorButtonTitle: 主体按钮标题 /// - parameter anotherButtonTitle: 其他按钮标题 /// - parameter completeBlock: 点击按钮后的回调 public convenience init(title alertTitle :CKAlertViewStringable, message alertMessages :[CKAlertViewStringable]?, cancelButtonTitle :CKAlertViewStringable, majorButtonTitle :CKAlertViewStringable, anotherButtonTitle :CKAlertViewStringable, completeBlock :(((Int) -> Void))? = nil) { self.init(nibName: nil, bundle: nil) dismissCompleteBlock = completeBlock let componentMaker = CKAlertViewComponentMajorActionMaker() componentMaker.alertView = self componentMaker.alertTitle = alertTitle componentMaker.alertMessages = alertMessages componentMaker.cancelButtonTitle = cancelButtonTitle componentMaker.otherButtonTitles = [majorButtonTitle,anotherButtonTitle] componentMaker.indentationPatternWidth = indentationPatternWidth installComponentMaker(maker: componentMaker) } } class CKAlertViewBottomSplitLineHeaderView : CKAlertViewHeaderView { override func setup() { super.setup() textFont = UIFont.systemFont(ofSize: 15) } override func makeLayout() { super.makeLayout() let splitLineView = UIView() splitLineView.backgroundColor = config().splitLineColor addSubview(splitLineView) splitLineView.snp.makeConstraints { (make) in make.bottom.equalTo(self).offset(-20) make.left.equalTo(self).offset(20) make.right.equalTo(self).offset(-20) make.height.equalTo(config().splitLineWidth) } if let titleLabel = subviews.first { titleLabel.snp.remakeConstraints({ (make) in make.top.equalTo(self).offset(20) make.left.equalTo(self).offset(20) make.right.equalTo(self).offset(-20) make.bottom.equalTo(splitLineView).offset(-20) }) } } } class CKAlertViewMajorActionFooterView : CKAlertViewFooterView { override func setup() { super.setup() textColor = HexColor(0x666666,1) cancelButtonTitleColor = HexColor(0x666666,1) } override func makeFooterTopHSplitLine() -> UIView? { return nil } override func layoutMultiButtons () { if otherButtons.count == 2 { let majorButton = otherButtons.first let anotherButton = otherButtons[1] majorButton?.backgroundColor = HexColor(0x49bc1e,1) majorButton?.layer.cornerRadius = 3 majorButton?.layer.masksToBounds = true majorButton?.setTitleColor(UIColor.white, for: .normal) majorButton?.snp.makeConstraints({ (make) in make.top.equalTo(self) make.left.equalTo(self).offset(20) make.height.equalTo(36) make.right.equalTo(self).offset(-20) }) cancelButton.snp.makeConstraints { (make) in make.top.equalTo(majorButton!.snp.bottom).offset(20) make.left.equalTo(self).offset(20) make.height.equalTo(36) make.bottom.equalTo(self).offset(-20) } anotherButton.snp.makeConstraints { (make) in make.left.equalTo(cancelButton.snp.right).offset(20) make.top.bottom.equalTo(cancelButton) make.width.height.equalTo(cancelButton) make.right.equalTo(self).offset(-20) } } } } class CKAlertViewComponentMajorActionMaker :CKAlertViewComponentMaker { override func makeHeader() -> CKAlertViewComponent? { let headerView = CKAlertViewBottomSplitLineHeaderView() headerView.alertTitle = alertTitle headerView.alertTitle = alertTitle return headerView } override func makeBody() -> CKAlertViewComponent? { let bodyView = super.makeBody() bodyView?.textColor = HexColor(0x666666,1) return bodyView } override func makeFooter() -> CKAlertViewComponent? { let footerView = CKAlertViewMajorActionFooterView() footerView.delegate = delegate footerView.cancelButtonTitle = cancelButtonTitle footerView.otherButtonTitles = otherButtonTitles return footerView } }
mit
recoveryrecord/SurveyNative
SurveyNative/Classes/TableViewCells/TableViewCellActivating.swift
1
186
// // TableViewCellActivating.swift // Pods // // Created by Nora Mullaney on 5/10/17. // // import Foundation public protocol TableViewCellActivating { func cellDidActivate() }
mit
Pyroh/CoreGeometry
Sources/CoreGeometry/Extensions/simdExtension.swift
1
530
// // File.swift // // // Created by Pierre Tacchi on 26/03/21. // import simd @inlinable func sqrt(_ x: SIMD2<Float>) -> SIMD2<Float> { 1 / rsqrt(x) } @inlinable func sqrt(_ x: SIMD2<Double>) -> SIMD2<Double> { 1 / rsqrt(x) } @inlinable func sqrt(_ x: SIMD3<Float>) -> SIMD3<Float> { 1 / rsqrt(x) } @inlinable func sqrt(_ x: SIMD3<Double>) -> SIMD3<Double> { 1 / rsqrt(x) } @inlinable func sqrt(_ x: SIMD4<Float>) -> SIMD4<Float> { 1 / rsqrt(x) } @inlinable func sqrt(_ x: SIMD4<Double>) -> SIMD4<Double> { 1 / rsqrt(x) }
mit
STShenZhaoliang/STKitSwift
STKitSwift/STAreaPickerView.swift
1
7324
// // STAreaPickerView.swift // STKitSwiftDemo // // Created by mac on 2019/7/8. // Copyright © 2019 沈兆良. All rights reserved. // import UIKit import SnapKit struct STChinaRegionsModel: Codable { var code:String? var name:String? var children:[STChinaRegionsModel]? } public class STAreaPickerView: UIButton { // MARK: 1.lift cycle override init(frame: CGRect) { super.init(frame: frame) addTarget(self, action: #selector(hidden), for: .touchUpInside) provinceRegion = models.first cityModels = provinceRegion?.children ?? [] cityRegion = cityModels.first areaModels = cityRegion?.children ?? [] areaRegion = areaModels.first contentView.snp.makeConstraints { (maker) in maker.left.right.equalToSuperview() maker.height.equalTo(260) maker.bottom.equalTo(260) } pickerView.snp.makeConstraints { (maker) in maker.left.right.bottom.equalToSuperview() maker.height.equalTo(216) } topView.snp.makeConstraints { (maker) in maker.left.right.equalToSuperview() maker.height.equalTo(44) maker.bottom.equalTo(pickerView.snp.top) } buttonCancel.snp.makeConstraints { (maker) in maker.left.top.bottom.equalToSuperview() maker.width.equalTo(66) } buttonOK.snp.makeConstraints { (maker) in maker.right.top.bottom.equalToSuperview() maker.width.equalTo(66) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: 2.private methods public class func show(inView view:UIView, selectedBlock block:((String?, String?, String?, String?, String?, String?) -> ())?){ let pickerView = STAreaPickerView() view.addSubview(pickerView) pickerView.snp.makeConstraints { (maker) in maker.edges.equalToSuperview() } pickerView.selectedBlock = block pickerView.show() } @objc func show(){ UIView.animate(withDuration: 0.3) { self.contentView.snp.updateConstraints({ (maker) in maker.bottom.equalTo(0) }) } } @objc func hidden(){ contentView.snp.updateConstraints({ (maker) in maker.bottom.equalTo(260) }) UIView.animate(withDuration: 0.3, animations: { self.layoutIfNeeded() }) { (finish) in self.removeFromSuperview() } } // MARK: 3.event response @objc func actionOK(){ selectedBlock?(provinceRegion?.name, provinceRegion?.code, cityRegion?.name, cityRegion?.code, areaRegion?.name, areaRegion?.code) hidden() } // MARK: 4.interface private lazy var models: [STChinaRegionsModel] = { let models:[STChinaRegionsModel]? = try? JSONDecoder().decode([STChinaRegionsModel].self, from: Data.st_data(named: "pca-code")) return models ?? [] }() private var cityModels:[STChinaRegionsModel] = [] private var areaModels:[STChinaRegionsModel] = [] private var provinceRegion:STChinaRegionsModel? private var cityRegion:STChinaRegionsModel? private var areaRegion:STChinaRegionsModel? private var selectedBlock:((String?, String?, String?, String?, String?, String?) -> ())? // MARK: 5.getter private lazy var contentView: UIView = { let contentView = UIView() contentView.backgroundColor = .white addSubview(contentView) return contentView }() private lazy var pickerView: UIPickerView = { let pickerView = UIPickerView() pickerView.backgroundColor = .white pickerView.dataSource = self pickerView.delegate = self contentView.addSubview(pickerView) return pickerView }() private lazy var topView: UIView = { let topView = UIView() topView.backgroundColor = UIColor.init(red: 245.0/255, green: 245.0/255, blue: 245.0/255, alpha: 1) contentView.addSubview(topView) return topView }() private lazy var buttonCancel: UIButton = { let button = UIButton() button.setTitle("取消", for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 17) button.setTitleColor( UIColor.init(red: 0/255, green: 122.0/255, blue: 255.0/255, alpha: 1), for: .normal) button.addTarget(self, action: #selector(hidden), for: .touchUpInside) topView.addSubview(button) return button }() private lazy var buttonOK: UIButton = { let button = UIButton() button.setTitle("完成", for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17) button.setTitleColor( UIColor.init(red: 0/255, green: 122.0/255, blue: 255.0/255, alpha: 1), for: .normal) button.addTarget(self, action: #selector(actionOK), for: .touchUpInside) topView.addSubview(button) return button }() } extension STAreaPickerView: UIPickerViewDataSource{ public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 3 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch component { case 0: return models.count case 1: return cityModels.count default: return areaModels.count } } } extension STAreaPickerView: UIPickerViewDelegate{ public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { var text = "" switch component { case 0: text = models[row].name ?? "" case 1: text = cityModels[row].name ?? "" default: text = areaModels[row].name ?? "" } let label = UILabel() label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 19) label.adjustsFontSizeToFitWidth = true label.text = text return label } public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch component { case 0: provinceRegion = models[row] cityModels = provinceRegion?.children ?? [] cityRegion = cityModels.first areaModels = cityRegion?.children ?? [] areaRegion = areaModels.first pickerView.reloadComponent(1) pickerView.reloadComponent(2) pickerView.selectRow(0, inComponent: 1, animated: true) pickerView.selectRow(0, inComponent: 2, animated: true) case 1: cityRegion = cityModels[row] areaModels = cityRegion?.children ?? [] areaRegion = areaModels.first pickerView.reloadComponent(2) pickerView.selectRow(0, inComponent: 2, animated: true) default: areaRegion = areaModels[row] break } } }
mit
Colrying/DouYuZB
DouYuZB/DouYuZB/Classes/Tools/NetworkTools.swift
1
889
// // NetworkTools.swift // DouYuZB // // Created by 皇坤鹏 on 17/4/13. // Copyright © 2017年 皇坤鹏. All rights reserved. // import UIKit import Alamofire enum MethodType { case GET case POST } // 删除集成,更轻量级 class NetworkTools { class func requestData(type: MethodType, urlString: String, parameters: [String: Any], finishedCallback: @escaping (_ result : AnyObject) -> ()) { // 1. 获取类型 let method = type == .GET ? HTTPMethod.get : HTTPMethod.post Alamofire.request(urlString, method: method, parameters: parameters).responseJSON { (response) in guard let result = response.result.value else { print(response.result.error!) return } // 回调结果 finishedCallback(result as AnyObject) } } }
mit
zhangjk4859/animal-plant_pool
animal-plant_pool/animal-plant_pool/其他/Controller/LoginVC.swift
1
1453
// // LoginVC.swift // animal-plant_pool // // Created by 张俊凯 on 2017/2/14. // Copyright © 2017年 张俊凯. All rights reserved. // import UIKit class LoginVC: UIViewController{ var backgroundImageView:UIImageView? var tableView : UITableView? override func viewDidLoad() { super.viewDidLoad() //首先添加一个imageView backgroundImageView = UIImageView(image: UIImage(named: "background")) view.backgroundColor = UIColor.white view.addSubview(backgroundImageView!) //颜色渐变 //添加三个按钮,宽度平分成六份 let width = view.width / 6 let height = width + 30 var names = ["手机登录","微信登录","QQ登录"] var imageNames = ["login_mobile","login_weixin","login_QQ"] for index in 0 ..< 3 { let btn = JKVerticalButton.init(type: UIButtonType.custom) view.addSubview(btn) btn.frame = CGRect(x: CGFloat(Float(index)) * width * 2 + width * 0.5, y: backgroundImageView!.frame.maxY + width, width: width, height: height) btn.setTitle(names[index], for: UIControlState.normal) btn.titleLabel?.adjustsFontSizeToFitWidth = true btn.setTitleColor(UIColor.black, for: .normal) btn.setImage(UIImage(named:imageNames[index]), for: UIControlState.normal) } } }
mit
xedin/swift
test/Driver/batch_mode_aux_file_order.swift
4
2213
// When multiple additional-outputs on the same command-line are no longer // supported (i.e. when we've moved to mandatory use of output file maps for // communicating multiple additional-outputs to frontends) this test will no // longer make sense, and should be removed. // // RUN: %empty-directory(%t) // RUN: touch %t/file-01.swift %t/file-02.swift %t/file-03.swift %t/file-04.swift %t/file-05.swift // RUN: touch %t/file-06.swift %t/file-07.swift %t/file-08.swift %t/file-09.swift // // RUN: %swiftc_driver -enable-batch-mode -driver-batch-seed 1 -driver-print-jobs -driver-skip-execution -j 3 -emit-module -module-name foo %t/file-01.swift %t/file-02.swift %t/file-03.swift %t/file-04.swift %t/file-05.swift %t/file-06.swift %t/file-07.swift %t/file-08.swift %t/file-09.swift >%t/out.txt // RUN: %FileCheck %s <%t/out.txt // // Each batch should get 3 primaries; check that each has 3 modules _in the same numeric order_. // // CHECK: {{.*[\\/]}}swift{{c?(\.EXE)?"?}} {{.*}}-primary-file {{[^ ]*[\\/]}}file-[[A1:[0-9]+]].swift{{"?}} {{.*}}-primary-file {{[^ ]*[\\/]}}file-[[A2:[0-9]+]].swift{{"?}} {{.*}}-primary-file {{[^ ]*[\\/]}}file-[[A3:[0-9]+]].swift{{"?}} // CHECK-SAME: -o {{.*[\\/]}}file-[[A1]]-{{[a-z0-9]+}}.swiftmodule{{"?}} -o {{.*[\\/]}}file-[[A2]]-{{[a-z0-9]+}}.swiftmodule{{"?}} -o {{.*[\\/]}}file-[[A3]]-{{[a-z0-9]+}}.swiftmodule{{"?}} // CHECK: {{.*[\\/]}}swift{{c?(\.EXE)?"?}} {{.*}}-primary-file {{[^ ]*[\\/]}}file-[[B1:[0-9]+]].swift{{"?}} {{.*}}-primary-file {{[^ ]*[\\/]}}file-[[B2:[0-9]+]].swift{{"?}} {{.*}}-primary-file {{[^ ]*[\\/]}}file-[[B3:[0-9]+]].swift{{"?}} // CHECK-SAME: -o {{.*[\\/]}}file-[[B1]]-{{[a-z0-9]+}}.swiftmodule{{"?}} -o {{.*[\\/]}}file-[[B2]]-{{[a-z0-9]+}}.swiftmodule{{"?}} -o {{.*[\\/]}}file-[[B3]]-{{[a-z0-9]+}}.swiftmodule{{"?}} // CHECK: {{.*[\\/]}}swift{{c?(\.EXE)?"?}} {{.*}}-primary-file {{[^ ]*[\\/]}}file-[[C1:[0-9]+]].swift{{"?}} {{.*}}-primary-file {{[^ ]*[\\/]}}file-[[C2:[0-9]+]].swift{{"?}} {{.*}}-primary-file {{[^ ]*[\\/]}}file-[[C3:[0-9]+]].swift{{"?}} // CHECK-SAME: -o {{.*[\\/]}}file-[[C1]]-{{[a-z0-9]+}}.swiftmodule{{"?}} -o {{.*[\\/]}}file-[[C2]]-{{[a-z0-9]+}}.swiftmodule{{"?}} -o {{.*[\\/]}}file-[[C3]]-{{[a-z0-9]+}}.swiftmodule{{"?}}
apache-2.0
crazypoo/PTools
Pods/Appz/Appz/Appz/Apps/RoboForm.swift
2
1009
// // RoboForm.swift // Pods // // Created by Mariam AlJamea on 1/19/16. // Copyright © 2016 kitz. All rights reserved. // public extension Applications { public struct RoboForm: ExternalApplication { public typealias ActionType = Applications.RoboForm.Action public let scheme = "roboform:" public let fallbackURL = "http://www.roboform.com/for-iphone-ipad-ios" public let appStoreId = "331787573" public init() {} } } // MARK: - Actions public extension Applications.RoboForm { public enum Action { case open } } extension Applications.RoboForm.Action: ExternalApplicationAction { public var paths: ActionPaths { switch self { case .open: return ActionPaths( app: Path( pathComponents: ["app"], queryParameters: [:] ), web: Path() ) } } }
mit
BenedictC/SwiftJSONReader
JSONReader/JSONReaderTests/JSONReaderTests.swift
1
7492
// // JSONReaderTests.swift // JSONReaderTests // // Created by Benedict Cohen on 09/12/2015. // Copyright © 2015 Benedict Cohen. All rights reserved. // import XCTest class JSONReaderTests: XCTestCase { func testObjectProperty() { //Given let reader = JSONReader(rootValue: []) //Valid object XCTAssertNotNil(reader.rootValue) XCTAssertFalse(reader.isEmpty) //InvalidObject let emptyReader = JSONReader(rootValue: nil) XCTAssertNil(emptyReader.rootValue) XCTAssertTrue(emptyReader.isEmpty) } func testInitWithJSONValidData() { //Given let expected = ["foo": "bar"] as NSDictionary let data = (try? JSONSerialization.data(withJSONObject: expected, options: [])) ?? Data() //When let reader = try? JSONReader(data: data) let actual: NSDictionary = (reader?.rootValue as? NSDictionary) ?? NSDictionary() //Then XCTAssertEqual(actual, expected) } func testInitWithJSONInvalidData() { //Given let data = Data() //When let reader = try? JSONReader(data: data) //Then XCTAssertNil(reader) } func testInitWithJSONDataWithFragmentTrue() { //Given let expected = NSNull() let data = "null".data(using: String.Encoding.utf8)! //When let reader = try? JSONReader(data: data, allowFragments: true) let actual = reader?.rootValue as? NSNull //Then if let actual = actual { XCTAssertEqual(actual, expected) } else { XCTFail() } } func testInitWithJSONDataWithFragmentFalse() { //Given let data = "null".data(using: String.Encoding.utf8)! //When let reader = try? JSONReader(data: data, allowFragments: false) //Then XCTAssertNil(reader) } func testValue() { //Given let expected: Float = 4.5 let reader = JSONReader(rootValue: expected) //When let actual = reader.value() as Float? //Then XCTAssertEqual(expected, actual) } func testIsValidPositiveIndex() { //Given let array = [0,1,2] let reader = JSONReader(rootValue: array) //When let actual = reader.isValidIndex(array.count - 1) //Then let expected = true XCTAssertEqual(actual, expected) } func testIsInvalidPositiveIndex() { //Given let array = [0,1,2] let reader = JSONReader(rootValue: array) //When let actual = reader.isValidIndex(Int.max) //Then let expected = false XCTAssertEqual(actual, expected) } func testIsValidNegativeIndex() { //Given let array = [0,1,2] let reader = JSONReader(rootValue: array) //When let actual = reader.isValidIndex(-array.count) //Then let expected = true XCTAssertEqual(actual, expected) } func testIsInvalidNegativeIndex() { //Given let array = [0,1,2] let reader = JSONReader(rootValue: array) //When let actual = reader.isValidIndex(Int.min) //Then let expected = false XCTAssertEqual(actual, expected) } func testValidPositiveNumericSubscript() { //Given let array = ["zero", "one", "two"] let reader = JSONReader(rootValue: array) //When let actual = reader[0].rootValue as? NSObject //Then let expected = JSONReader(rootValue: array.first!).rootValue as? NSObject XCTAssertEqual(actual, expected) } func testInvalidPositiveNumericSubscript() { //Given let array = ["zero", "one", "two"] let reader = JSONReader(rootValue: array) //When let actual = reader[Int.max].rootValue as? NSObject //Then let expected = JSONReader(rootValue: nil).rootValue as? NSObject XCTAssertEqual(actual, expected) } func testValidNegativeNumericSubscript() { //Given let array = ["zero", "one", "two"] let reader = JSONReader(rootValue: array) //When let actual = reader[-array.count].rootValue as? NSObject //Then let expected = JSONReader(rootValue: array.first!).rootValue as? NSObject XCTAssertEqual(actual, expected) } func testInvalidNegativeNumericSubscript() { //Given let array = ["zero", "one", "two"] let reader = JSONReader(rootValue: array) //When let actual = reader[Int.min].rootValue as? NSObject //Then let expected = JSONReader(rootValue: nil).rootValue as? NSObject XCTAssertEqual(actual, expected) } //MARK: func testIsValidKeyHappy() { //Given let key = "foo" let value = "bar" let dict = [key: value] let reader = JSONReader(rootValue: dict) //When let actual = reader.isValidKey(key) //Then let expected = true XCTAssertEqual(actual, expected) } func testIsValidKeyUnhappy() { //Given let key = "foo" let value = "bar" let dict = [key: value] let reader = JSONReader(rootValue: dict) //When let unhappyKey = "asgrdhf" let actual = reader.isValidKey(unhappyKey) //Then let expected = false XCTAssertEqual(actual, expected) } func testStringSubscriptValid() { //Given let key = "foo" let value = "bar" let dict = [key: value] let reader = JSONReader(rootValue: dict) //When let actual = reader[key].rootValue as? NSObject //Then let expected = JSONReader(rootValue: value).rootValue as? NSObject XCTAssertEqual(actual, expected) } func testStringSubscriptInvalid() { //Given let key = "foo" let value = "bar" let dict = [key: value] let reader = JSONReader(rootValue: dict) //When let unhappyKey = "aegrsetwr" let actual = reader[unhappyKey].rootValue as? NSObject //Then let expected = JSONReader(rootValue: nil).rootValue as? NSObject XCTAssertEqual(actual, expected) } } class JSONReaderJSONPathTests: XCTestCase { func testReaderAtPathValid() { //Given let value = true let dict = ["key": value] let reader = JSONReader(rootValue: dict) //When let actual = (try? reader.reader(at:"key"))?.rootValue as? NSObject ?? JSONReader(rootValue: nil).rootValue as? NSObject //Then let expected = JSONReader(rootValue: value).rootValue as? NSObject XCTAssertEqual(actual, expected) } func testReaderAtPathInvalid() { //Given let dict = ["key": "value"] let reader = JSONReader(rootValue: dict) //When let actual: JSONReader? let actualError: Error? do { actual = try reader.reader(at: "arf") actualError = nil } catch { actualError = error actual = nil } //Then XCTAssertNotNil(actualError) XCTAssertNil(actual) } //TODO: Test errors are of expected value //TODO: 64 bit number edge cases }
mit
IngmarStein/swift
validation-test/IDE/crashers/085-swift-persistentparserstate-delaytoplevel.swift
1
156
// RUN: not --crash %target-swift-ide-test -code-completion -code-completion-token=A -source-filename=%s // REQUIRES: asserts class A{let:e({var _={" }#^A^#
apache-2.0
Moya/Moya
Tests/MoyaTests/EndpointSpec.swift
1
34050
import Quick import Moya import Nimble import Foundation final class NonUpdatingRequestEndpointConfiguration: QuickConfiguration { override static func configure(_ configuration: Configuration) { sharedExamples("endpoint with no request property changed") { (context: SharedExampleContext) in let task = context()["task"] as! Task let oldEndpoint = context()["endpoint"] as! Endpoint let endpoint = oldEndpoint.replacing(task: task) let request = try! endpoint.urlRequest() it("didn't update any of the request properties") { expect(request.httpBody).to(beNil()) expect(request.url?.absoluteString).to(equal(endpoint.url)) expect(request.allHTTPHeaderFields).to(equal(endpoint.httpHeaderFields)) expect(request.httpMethod).to(equal(endpoint.method.rawValue)) } } } } final class ParametersEncodedEndpointConfiguration: QuickConfiguration { override static func configure(_ configuration: Configuration) { sharedExamples("endpoint with encoded parameters") { (context: SharedExampleContext) in let parameters = context()["parameters"] as! [String: Any] let encoding = context()["encoding"] as! ParameterEncoding let endpoint = context()["endpoint"] as! Endpoint let request = try! endpoint.urlRequest() it("updated the request correctly") { let newEndpoint = endpoint.replacing(task: .requestPlain) let newRequest = try! newEndpoint.urlRequest() let newEncodedRequest = try? encoding.encode(newRequest, with: parameters) expect(request.httpBody).to(equal(newEncodedRequest?.httpBody)) expect(request.url?.absoluteString).to(equal(newEncodedRequest?.url?.absoluteString)) expect(request.allHTTPHeaderFields).to(equal(newEncodedRequest?.allHTTPHeaderFields)) expect(request.httpMethod).to(equal(newEncodedRequest?.httpMethod)) } } } } final class EndpointSpec: QuickSpec { private var simpleGitHubEndpoint: Endpoint { let target: GitHub = .zen let headerFields = ["Title": "Dominar"] return Endpoint(url: url(target), sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: Moya.Method.get, task: .requestPlain, httpHeaderFields: headerFields) } override func spec() { var endpoint: Endpoint! beforeEach { endpoint = self.simpleGitHubEndpoint } it("returns a new endpoint for adding(newHTTPHeaderFields:)") { let agent = "Zalbinian" let newEndpoint = endpoint.adding(newHTTPHeaderFields: ["User-Agent": agent]) let newEndpointAgent = newEndpoint.httpHeaderFields?["User-Agent"] // Make sure our closure updated the sample response, as proof that it can modify the Endpoint expect(newEndpointAgent).to(equal(agent)) // Compare other properties to ensure they've been copied correctly expect(newEndpoint.url).to(equal(endpoint.url)) expect(newEndpoint.method).to(equal(endpoint.method)) } it("returns a nil urlRequest for an invalid URL") { let badEndpoint = Endpoint(url: "some invalid URL", sampleResponseClosure: { .networkResponse(200, Data()) }, method: .get, task: .requestPlain, httpHeaderFields: nil) let urlRequest = try? badEndpoint.urlRequest() expect(urlRequest).to(beNil()) } describe("successful converting to urlRequest") { context("when task is .requestPlain") { itBehavesLike("endpoint with no request property changed") { ["task": Task.requestPlain, "endpoint": self.simpleGitHubEndpoint] } } context("when task is .uploadFile") { itBehavesLike("endpoint with no request property changed") { ["task": Task.uploadFile(URL(string: "https://google.com")!), "endpoint": self.simpleGitHubEndpoint] } } context("when task is .uploadMultipart") { itBehavesLike("endpoint with no request property changed") { ["task": Task.uploadMultipart([]), "endpoint": self.simpleGitHubEndpoint] } } context("when task is .downloadDestination") { itBehavesLike("endpoint with no request property changed") { let destination: DownloadDestination = { url, response in return (destinationURL: url, options: []) } return ["task": Task.downloadDestination(destination), "endpoint": self.simpleGitHubEndpoint] } } context("when task is .requestParameters") { itBehavesLike("endpoint with encoded parameters") { let parameters = ["Nemesis": "Harvey"] let encoding = JSONEncoding.default let endpoint = self.simpleGitHubEndpoint.replacing(task: .requestParameters(parameters: parameters, encoding: encoding)) return ["parameters": parameters, "encoding": encoding, "endpoint": endpoint] } } context("when task is .downloadParameters") { itBehavesLike("endpoint with encoded parameters") { let parameters = ["Nemesis": "Harvey"] let encoding = JSONEncoding.default let destination: DownloadDestination = { url, response in return (destinationURL: url, options: []) } let endpoint = self.simpleGitHubEndpoint.replacing(task: .downloadParameters(parameters: parameters, encoding: encoding, destination: destination)) return ["parameters": parameters, "encoding": encoding, "endpoint": endpoint] } } context("when task is .requestData") { var data: Data! var request: URLRequest! beforeEach { data = "test data".data(using: .utf8) endpoint = endpoint.replacing(task: .requestData(data)) request = try! endpoint.urlRequest() } it("updates httpBody") { expect(request.httpBody).to(equal(data)) } it("doesn't update any of the other properties") { expect(request.url?.absoluteString).to(equal(endpoint.url)) expect(request.allHTTPHeaderFields).to(equal(endpoint.httpHeaderFields)) expect(request.httpMethod).to(equal(endpoint.method.rawValue)) } } context("when task is .requestJSONEncodable") { var issue: Issue! var request: URLRequest! beforeEach { issue = Issue(title: "Hello, Moya!", createdAt: Date(), rating: 0) endpoint = endpoint.replacing(task: .requestJSONEncodable(issue)) request = try! endpoint.urlRequest() } it("updates httpBody") { let expectedIssue = try! JSONDecoder().decode(Issue.self, from: request.httpBody!) expect(issue.createdAt).to(equal(expectedIssue.createdAt)) expect(issue.title).to(equal(expectedIssue.title)) } it("updates headers to include Content-Type: application/json") { let contentTypeHeaders = ["Content-Type": "application/json"] let initialHeaderFields = endpoint.httpHeaderFields ?? [:] let expectedHTTPHeaderFields = initialHeaderFields.merging(contentTypeHeaders) { initialValue, _ in initialValue } expect(request.allHTTPHeaderFields).to(equal(expectedHTTPHeaderFields)) } it("doesn't update any of the other properties") { expect(request.url?.absoluteString).to(equal(endpoint.url)) expect(request.httpMethod).to(equal(endpoint.method.rawValue)) } } context("when task is .requestCustomJSONEncodable") { var issue: Issue! var request: URLRequest! let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" let encoder = JSONEncoder() encoder.dateEncodingStrategy = .formatted(formatter) let decoder = JSONDecoder() decoder.dateDecodingStrategy = .formatted(formatter) beforeEach { issue = Issue(title: "Hello, Moya!", createdAt: Date(), rating: 0) endpoint = endpoint.replacing(task: .requestCustomJSONEncodable(issue, encoder: encoder)) request = try! endpoint.urlRequest() } it("updates httpBody") { let expectedIssue = try! decoder.decode(Issue.self, from: request.httpBody!) expect(formatter.string(from: issue.createdAt)).to(equal(formatter.string(from: expectedIssue.createdAt))) expect(issue.title).to(equal(expectedIssue.title)) } it("updates headers to include Content-Type: application/json") { let contentTypeHeaders = ["Content-Type": "application/json"] let initialHeaderFields = endpoint.httpHeaderFields ?? [:] let expectedHTTPHeaderFields = initialHeaderFields.merging(contentTypeHeaders) { initialValue, _ in initialValue } expect(request.allHTTPHeaderFields).to(equal(expectedHTTPHeaderFields)) } it("doesn't update any of the other properties") { expect(request.url?.absoluteString).to(equal(endpoint.url)) expect(request.httpMethod).to(equal(endpoint.method.rawValue)) } } context("when task is .requestCompositeData") { var parameters: [String: Any]! var data: Data! var request: URLRequest! beforeEach { parameters = ["Nemesis": "Harvey"] data = "test data".data(using: .utf8) endpoint = endpoint.replacing(task: .requestCompositeData(bodyData: data, urlParameters: parameters)) request = try! endpoint.urlRequest() } it("updates url") { let expectedUrl = endpoint.url + "?Nemesis=Harvey" expect(request.url?.absoluteString).to(equal(expectedUrl)) } it("updates httpBody") { expect(request.httpBody).to(equal(data)) } it("doesn't update any of the other properties") { expect(request?.allHTTPHeaderFields).to(equal(endpoint.httpHeaderFields)) expect(request?.httpMethod).to(equal(endpoint.method.rawValue)) } } context("when task is .requestCompositeParameters") { var bodyParameters: [String: Any]! var urlParameters: [String: Any]! var encoding: ParameterEncoding! var request: URLRequest! beforeEach { bodyParameters = ["Nemesis": "Harvey"] urlParameters = ["Harvey": "Nemesis"] encoding = JSONEncoding.default endpoint = endpoint.replacing(task: .requestCompositeParameters(bodyParameters: bodyParameters, bodyEncoding: encoding, urlParameters: urlParameters)) request = try! endpoint.urlRequest() } it("updates url") { let expectedUrl = endpoint.url + "?Harvey=Nemesis" expect(request.url?.absoluteString).to(equal(expectedUrl)) } it("updates the request correctly") { let newEndpoint = endpoint.replacing(task: .requestPlain) let newRequest = try! newEndpoint.urlRequest() let newEncodedRequest = try? encoding.encode(newRequest, with: bodyParameters) expect(request.httpBody).to(equal(newEncodedRequest?.httpBody)) expect(request.allHTTPHeaderFields).to(equal(newEncodedRequest?.allHTTPHeaderFields)) expect(request.httpMethod).to(equal(newEncodedRequest?.httpMethod)) } } context("when task is .uploadCompositeMultipart") { var urlParameters: [String: Any]! var request: URLRequest! beforeEach { urlParameters = ["Harvey": "Nemesis"] endpoint = endpoint.replacing(task: .uploadCompositeMultipart([], urlParameters: urlParameters)) request = try! endpoint.urlRequest() } it("updates url") { let expectedUrl = endpoint.url + "?Harvey=Nemesis" expect(request.url?.absoluteString).to(equal(expectedUrl)) } } } describe("unsuccessful converting to urlRequest") { context("when url String is invalid") { it("throws a .requestMapping error") { let badEndpoint = Endpoint(url: "some invalid URL", sampleResponseClosure: { .networkResponse(200, Data()) }, method: .get, task: .requestPlain, httpHeaderFields: nil) let expectedError = MoyaError.requestMapping("some invalid URL") var recievedError: MoyaError? do { _ = try badEndpoint.urlRequest() } catch { recievedError = error as? MoyaError } expect(recievedError).toNot(beNil()) expect(recievedError).to(beOfSameErrorType(expectedError)) } } context("when parameter encoding is unsuccessful") { it("throws a .parameterEncoding error") { // Non-serializable type to cause serialization error class InvalidParameter {} endpoint = endpoint.replacing(task: .requestParameters(parameters: ["": InvalidParameter()], encoding: PropertyListEncoding.default)) let cocoaError = NSError(domain: "NSCocoaErrorDomain", code: 3851, userInfo: ["NSDebugDescription": "Property list invalid for format: 100 (property lists cannot contain objects of type 'CFType')"]) let expectedError = MoyaError.parameterEncoding(cocoaError) var recievedError: MoyaError? do { _ = try endpoint.urlRequest() } catch { recievedError = error as? MoyaError } expect(recievedError).toNot(beNil()) expect(recievedError).to(beOfSameErrorType(expectedError)) } } context("when JSONEncoder set with incorrect parameters") { it("throws a .encodableMapping error") { let encoder = JSONEncoder() let issue = Issue(title: "Hello, Moya!", createdAt: Date(), rating: Float.infinity) endpoint = endpoint.replacing(task: .requestCustomJSONEncodable(issue, encoder: encoder)) let expectedError = MoyaError.encodableMapping(EncodingError.invalidValue(Float.infinity, EncodingError.Context(codingPath: [Issue.CodingKeys.rating], debugDescription: "Unable to encode Float.infinity directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded.", underlyingError: nil))) var recievedError: MoyaError? do { _ = try endpoint.urlRequest() } catch { recievedError = error as? MoyaError } expect(recievedError).toNot(beNil()) expect(recievedError).to(beOfSameErrorType(expectedError)) } } #if !SWIFT_PACKAGE context("when task is .requestCompositeParameters") { it("throws an error when bodyEncoding is an URLEncoding.queryString") { endpoint = endpoint.replacing(task: .requestCompositeParameters(bodyParameters: [:], bodyEncoding: URLEncoding.queryString, urlParameters: [:])) expect({ _ = try? endpoint.urlRequest() }).to(throwAssertion()) } it("throws an error when bodyEncoding is an URLEncoding.default") { endpoint = endpoint.replacing(task: .requestCompositeParameters(bodyParameters: [:], bodyEncoding: URLEncoding.default, urlParameters: [:])) expect({ _ = try? endpoint.urlRequest() }).to(throwAssertion()) } it("doesn't throw an error when bodyEncoding is an URLEncoding.httpBody") { endpoint = endpoint.replacing(task: .requestCompositeParameters(bodyParameters: [:], bodyEncoding: URLEncoding.httpBody, urlParameters: [:])) expect({ _ = try? endpoint.urlRequest() }).toNot(throwAssertion()) } } #endif } describe("given endpoint comparison") { context("when task is .uploadMultipart") { it("should correctly acknowledge as equal for the same url, headers and form data") { endpoint = endpoint.replacing(task: .uploadMultipart([MultipartFormData(provider: .data("test".data(using: .utf8)!), name: "test")])) let endpointToCompare = endpoint.replacing(task: .uploadMultipart([MultipartFormData(provider: .data("test".data(using: .utf8)!), name: "test")])) expect(endpoint) == endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers and different form data") { endpoint = endpoint.replacing(task: .uploadMultipart([MultipartFormData(provider: .data("test".data(using: .utf8)!), name: "test")])) let endpointToCompare = endpoint.replacing(task: .uploadMultipart([MultipartFormData(provider: .data("test1".data(using: .utf8)!), name: "test")])) expect(endpoint) != endpointToCompare } } context("when task is .uploadCompositeMultipart") { it("should correctly acknowledge as equal for the same url, headers and form data") { endpoint = endpoint.replacing(task: .uploadCompositeMultipart([MultipartFormData(provider: .data("test".data(using: .utf8)!), name: "test")], urlParameters: [:])) let endpointToCompare = endpoint.replacing(task: .uploadCompositeMultipart([MultipartFormData(provider: .data("test".data(using: .utf8)!), name: "test")], urlParameters: [:])) expect(endpoint) == endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers and different form data") { endpoint = endpoint.replacing(task: .uploadCompositeMultipart([MultipartFormData(provider: .data("test".data(using: .utf8)!), name: "test")], urlParameters: [:])) let endpointToCompare = endpoint.replacing(task: .uploadCompositeMultipart([MultipartFormData(provider: .data("test1".data(using: .utf8)!), name: "test")], urlParameters: [:])) expect(endpoint) != endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers and different url parameters") { endpoint = endpoint.replacing(task: .uploadCompositeMultipart([MultipartFormData(provider: .data("test".data(using: .utf8)!), name: "test")], urlParameters: ["test": "test2"])) let endpointToCompare = endpoint.replacing(task: .uploadCompositeMultipart([MultipartFormData(provider: .data("test".data(using: .utf8)!), name: "test")], urlParameters: ["test": "test3"])) expect(endpoint) != endpointToCompare } } context("when task is .uploadFile") { it("should correctly acknowledge as equal for the same url, headers and file") { endpoint = endpoint.replacing(task: .uploadFile(URL(string: "https://google.com")!)) let endpointToCompare = endpoint.replacing(task: .uploadFile(URL(string: "https://google.com")!)) expect(endpoint) == endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers and different file") { endpoint = endpoint.replacing(task: .uploadFile(URL(string: "https://google.com")!)) let endpointToCompare = endpoint.replacing(task: .uploadFile(URL(string: "https://google.com?q=test")!)) expect(endpoint) != endpointToCompare } } context("when task is .downloadDestination") { it("should correctly acknowledge as equal for the same url, headers and download destination") { endpoint = endpoint.replacing(task: .downloadDestination { temporaryUrl, _ in return (destinationURL: temporaryUrl, options: []) }) let endpointToCompare = endpoint.replacing(task: .downloadDestination { temporaryUrl, _ in return (destinationURL: temporaryUrl, options: []) }) expect(endpoint) == endpointToCompare } it("should correctly acknowledge as equal for the same url, headers and different download destination") { endpoint = endpoint.replacing(task: .downloadDestination { temporaryUrl, _ in return (destinationURL: temporaryUrl, options: []) }) let endpointToCompare = endpoint.replacing(task: .downloadDestination { _, _ in return (destinationURL: URL(string: "https://google.com")!, options: []) }) expect(endpoint) == endpointToCompare } } context("when task is .downloadParameters") { it("should correctly acknowledge as equal for the same url, headers and download destination") { endpoint = endpoint.replacing(task: .downloadParameters(parameters: ["test": "test2"], encoding: JSONEncoding.default, destination: { temporaryUrl, _ in return (destinationURL: temporaryUrl, options: []) })) let endpointToCompare = endpoint.replacing(task: .downloadParameters(parameters: ["test": "test2"], encoding: JSONEncoding.default, destination: { temporaryUrl, _ in return (destinationURL: temporaryUrl, options: []) })) expect(endpoint) == endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers, download destionation and different parameters") { endpoint = endpoint.replacing(task: .downloadParameters(parameters: ["test": "test2"], encoding: JSONEncoding.default, destination: { temporaryUrl, _ in return (destinationURL: temporaryUrl, options: []) })) let endpointToCompare = endpoint.replacing(task: .downloadParameters(parameters: ["test": "test3"], encoding: JSONEncoding.default, destination: { temporaryUrl, _ in return (destinationURL: temporaryUrl, options: []) })) expect(endpoint) != endpointToCompare } } context("when task is .requestCompositeData") { it("should correctly acknowledge as equal for the same url, headers, body and url parameters") { endpoint = endpoint.replacing(task: .requestCompositeData(bodyData: "test".data(using: .utf8)!, urlParameters: ["test": "test1"])) let endpointToCompare = endpoint.replacing(task: .requestCompositeData(bodyData: "test".data(using: .utf8)!, urlParameters: ["test": "test1"])) expect(endpoint) == endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers, body and different url parameters") { endpoint = endpoint.replacing(task: .requestCompositeData(bodyData: "test".data(using: .utf8)!, urlParameters: ["test": "test1"])) let endpointToCompare = endpoint.replacing(task: .requestCompositeData(bodyData: "test".data(using: .utf8)!, urlParameters: ["test": "test2"])) expect(endpoint) != endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers, url parameters and different body") { endpoint = endpoint.replacing(task: .requestCompositeData(bodyData: "test".data(using: .utf8)!, urlParameters: ["test": "test1"])) let endpointToCompare = endpoint.replacing(task: .requestCompositeData(bodyData: "test2".data(using: .utf8)!, urlParameters: ["test": "test1"])) expect(endpoint) != endpointToCompare } } context("when task is .requestPlain") { it("should correctly acknowledge as equal for the same url, headers and body") { endpoint = endpoint.replacing(task: .requestPlain) let endpointToCompare = endpoint.replacing(task: .requestPlain) expect(endpoint) == endpointToCompare } } context("when task is .requestData") { it("should correctly acknowledge as equal for the same url, headers and data") { endpoint = endpoint.replacing(task: .requestData("test".data(using: .utf8)!)) let endpointToCompare = endpoint.replacing(task: .requestData("test".data(using: .utf8)!)) expect(endpoint) == endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers and different data") { endpoint = endpoint.replacing(task: .requestData("test".data(using: .utf8)!)) let endpointToCompare = endpoint.replacing(task: .requestData("test1".data(using: .utf8)!)) expect(endpoint) != endpointToCompare } } context("when task is .requestJSONEncodable") { it("should correctly acknowledge as equal for the same url, headers and encodable") { let date = Date() endpoint = endpoint.replacing(task: .requestJSONEncodable(Issue(title: "T", createdAt: date, rating: 0))) let endpointToCompare = endpoint.replacing(task: .requestJSONEncodable(Issue(title: "T", createdAt: date, rating: 0))) expect(endpoint) == endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers and different encodable") { let date = Date() endpoint = endpoint.replacing(task: .requestJSONEncodable(Issue(title: "T", createdAt: date, rating: 0))) let endpointToCompare = endpoint.replacing(task: .requestJSONEncodable(Issue(title: "Ta", createdAt: date, rating: 0))) expect(endpoint) != endpointToCompare } } context("when task is .requestParameters") { it("should correctly acknowledge as equal for the same url, headers and parameters") { endpoint = endpoint.replacing(task: .requestParameters(parameters: ["test": "test1"], encoding: URLEncoding.queryString)) let endpointToCompare = endpoint.replacing(task: .requestParameters(parameters: ["test": "test1"], encoding: URLEncoding.queryString)) expect(endpoint) == endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers and different parameters") { endpoint = endpoint.replacing(task: .requestParameters(parameters: ["test": "test1"], encoding: URLEncoding.queryString)) let endpointToCompare = endpoint.replacing(task: .requestParameters(parameters: ["test": "test2"], encoding: URLEncoding.queryString)) expect(endpoint) != endpointToCompare } } context("when task is .requestCompositeParameters") { it("should correctly acknowledge as equal for the same url, headers, body and url parameters") { endpoint = endpoint.replacing(task: .requestCompositeParameters(bodyParameters: ["test": "test1"], bodyEncoding: JSONEncoding.default, urlParameters: ["url_test": "test1"])) let endpointToCompare = endpoint.replacing(task: .requestCompositeParameters(bodyParameters: ["test": "test1"], bodyEncoding: JSONEncoding.default, urlParameters: ["url_test": "test1"])) expect(endpoint) == endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers, body parameters and different url parameters") { endpoint = endpoint.replacing(task: .requestCompositeParameters(bodyParameters: ["test": "test1"], bodyEncoding: JSONEncoding.default, urlParameters: ["url_test": "test1"])) let endpointToCompare = endpoint.replacing(task: .requestCompositeParameters(bodyParameters: ["test": "test1"], bodyEncoding: JSONEncoding.default, urlParameters: ["url_test": "test2"])) expect(endpoint) != endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers, url parameters and different body parameters") { endpoint = endpoint.replacing(task: .requestCompositeParameters(bodyParameters: ["test": "test1"], bodyEncoding: JSONEncoding.default, urlParameters: ["url_test": "test1"])) let endpointToCompare = endpoint.replacing(task: .requestCompositeParameters(bodyParameters: ["test": "test2"], bodyEncoding: JSONEncoding.default, urlParameters: ["url_test": "test1"])) expect(endpoint) != endpointToCompare } } context("when task is .requestCustomJSONEncodable") { it("should correctly acknowledge as equal for the same url, headers, encodable and encoder") { let date = Date() endpoint = endpoint.replacing(task: .requestCustomJSONEncodable(Issue(title: "T", createdAt: date, rating: 0), encoder: JSONEncoder())) let endpointToCompare = endpoint.replacing(task: .requestCustomJSONEncodable(Issue(title: "T", createdAt: date, rating: 0), encoder: JSONEncoder())) expect(endpoint) == endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers, encoder and different encodable") { let date = Date() endpoint = endpoint.replacing(task: .requestCustomJSONEncodable(Issue(title: "T", createdAt: date, rating: 0), encoder: JSONEncoder())) let endpointToCompare = endpoint.replacing(task: .requestCustomJSONEncodable(Issue(title: "Ta", createdAt: date, rating: 0), encoder: JSONEncoder())) expect(endpoint) != endpointToCompare } it("should correctly acknowledge as not equal for the same url, headers, encodable and different encoder") { let date = Date() endpoint = endpoint.replacing(task: .requestCustomJSONEncodable(Issue(title: "T", createdAt: date, rating: 0), encoder: JSONEncoder())) let snakeEncoder = JSONEncoder() snakeEncoder.keyEncodingStrategy = .convertToSnakeCase let endpointToCompare = endpoint.replacing(task: .requestCustomJSONEncodable(Issue(title: "T", createdAt: date, rating: 0), encoder: snakeEncoder)) expect(endpoint) != endpointToCompare } } } } } enum Empty { } extension Empty: TargetType { // None of these matter since the Empty has no cases and can't be instantiated. var baseURL: URL { URL(string: "http://example.com")! } var path: String { "" } var method: Moya.Method { .get } var parameters: [String: Any]? { nil } var parameterEncoding: ParameterEncoding { URLEncoding.default } var task: Task { .requestPlain } var sampleData: Data { Data() } var headers: [String: String]? { nil } }
mit