repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
weirenxin/QRcode
QRcode/QRcode/Classes/DetectorQRCode/ViewController/DetectorQRCodeVC.swift
1
2811
// // DetectorQRCodeVC.swift // QRcode // // Created by weirenxin on 2016/11/3. // Copyright © 2016年 广西家饰宝科技有限公司. All rights reserved. // import UIKit import CoreImage class DetectorQRCodeVC: UIViewController { @IBOutlet weak var sourceImageView: UIImageView! @IBAction func detectorQRCodeAction(_ sender: UIButton) { //distinguishQRCode() setupQRCodeFrame() } // 0. erweima.png private func distinguishQRCode() { let image = sourceImageView.image let imageCI = CIImage(image: image!) // 1.创建一个二维码探测器 // CIDetectorTypeQRCode : 识别类型 // CIDetectorAccuracy : 识别率 let dector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]) // 2.直接探测二维码特征 let features = dector?.features(in: imageCI!) for feature in features! { let qrFeature = feature as! CIQRCodeFeature print(qrFeature.messageString ?? "NO") print(qrFeature.bounds) } } } // MARK: - 二维码边框 extension DetectorQRCodeVC { fileprivate func setupQRCodeFrame() { let image = sourceImageView.image let imageCI = CIImage(image: image!) let dector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]) let features = dector?.features(in: imageCI!) var resultImage = image var result = [String]() for feature in features! { let qrFeature = feature as! CIQRCodeFeature result.append(qrFeature.messageString!) resultImage = drawFrame(resultImage!, qrFeature) sourceImageView.image = resultImage } } private func drawFrame(_ image: UIImage, _ feature: CIQRCodeFeature) -> UIImage { let size = image.size print(size) UIGraphicsBeginImageContext(size) //绘制大图 image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) // 转换坐标系 上下颠倒 let context = UIGraphicsGetCurrentContext() context?.scaleBy(x: 1, y: -1) context?.translateBy(x: 0, y: -size.height) // 绘制路径 let bounds = feature.bounds let path = UIBezierPath(rect: bounds) UIColor.red.setStroke() path.lineWidth = 6 path.stroke() let resultImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resultImage! } }
apache-2.0
77fda6bfb0197f2734b134fa1a3f447e
26.731959
130
0.592193
4.744268
false
false
false
false
magicien/MMDSceneKit
Source/Common/MMDVACReader.swift
1
2602
// // MMDVACReader.swift // MMDSceneKit // // Created by magicien on 11/25/16. // Copyright © 2016 DarkHorse. All rights reserved. // import SceneKit class MMDVACReader: MMDReader { static func getNode(_ data: Data, directoryPath: String! = "") -> MMDNode? { let reader = MMDVACReader(data: data, directoryPath: directoryPath) let node = reader.loadVACFile() return node } // MARK: - Loading VMD File /** */ private func loadVACFile() -> MMDNode? { let data = String(data: self.binaryData, encoding: .shiftJIS) if let lines = data?.components(separatedBy: "\r\n") { if lines.count < 6 { return nil } let name = lines[0] let fileName = lines[1] let scaleStr = lines[2] let positions = lines[3].components(separatedBy: ",") let rotations = lines[4].components(separatedBy: ",") let boneName = lines[5] let xFilePath = (self.directoryPath as NSString).appendingPathComponent(fileName) var model: MMDNode? = nil if let scene = MMDSceneSource(path: xFilePath) { model = scene.getModel() } else { print("can't read file: \(xFilePath)") } if let mmdModel = model { mmdModel.name = name if let scale = Float(scaleStr) { let s = OSFloat(scale * 10.0) mmdModel.scale = SCNVector3Make(s, s, s) } else { mmdModel.scale = SCNVector3Make(10.0, 10.0, 10.0) } if positions.count >= 3 { let posX = Float(positions[0]) let posY = Float(positions[1]) let posZ = Float(positions[2]) if let x = posX, let y = posY, let z = posZ { mmdModel.position = SCNVector3Make(OSFloat(x), OSFloat(y), OSFloat(z)) } } if rotations.count >= 3 { let rotX = Float(rotations[0]) let rotY = Float(rotations[1]) let rotZ = Float(rotations[2]) if let x = rotX, let y = rotY, let z = rotZ { // TODO: implement } } return mmdModel } } return nil } }
mit
00f9dd5dc523ac14ba970891687dbb55
31.924051
94
0.45867
4.571178
false
false
false
false
KyoheiG3/SimpleAlert
SimpleAlert/Extension/UIStackViewExtension.swift
1
1276
// // UIStackViewExtension.swift // SimpleAlert // // Created by Kyohei Ito on 2019/06/15. // Copyright © 2019 kyohei_ito. All rights reserved. // import UIKit extension UIStackView { func makeBorderView() -> UIView { let borderView = UIView() borderView.translatesAutoresizingMaskIntoConstraints = false borderView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.4) switch axis { case .horizontal: borderView.widthAnchor.constraint(equalToConstant: CGFloat.thinWidth).isActive = true case .vertical: borderView.heightAnchor.constraint(equalToConstant: CGFloat.thinWidth).isActive = true @unknown default: borderView.heightAnchor.constraint(equalToConstant: CGFloat.thinWidth).isActive = true } return borderView } func addAction(_ action: AlertAction) { addArrangedSubview(makeBorderView()) action.button.heightAnchor.constraint(equalToConstant: action.button.bounds.height).isActive = true addArrangedSubview(action.button) } func removeAllArrangedSubviews() { arrangedSubviews.forEach { view in removeArrangedSubview(view) view.removeFromSuperview() } } }
mit
c9e7356983a1c4ec750382fb4ea98c2f
29.357143
107
0.68
5.246914
false
false
false
false
m-alani/contests
leetcode/fizzBuzz.swift
1
675
// // fizzBuzz.swift // // Practice solution - Marwan Alani - 2017 // // Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/fizz-buzz/ // Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code // class Solution { func fizzBuzz(_ n: Int) -> [String] { var output = [String]() guard n > 0 else { return output } for i in 1...n { var current = String() if i % 3 == 0 { current.append("Fizz") } if i % 5 == 0 { current.append("Buzz") } if current.count == 0 { current.append(String(i)) } output.append(current) } return output } }
mit
f7a4118612dca6dc3ca07b3adc407f8d
28.347826
117
0.608889
3.443878
false
false
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Frontend/Browser/Dashboard/Offrz/OffrzOnboardingView.swift
2
2965
// // OffrzOnboardingView.swift // Client // // Created by Sahakyan on 12/27/17. // Copyright © 2017 Mozilla. All rights reserved. // import Foundation enum OffrzOnboardingActions { case hide case learnMore } typealias OffrzOnboardingActionHandler = () -> Void class OffrzOnboardingView: UIView { private let hideButton = UIButton(type: .custom) private let descriptionLabel = UILabel() private let moreButton = UIButton(type: .custom) private let offrzPresentImageView = UIImageView(image: UIImage(named: "offrz_present")) private var actionHandlers = [OffrzOnboardingActions: OffrzOnboardingActionHandler]() override init(frame: CGRect) { super.init(frame: frame) self.setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } init() { super.init(frame: CGRect.zero) self.setup() } override func updateConstraints() { super.updateConstraints() self.layoutComponents() } func addActionHandler(_ action: OffrzOnboardingActions, handler: @escaping OffrzOnboardingActionHandler) { self.actionHandlers[action] = handler } private func setup() { self.setupComponents() self.setStyles() self.layoutComponents() } private func setupComponents() { self.addSubview(offrzPresentImageView) hideButton.setImage(UIImage(named: "closeTab"), for: .normal) hideButton.addTarget(self, action: #selector(hideOnboardingView) , for: .touchUpInside) self.addSubview(hideButton) descriptionLabel.text = NSLocalizedString("MyOffrz Onboarding", tableName: "Cliqz", comment: "[MyOffrz] MyOffrz description") self.addSubview(descriptionLabel) moreButton.setTitle(NSLocalizedString("LEARN MORE", tableName: "Cliqz", comment: "[MyOffrz] Learn more button title"), for: .normal) moreButton.addTarget(self, action: #selector(openLearnMore), for: .touchUpInside) self.addSubview(moreButton) } private func setStyles() { self.backgroundColor = UIColor(colorString: "ABD8EA") descriptionLabel.textColor = UIColor.gray descriptionLabel.textAlignment = .center descriptionLabel.numberOfLines = 2 moreButton.setTitleColor(UIConstants.CliqzThemeColor, for: .normal) } private func layoutComponents() { hideButton.snp.remakeConstraints { (make) in make.top.right.equalTo(self).inset(10) make.height.width.equalTo(25) } offrzPresentImageView.snp.remakeConstraints { (make) in make.centerX.equalTo(self) make.top.equalTo(self).inset(10) } descriptionLabel.snp.remakeConstraints { (make) in make.right.left.equalTo(self).inset(25) make.top.equalTo(offrzPresentImageView.snp.bottom).offset(10) } moreButton.snp.remakeConstraints { (make) in make.centerX.equalTo(self) make.bottom.equalTo(self) } } @objc private func openLearnMore() { if let action = self.actionHandlers[.learnMore] { action() } } @objc private func hideOnboardingView() { if let action = self.actionHandlers[.hide] { action() } } }
mpl-2.0
23b8a4e9886491ceb0e34639f6932d69
25.230088
134
0.741228
3.592727
false
false
false
false
kjifw/Senses
senses-client/Senses/Senses/Models/UserDetailsModel.swift
1
1253
// // UserDetailsModel.swift // Senses // // Created by Jeff on 4/1/17. // Copyright © 2017 Telerik Academy. All rights reserved. // import Foundation class UserDetailsModel { var username: String? var email: String? var city: String? var picture: String? var age: String? var gender: String? var about: String? var kudos: String? var genderPrefs: [Any]? var invitationsList: [Any]? var partyHistory: [Any]? init(withUsername username: String, withEmail email: String, withCity city: String, withPicture picture: String, withAge age: String, withGender gender: String, withInformation about: String, withKudos kudos: String, withGenderPrefs prefs: [Any], withInvitationsList invitationsList: [Any], withPartyHistory partyHistory: [Any]) { self.username = username self.email = email self.city = city self.picture = picture self.age = age self.gender = gender self.about = about self.kudos = kudos self.genderPrefs = prefs self.invitationsList = invitationsList self.partyHistory = partyHistory } }
mit
d86b4c6df2846468e89ad94f5763f725
21.763636
58
0.611022
4.145695
false
false
false
false
polymr/polymyr-api
Sources/App/Utility/Request+Convenience.swift
1
852
// // Request+Convenience.swift // subber-api // // Created by Hakon Hanesand on 1/22/17. // // import HTTP import Vapor extension Request { func customerInjectable(key: String = "customer_id") throws -> Node { let customer = try self.customer() guard let id = customer.id?.int else { throw Abort.custom(status: .internalServerError, message: "Logged in user does not have id.") } return .object([key : .number(.int(id))]) } func makerInjectable(key: String = "maker_id") throws -> Node { let maker = try self.maker() guard let id = maker.id?.int else { throw Abort.custom(status: .internalServerError, message: "Logged in maker does not have id.") } return .object([key : .number(.int(id))]) } }
mit
a597326b6b5444b2a3889a148c95da2b
24.818182
106
0.575117
4.076555
false
false
false
false
firebase/firebase-ios-sdk
ReleaseTooling/Sources/ZipBuilder/ResourcesManager.swift
2
14388
/* * Copyright 2019 Google * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import Utils /// Functions related to managing resources. Intentionally empty, this enum is used as a namespace. enum ResourcesManager {} extension ResourcesManager { /// Recursively searches a directory for any sign of resources: `.bundle` folders, or a non-empty /// directory called "Resources". /// /// - Parameter dir: The directory to search for any sign of resources. /// - Returns: True if any resources could be found, otherwise false. /// - Throws: A FileManager API that was thrown while searching. static func directoryContainsResources(_ dir: URL) throws -> Bool { // First search for any .bundle files. let fileManager = FileManager.default let bundles = try fileManager.recursivelySearch(for: .bundles, in: dir) // Stop searching if there were any bundles found. if !bundles.isEmpty { return true } // Next, search for any non-empty Resources directories. let existingResources = try fileManager.recursivelySearch(for: .directories(name: "Resources"), in: dir) for resource in existingResources { let fileList = try fileManager.contentsOfDirectory(atPath: resource.path) if !fileList.isEmpty { return true } } // At this point: no bundles were found, and either there were no Resources directories or they // were all empty. Safe to say this directory doesn't contain any resources. return false } /// Packages all resources in a directory (recursively) - compiles them, puts them in a /// bundle, embeds them in the adjacent .framework file, and cleans up any empty Resources /// directories. /// /// - Parameters: /// - fromDir: The directory to search for resources. /// - toDir: The Resources directory to dump all resource bundles in. /// - bundlesToRemove: Any bundles to remove (name of the bundle, not a full path). /// - Returns: True if any resources were moved and packaged, otherwise false. /// - Throws: Any file system errors that occur. @discardableResult static func packageAllResources(containedIn dir: URL, bundlesToIgnore: [String] = []) throws -> Bool { let resourcesFound = try directoryContainsResources(dir) // Quit early if there are no resources to deal with. if !resourcesFound { return false } let fileManager = FileManager.default // There are three possibilities for resources at this point: // 1. A `.bundle` could be packaged in a `Resources` directory inside of a framework. // - We want to keep these where they are. // 2. A `.bundle` could be packaged in a `Resources` directory outside of a framework. // - We want to move these into the framework adjacent to the `Resources` dir. // 3. A `Resources` directory that still needs to be compiled, outside of a framework. // - These need to be compiled into `.bundles` and moved into the relevant framework // directory. let allResourceDirs = try fileManager.recursivelySearch(for: .directories(name: "Resources"), in: dir) for resourceDir in allResourceDirs { // Situation 1: Ignore any Resources directories that are already in the .framework. let parentDir = resourceDir.deletingLastPathComponent() guard parentDir.pathExtension != "framework" else { print("Found a Resources directory inside \(parentDir), no action necessary.") continue } // Store the paths to bundles that are found or newly assembled. var bundles: [URL] = [] // Situation 2: Find any bundles that already exist but aren't included in the framework. bundles += try fileManager.recursivelySearch(for: .bundles, in: resourceDir) // Situation 3: Create any leftover bundles in this directory. bundles += try createBundles(fromDir: resourceDir) // Filter out any explicitly ignored bundles. bundles.removeAll(where: { bundlesToIgnore.contains($0.lastPathComponent) }) // Find the right framework for these bundles to be embedded in - the folder structure is // likely: // - ProductFoo // - Frameworks // - ProductFoo.framework // - Resources // - BundleFoo.bundle // - BundleBar.bundle // - etc. // If there are more than one frameworks in the "Frameworks" directory, we can try to match // the name of the bundle and the framework but if it doesn't match, fail because we don't // know what bundle the resources belong to. This isn't the case now for any Firebase products // but it's a good flag to raise in case that happens in the future. let frameworksDir = parentDir.appendingPathComponent("Frameworks") guard fileManager.directoryExists(at: frameworksDir) else { fatalError("Could not package resources in \(resourceDir): Frameworks directory doesn't " + "exist: \(frameworksDir)") } let contents = try fileManager.contentsOfDirectory(atPath: frameworksDir.path) switch contents.count { case 0: // No Frameworks exist. fatalError("Could not find framework file to package Resources in \(resourceDir). " + "\(frameworksDir) is empty.") case 1: // Force unwrap is fine here since we know the first one exists. let frameworkName = contents.first! let frameworkResources = frameworksDir.appendingPathComponents([frameworkName, "Resources"]) // Move all the bundles into the Resources directory for that framework. This will create // the directory if it doesn't exist. try moveAllFiles(bundles, toDir: frameworkResources) default: // More than one framework is found. Try a last ditch effort of lining up the name, and if // that doesn't work fail out. for bundle in bundles { // Get the name of the bundle without any suffix. let name = bundle.lastPathComponent.replacingOccurrences(of: ".bundle", with: "") guard contents.contains(name) else { fatalError("Attempting to embed \(name).bundle into a framework but there are too " + "many frameworks to choose from in \(frameworksDir).") } // We somehow have a match, embed that bundle in the framework and try the next one! let frameworkResources = frameworksDir.appendingPathComponents([name, "Resources"]) try moveAllFiles([bundle], toDir: frameworkResources) } } } // Let the caller know we've modified resources. return true } /// Recursively searches for bundles in `dir` and moves them to the Resources directory /// `resourceDir`. /// /// - Parameters: /// - dir: The directory to search for Resource bundles. /// - resourceDir: The destination Resources directory. This function will create the Resources /// directory if it doesn't exist. /// - keepOriginal: Do a copy instead of a move. /// - Returns: An array of URLs pointing to the newly located bundles. /// - Throws: Any file system errors that occur. @discardableResult static func moveAllBundles(inDirectory dir: URL, to resourceDir: URL, keepOriginal: Bool = false) throws -> [URL] { let fileManager = FileManager.default let allBundles = try fileManager.recursivelySearch(for: .bundles, in: dir) // If no bundles are found, return an empty array since nothing was done (but there wasn't an // error). guard !allBundles.isEmpty else { return [] } // Move the found bundles into the Resources directory. let bundlesMoved = try moveAllFiles(allBundles, toDir: resourceDir, keepOriginal: keepOriginal) // Remove any empty Resources directories left over as part of the move. removeEmptyResourcesDirectories(in: dir) return bundlesMoved } /// Searches for and attempts to remove all empty "Resources" directories in a given directory. /// This is a recrusive search. /// /// - Parameter dir: The directory to recursively search for Resources directories in. static func removeEmptyResourcesDirectories(in dir: URL) { // Find all the Resources directories to begin with. let fileManager = FileManager.default guard let resourceDirs = try? fileManager .recursivelySearch(for: .directories(name: "Resources"), in: dir) else { print("Attempted to remove empty resource directories, but it failed. This shouldn't be " + "classified as an error, but something to look out for.") return } // Get the contents of each directory and if it's empty, remove it. for resourceDir in resourceDirs { guard let contents = try? fileManager.contentsOfDirectory(atPath: resourceDir.path) else { print("WARNING: Failed to get contents of apparent Resources directory at \(resourceDir)") continue } // Remove the directory if it's empty. Only warn if it's not successful, since it's not a // requirement but a nice to have. if contents.isEmpty { do { try fileManager.removeItem(at: resourceDir) } catch { print("WARNING: Failed to remove empty Resources directory while cleaning up folder " + "heirarchy: \(error)") } } } } // MARK: Private Helpers /// Creates bundles for all folders in the directory passed in, and will compile /// /// - Parameter dir: A directory containing folders to make into bundles. /// - Returns: An array of filepaths to bundles that were packaged. /// - Throws: Any file manager errors thrown. private static func createBundles(fromDir dir: URL) throws -> [URL] { // Get all the folders in the "Resources" directory and loop through them. let fileManager = FileManager.default var bundles: [URL] = [] let contents = try fileManager.contentsOfDirectory(atPath: dir.path) for fileOrFolder in contents { let fullPath = dir.appendingPathComponent(fileOrFolder) // The dir itself may contain resource files at its root. If so, we may need to package these // in the future but print a warning for now. guard fileManager.isDirectory(at: fullPath) else { print("WARNING: Found a file in the Resources directory, this may need to be packaged: " + "\(fullPath)") continue } if fullPath.lastPathComponent.hasSuffix("bundle") { // It's already a bundle, so no need to create one. continue } // It's a folder. Generate the name and location based on the folder name. let name = fullPath.lastPathComponent + ".bundle" let location = dir.appendingPathComponent(name) // Copy the existing Resources folder to the new bundle location. try fileManager.copyItem(at: fullPath, to: location) // Compile any storyboards that exist in the new bundle. compileStoryboards(inDir: location) bundles.append(location) } return bundles } /// Finds and compiles all `.storyboard` files in a directory, removing the original file. private static func compileStoryboards(inDir dir: URL) { let fileManager = FileManager.default let storyboards: [URL] do { storyboards = try fileManager.recursivelySearch(for: .storyboards, in: dir) } catch { fatalError("Failed to search for storyboards in directory: \(error)") } // Compile each storyboard, then remove it. for storyboard in storyboards { // Compiled storyboards have the extension `storyboardc`. let compiledPath = storyboard.deletingPathExtension().appendingPathExtension("storyboardc") // Run the command and throw an error if it fails. let command = "ibtool --compile \(compiledPath.path) \(storyboard.path)" let result = Shell.executeCommandFromScript(command) switch result { case .success: // Remove the original storyboard file and continue. do { try fileManager.removeItem(at: storyboard) } catch { fatalError("Could not remove storyboard file \(storyboard) from bundle after " + "compilation: \(error)") } case let .error(code, output): fatalError("Failed to compile storyboard \(storyboard): error \(code) \(output)") } } } /// Moves all files passed in to the destination dir, keeping the same filename. /// /// - Parameters: /// - files: URLs to files to move. /// - destinationDir: Destination directory to move all the files. Creates the directory if it /// doesn't exist. /// - keepOriginal: Do a copy instead of a move. /// - Throws: Any file system errors that occur. @discardableResult private static func moveAllFiles(_ files: [URL], toDir destinationDir: URL, keepOriginal: Bool = false) throws -> [URL] { let fileManager = FileManager.default if !fileManager.directoryExists(at: destinationDir) { try fileManager.createDirectory(at: destinationDir, withIntermediateDirectories: true) } var filesMoved: [URL] = [] for file in files { // Create the destination URL by using the filename of the file but prefix of the // destinationDir. let destination = destinationDir.appendingPathComponent(file.lastPathComponent) if keepOriginal { try fileManager.copyItem(at: file, to: destination) } else { try fileManager.moveItem(at: file, to: destination) } filesMoved.append(destination) } return filesMoved } }
apache-2.0
188facecb32a5a17f2227da2f6d71c89
42.732523
100
0.668265
4.762661
false
false
false
false
AlexLombry/SwiftMastery-iOS10
PlayGround/Generics.playground/Contents.swift
1
2140
//: Playground - noun: a place where people can play import UIKit func swap<T>(value1: inout T, value2: inout T) { let temp = value1 value1 = value2 value2 = temp } var int1 = 50 var int2 = 100 swap(value1: &int1, value2: &int2) print(int1) print(int2) var someStringValue = "UPPERCASE VALUE" var anotherStringValue = "lowercase value" swap(&someStringValue, &anotherStringValue) print(someStringValue) print(anotherStringValue) var arrayFirstNames = ["bill", "bob", "mike"] var arrayLastNames = ["smith", "jackson", "harris"] swap(&arrayFirstNames, &arrayLastNames) print(arrayFirstNames) print(arrayLastNames) // * Custom generic types (class struct enum) // generic stack /* struct StackOfStrings { var objects = [String]() // mutating because they need to modify the struct array given mutating func push(object: String) { objects.append(object) } mutating func pop() -> String { return objects.removeLast() } } */ // Generic struct struct StackOfObjects <Element>{ var objects = [Element]() // mutating because they need to modify the struct array given mutating func push(object: Element) { objects.append(object) } mutating func pop() -> Element { return objects.removeLast() } } // instance of the struct var stringStack = StackOfObjects<String>() stringStack.push(object: "France") stringStack.push(object: "Allemagne") stringStack.push(object: "Belgique") print(stringStack) let fromtheTop = stringStack.pop() print(stringStack) var intStack = StackOfObjects<Int>() intStack.push(object: 2) intStack.push(object: 4) intStack.push(object: 6) intStack.push(object: 8) print(intStack) intStack.pop() print(intStack) var textField = StackOfObjects<UITextField>() var sliderStack = StackOfObjects<UISlider>() // * Extending a Generic extension StackOfObjects { var top: Element? { return objects.isEmpty ? nil : objects[objects.count - 1] } } print(intStack.top as Any) if let topObject = intStack.top { print("The top object on the stack is \(topObject).") }
apache-2.0
33e16216b48cbbfedd6995a52eb76d3c
15.984127
66
0.689252
3.651877
false
false
false
false
RTWeiss/pretto
Pretto/Invitation.swift
1
7695
// // Invitation.swift // Pretto // // Created by Josiah Gaskin on 6/14/15. // Copyright (c) 2015 Pretto. All rights reserved. // import Foundation import Photos private let kClassName = "Invitation" class Invitation : PFObject, PFSubclassing { var isUpdating : Bool = false override class func initialize() { struct Static { static var onceToken : dispatch_once_t = 0; } dispatch_once(&Static.onceToken) { self.registerSubclass() } } static func parseClassName() -> String { return kClassName } @NSManaged var event : Event @NSManaged var from : PFUser @NSManaged var to : PFUser var paused: Bool { get { return self["paused"] as! Bool } set { self["paused"] = newValue } } var accepted: Bool { get { return self["accepted"] as! Bool } set { self["accepted"] = newValue } } @NSManaged var lastUpdated : NSDate? var shouldUploadPhotos : Bool { return accepted && !paused } // Get all photos from the camera roll past self.lastUpdated and add them to the event func updateFromCameraRoll() { if self.isUpdating { return } self.isUpdating = true let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let startDate = self.lastUpdated ?? event.startDate lastUpdated = NSDate() fetchOptions.predicate = NSPredicate(format: "creationDate > %@ AND creationDate < %@", startDate, event.endDate) PHPhotoLibrary.requestAuthorization(nil) let allResult = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions) let requestOptions = PHImageRequestOptions() requestOptions.deliveryMode = PHImageRequestOptionsDeliveryMode.FastFormat requestOptions.version = PHImageRequestOptionsVersion.Current let requestManager = PHImageManager.defaultManager() println("Adding \(allResult.count) photos to \(event.title)") let targetRect = CGRectMake(0, 0, 140, 140) for var i = 0; i < allResult.count; i++ { requestManager.requestImageForAsset(allResult[i] as! PHAsset, targetSize: targetRect.size, contentMode: PHImageContentMode.AspectFit, options: requestOptions, resultHandler: { (image, info) -> Void in UIGraphicsBeginImageContext(image.size) image.drawInRect(targetRect) let finalImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let data = UIImageJPEGRepresentation(finalImage, 1.0) if data == nil { return } let thumbFile = PFFile(data: data) thumbFile.saveInBackground() let image = Photo() image.thumbnailFile = thumbFile image.owner = PFUser.currentUser()! image.saveInBackgroundWithBlock({ (success, err) -> Void in NSNotificationCenter.defaultCenter().postNotificationName("PrettoNewPhotoForEvent", object: self.event) }) self.event.addImageToEvent(image) }) } saveInBackground() self.isUpdating = false } // Query for all live events in the background and call the given block with the result class func getAllLiveEvents(block: ([Invitation] -> Void) ) { let query = PFQuery(className: "Invitation", predicate: nil) query.includeKey("event") let innerQuery = PFQuery(className: "Event", predicate: nil) innerQuery.whereKey(kEventStartDateKey, lessThanOrEqualTo: NSDate()) innerQuery.whereKey(kEventEndDateKey, greaterThan: NSDate()) query.whereKey("event", matchesQuery: innerQuery) query.whereKey("to", equalTo: PFUser.currentUser()!) query.includeKey("event") query.orderByDescending("createdAt") query.findObjectsInBackgroundWithBlock { (items, error) -> Void in if error == nil { var invites : [Invitation] = [] for obj in items ?? [] { if let invitation = obj as? Invitation { invites.append(invitation) } } block(invites) } } } // Query for all past events in the background and call the given block with the result class func getAllPastEvents(block: ([Invitation] -> Void) ) { let query = PFQuery(className: "Invitation", predicate: nil) query.includeKey("event") let innerQuery = PFQuery(className: "Event", predicate: nil) innerQuery.whereKey(kEventEndDateKey, lessThan: NSDate()) query.whereKey("event", matchesQuery: innerQuery) query.whereKey("to", equalTo: PFUser.currentUser()!) query.includeKey("event") query.orderByDescending("createdAt") query.findObjectsInBackgroundWithBlock { (items, error) -> Void in if error == nil { var invites : [Invitation] = [] for obj in items ?? [] { if let invitation = obj as? Invitation { invites.append(invitation) } } block(invites) } } } // Query for all future events in the background and call the given block with the result class func getAllFutureEvents(block: ([Invitation] -> Void) ) { let query = PFQuery(className: "Invitation", predicate: nil) query.includeKey("event") let innerQuery = PFQuery(className: "Event", predicate: nil) innerQuery.whereKey(kEventStartDateKey, greaterThanOrEqualTo: NSDate()) query.whereKey("event", matchesQuery: innerQuery) query.whereKey("to", equalTo: PFUser.currentUser()!) query.includeKey("event") query.orderByDescending("createdAt") query.findObjectsInBackgroundWithBlock { (items, error) -> Void in if error == nil { var invites : [Invitation] = [] for obj in items ?? [] { if let invitation = obj as? Invitation { invites.append(invitation) } } block(invites) } } } // Query for all future events in the background and call the given block with the result class func getAllLiveAndFutureNonAcceptedEvents(block: ([Invitation] -> Void) ) { let query = PFQuery(className: "Invitation", predicate: nil) query.includeKey("event") let innerQuery = PFQuery(className: "Event", predicate: nil) innerQuery.whereKey(kEventEndDateKey, greaterThanOrEqualTo: NSDate()) query.whereKey("event", matchesQuery: innerQuery) query.whereKey("to", equalTo: PFUser.currentUser()!) query.whereKey("accepted", equalTo: false) query.includeKey("event") query.orderByDescending("createdAt") query.findObjectsInBackgroundWithBlock { (items, error) -> Void in if error == nil { var invites : [Invitation] = [] for obj in items ?? [] { if let invitation = obj as? Invitation { invites.append(invitation) } } block(invites) } } } }
mit
fe36e2c88fa262d6a45cf88ccddb8d61
38.265306
212
0.584925
5.303239
false
false
false
false
jdspoone/Recipinator
RecipeBook/IngredientAmountToIngredientAmountPolicy.swift
1
1869
/* Written by Jeff Spooner Custom migration policy for IngredientAmount instances */ import CoreData class IngredientAmountToIngredientAmountPolicy: NSEntityMigrationPolicy { override func createRelationships(forDestination destinationInstance: NSManagedObject, in mapping: NSEntityMapping, manager: NSMigrationManager) throws { // Get the user info dictionary let userInfo = mapping.userInfo! // Get the source version let sourceVersion = userInfo["sourceVersion"] as? String // If a source version was specified if let sourceVersion = sourceVersion { // Get the source note let sourceIngredientAmount = manager.sourceInstances(forEntityMappingName: mapping.name, destinationInstances: [destinationInstance]).first! // Get the source note's relationship keys and values let sourceRelationshipKeys = Array(sourceIngredientAmount.entity.relationshipsByName.keys) let sourceRelationshipValues = sourceIngredientAmount.dictionaryWithValues(forKeys: sourceRelationshipKeys) // Switch on the source version switch sourceVersion { // Migrating from v1.2 to v1.3 case "v1.2": // Get the source instance's incorrectly named recipesUsedIn relationship let sourceRecipe = sourceRelationshipValues["recipesUsedIn"] as! NSManagedObject // Get the corresponding destination recipe let destinationRecipe = manager.destinationInstances(forEntityMappingName: "RecipeToRecipe", sourceInstances: [sourceRecipe]).first! // Set the destination instance's recipeUsedIn relationship destinationInstance.setValue(destinationRecipe, forKey: "recipeUsedIn") default: break } } } }
mit
45330a9b49619b9465cdd93c0270330e
32.981818
155
0.691279
5.612613
false
false
false
false
KevinMorais/iOS-Mapbox
Test-Mapbox/Controllers/SearchTableViewController.swift
1
4731
// // SearchTableViewController.swift // Test-Mapbox // // Created by Kevin Morais on 15/01/2017. // Copyright © 2017 Kevin Morais. All rights reserved. // import UIKit import CoreLocation protocol SearchTableViewControllerDelegate: class { func userDidSelectPlacemark(placemark: TMapPlacemark) } class SearchTableViewController: UITableViewController { weak var delegate: SearchTableViewControllerDelegate? fileprivate var placemarks: [TMapPlacemark] = [TMapPlacemark]() fileprivate var findHistory: [TMapPlacemark] = [TMapPlacemark]() fileprivate var historyPlacemarks: [TMapPlacemark] = [TMapPlacemark]() override func viewDidLoad() { super.viewDidLoad() self.tableView.tableFooterView = UIView(frame: .zero) } override func viewWillAppear(_ animated: Bool) { self.loadHistoryCoordinates() } private func loadHistoryCoordinates() { // Load history guard let history = CLLocationCoordinate2D.loadCoordinates() else { return } self.historyPlacemarks.removeAll() for (idx, item) in history.enumerated() { let _ = TMapGeocoder.sharedInstance.geocode(coord: item, completionHandler: { (placemarks, error) in if error != nil { print(error!.localizedDescription) return } if placemarks != nil { self.historyPlacemarks.append(placemarks![0]) } if history.endIndex == idx { self.tableView.beginUpdates() self.tableView.reloadSections([0], with: .automatic) self.tableView.endUpdates() } }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 15.0 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "Places History" } else if section == 1 { return "Results" } return "" } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return self.findHistory.count } if section == 1 { return self.placemarks.count } return 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) let placemark: TMapPlacemark if indexPath.section == 0 { placemark = self.findHistory[indexPath.row] } else { placemark = self.placemarks[indexPath.row] } cell.textLabel?.text = placemark.qualifiedName cell.backgroundColor = .white return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.delegate?.userDidSelectPlacemark(placemark: self.placemarks[indexPath.row]) self.dismiss(animated: true, completion: nil) } } extension SearchTableViewController: UISearchResultsUpdating { internal func updateSearchResults(for searchController: UISearchController) { guard let searchBarText = searchController.searchBar.text else { return } // Search in using geocoder let _ = TMapGeocoder.sharedInstance.geocode(query: searchBarText) { (placemarks, error) in if error != nil { print(error!.localizedDescription) return } if placemarks != nil { self.placemarks = placemarks! } self.tableView.reloadData() } //Search in the history self.findHistory = self.historyPlacemarks.filter({ (placemark) -> Bool in return placemark.name.uppercased().contains(searchBarText.uppercased()) || placemark.qualifiedName.uppercased().contains(searchBarText.uppercased()) }) self.tableView.reloadSections([0], with: .none) } }
apache-2.0
b50fbe67db78fada9d12a9c902261183
30.118421
160
0.594292
5.57126
false
false
false
false
GnuRant/B3LabSideBar
SideBarController/AppDelegate.swift
1
2825
// // AppDelegate.swift // SideBarController // // Created by Luca D'incà on 04/11/14. // Copyright (c) 2014 B3LAB. 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. let windows: UIWindow = UIWindow(frame: UIScreen.mainScreen().bounds) //DEBUG var controller1: UIViewController = UIViewController() controller1.view.backgroundColor = UIColor.orangeColor() var controller2: UIViewController = UIViewController() controller1.view.backgroundColor = UIColor.blueColor() var rootViewController = B3LabSideBarViewController() rootViewController.controllers = [controller1, controller1] rootViewController.titles = ["Controller 1", "Controller 2"] window?.rootViewController = rootViewController window?.makeKeyAndVisible() 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
eeb0300703b4ff2d7d5920671f1c2bea
44.548387
285
0.734419
5.636727
false
false
false
false
oneWarcraft/PictureBrowser-Swift
PictureBrowser/PictureBrowser/Classes/Home/HomeCollectionViewFlowLayout.swift
1
736
// // HomeCollectionViewFlowLayout.swift // PictureBrowser // // Created by 王继伟 on 16/7/14. // Copyright © 2016年 WangJiwei. All rights reserved. // import UIKit class HomeCollectionViewFlowLayout: UICollectionViewFlowLayout { override func prepareLayout() { super.prepareLayout() let margin : CGFloat = 10 let itemWH = (UIScreen.mainScreen().bounds.width - 4 * margin - 1) / 3 itemSize = CGSize(width: itemWH, height: itemWH) minimumLineSpacing = margin minimumInteritemSpacing = margin collectionView?.contentInset = UIEdgeInsets(top: margin + 64, left: margin, bottom: margin, right: margin) } }
apache-2.0
a225bc1ef13cc4c4dd7f6d50814d48df
24.964286
114
0.627235
4.782895
false
false
false
false
ichu501/FBSimulatorControl
fbsimctl/FBSimulatorControlKit/Sources/Relay.swift
1
2221
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Foundation /** A Protocol for defining */ protocol Relay { func start() throws func stop() throws } /** A Relay that does nothing */ class EmptyRelay : Relay { func start() { } func stop() { } } /** Wraps an existing Relay, spinning the run loop after the underlying relay has started. */ class SynchronousRelay : Relay { let relay: Relay let reporter: EventReporter let started: (Void) -> Void init(relay: Relay, reporter: EventReporter, started: @escaping (Void) -> Void) { self.relay = relay self.reporter = reporter self.started = started } func start() throws { // Setup the Signal Handling first, so sending a Signal cannot race with starting the relay. var signalled = false let handler = SignalHandler { info in self.reporter.reportSimple(EventName.Signalled, EventType.Discrete, info) signalled = true } handler.register() // Start the Relay and notify consumers. try self.relay.start() self.started() // Start the event loop. RunLoop.current.spinRunLoop(withTimeout: DBL_MAX) { signalled } handler.unregister() } func stop() throws { try self.relay.stop() } } /** A Relay that accepts input from stdin, writing it to the Line Buffer. */ class FileHandleRelay : Relay { let commandBuffer: CommandBuffer let input: FileHandle init(commandBuffer: CommandBuffer, input: FileHandle) { self.commandBuffer = commandBuffer self.input = input } convenience init(commandBuffer: CommandBuffer) { self.init( commandBuffer: commandBuffer, input: FileHandle.standardInput ) } func start() throws { let commandBuffer = self.commandBuffer self.input.readabilityHandler = { handle in let data = handle.availableData let _ = commandBuffer.append(data) } } func stop() { self.input.readabilityHandler = nil } }
bsd-3-clause
6fda9f0b76172f068425d7f6f5133a42
21.21
96
0.682125
4.214421
false
false
false
false
Jamnitzer/Wavey-Checkers-Compute-
Wavey_Checkers_Compute/ViewController.swift
1
15460
//------------------------------------------------------------------------------------------ // ViewController.m // Metal Example // // Created by Stefan Johnson on 4/06/2014. // Copyright (c) 2014 Stefan Johnson. All rights reserved. // //------------------------------------------------------------------------------------------ // ScrimpyCat/Metal-Examples //------------------------------------------------------------------------------------------ // converted to Swift by Jim Wrenholt. //------------------------------------------------------------------------------------------ import UIKit import Metal let RESOURCE_COUNT = 3 //------------------------------------------------------------------------------------------ struct V2f { let x:Float let y:Float } //------------------------------------------------------------------------------------------ struct PointData { let position:V2f let texCoord:V2f } //------------------------------------------------------------------------------------------ struct BufferDataB { var pointA:PointData var pointB:PointData var pointC:PointData var pointD:PointData let rectScale:V2f let timeA:Float let timeB:Float let timeC:Float } //------------------------------------------------------------------------------------------ class ViewController: UIViewController { var commandQueue:MTLCommandQueue! = nil var renderLayer:CAMetalLayer! = nil var renderPass:MTLRenderPassDescriptor? = nil var displayLink:CADisplayLink! = nil // calls render.. var colourPipeline:MTLRenderPipelineState! = nil var checkerPipeline:MTLComputePipelineState! = nil var data:MTLBuffer! = nil var checkerTexture:MTLTexture! = nil var previousTime:CFTimeInterval = 0 var time:Float = 0.0 var resourceSemaphore:dispatch_semaphore_t! = nil var renderFrameCycle:UInt = 0 var defaultLibrary:MTLLibrary? = nil var drawable:CAMetalDrawable? = nil //-------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() let device = MTLCreateSystemDefaultDevice() commandQueue = device!.newCommandQueue() defaultLibrary = device!.newDefaultLibrary() //----------------------------------------------------------- // vertex attribute for position //----------------------------------------------------------- let PositionDescriptor = MTLVertexAttributeDescriptor() PositionDescriptor.format = MTLVertexFormat.Float2 PositionDescriptor.offset = 0 // offsetof(PointData, position) PositionDescriptor.bufferIndex = 0 //----------------------------------------------------------- // vertex attribute for texCoord //----------------------------------------------------------- let TexCoordDescriptor = MTLVertexAttributeDescriptor() TexCoordDescriptor.format = MTLVertexFormat.Float2 TexCoordDescriptor.offset = sizeof(V2f) // offsetof(PointData, texCoord) TexCoordDescriptor.bufferIndex = 0 // //----------------------------------------------------------- // Layout descriptor for Vertex Data. //----------------------------------------------------------- let LayoutDescriptor = MTLVertexBufferLayoutDescriptor() LayoutDescriptor.stride = sizeof(PointData) LayoutDescriptor.stepFunction = MTLVertexStepFunction.PerVertex LayoutDescriptor.stepRate = 1 // //----------------------------------------------------------- // vertex descriptor for rect. //----------------------------------------------------------- let RectDescriptor = MTLVertexDescriptor() RectDescriptor.attributes[0] = PositionDescriptor RectDescriptor.attributes[1] = TexCoordDescriptor RectDescriptor.layouts[0] = LayoutDescriptor //----------------------------------------------------------- // Colour Pipeline shader. //----------------------------------------------------------- let vertexProgram = defaultLibrary!.newFunctionWithName("ColourVertex") let fragmentProgram = defaultLibrary!.newFunctionWithName("ColourFragment") let ColourPipelineDescriptor = MTLRenderPipelineDescriptor() ColourPipelineDescriptor.label = "ColourPipeline" ColourPipelineDescriptor.colorAttachments[0].pixelFormat = MTLPixelFormat.BGRA8Unorm ColourPipelineDescriptor.vertexFunction = vertexProgram! ColourPipelineDescriptor.fragmentFunction = fragmentProgram ColourPipelineDescriptor.vertexDescriptor = RectDescriptor do { self.colourPipeline = try device!.newRenderPipelineStateWithDescriptor( ColourPipelineDescriptor) } catch let pipeline_err as NSError { print("pipeline_err = \(pipeline_err)") } //----------------------------------------------------------- // compute pipeline state. //----------------------------------------------------------- let computeFunction = defaultLibrary!.newFunctionWithName("CheckerKernel") do { self.checkerPipeline = try device!.newComputePipelineStateWithFunction( computeFunction!) } catch let pipeline_err as NSError { print("pipeline_err = \(pipeline_err)") } //----------------------------------------------------------- // fill in BufferData. //----------------------------------------------------------- let Size:CGSize = self.view.bounds.size let Scale:Float = 63.8 //----------------------------------------------------------- var src_data = BufferDataB( pointA: PointData( position: V2f(x:Float(-1.0), y:Float(-1.0)), texCoord: V2f(x:Float( 0.0), y:Float( 0.0))), pointB:PointData( position: V2f(x:Float(+1.0), y:Float(-1.0)), texCoord: V2f(x:Float(+1.0), y:Float( 0.0))), pointC:PointData( position: V2f(x:Float(-1.0), y:Float(+1.0)), texCoord: V2f(x:Float( 0.0), y:Float(+1.0))), pointD:PointData( position: V2f(x:Float(+1.0), y:Float(+1.0)), texCoord: V2f(x:Float(+1.0), y:Float(+1.0))), rectScale: V2f(x: Scale / Float(Size.width), y: Scale / Float(Size.height)), timeA: Float(0.0), timeB: Float(0.0), timeC: Float(0.0) ) //----------------------------------------------------------- // new buffer with BufferData. //----------------------------------------------------------- self.data = device!.newBufferWithLength(sizeof(BufferDataB), options:MTLResourceOptions.OptionCPUCacheModeDefault) // print("sizeof(PointData) = \(sizeof(PointData))") // print("sizeof(BufferDataB) = \(sizeof(BufferDataB))") let bufferPointer = data?.contents() memcpy(bufferPointer!, &src_data, Int(sizeof(BufferDataB))) //----------------------------------------------------------- // new texture checkerTexture. //----------------------------------------------------------- let ContentScale:CGFloat = UIScreen.mainScreen().scale let texWidth = Int(Size.width * ContentScale) let texHeight = Int(Size.height * ContentScale) let texDescriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( MTLPixelFormat.BGRA8Unorm, width:texWidth, height:texHeight, mipmapped:false) self.checkerTexture = device!.newTextureWithDescriptor(texDescriptor) //----------------------------------------------------------- // generate the checker texture. //----------------------------------------------------------- generateCheckerTexture() //----------------------------------------------------------- // render layer. //----------------------------------------------------------- self.renderLayer = CAMetalLayer() renderLayer.device = device renderLayer.pixelFormat = .BGRA8Unorm renderLayer.framebufferOnly = true renderLayer.frame = view.layer.frame var drawableSize = view.bounds.size drawableSize.width = drawableSize.width * CGFloat(view.contentScaleFactor) drawableSize.height = drawableSize.height * CGFloat(view.contentScaleFactor) renderLayer.drawableSize = drawableSize self.view.layer.addSublayer(self.renderLayer) self.view.opaque = true self.view.contentScaleFactor = ContentScale self.resourceSemaphore = dispatch_semaphore_create(RESOURCE_COUNT) previousTime = CACurrentMediaTime() displayLink = CADisplayLink(target: self, selector: Selector("render")) displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) } //-------------------------------------------------------------------- override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //-------------------------------------------------------------------- override func prefersStatusBarHidden() -> Bool { return true } //-------------------------------------------------------------------- func generateCheckerTexture() { //----------------------------------------------------------- // called only once to fill in a texture. //----------------------------------------------------------- let commandBuffer = commandQueue.commandBuffer() commandBuffer.label = "CreateCheckerTextureCommandBuffer" let WorkGroupSize = MTLSizeMake(16, 16, 1) let WorkGroupCount = MTLSizeMake( checkerTexture.width / 16 / 4, checkerTexture.height / 16, 1) let computeEncoder = commandBuffer.computeCommandEncoder() computeEncoder.pushDebugGroup("Create checker texture") // SET PIPELINE STATE computeEncoder.setComputePipelineState(checkerPipeline) // SET BUFFERDATA let scaleOffset = 4 * sizeof(PointData) computeEncoder.setBuffer(data, offset: scaleOffset, atIndex: 0) //offsetof(BufferData, rectScale) // SET TEXTURE computeEncoder.setTexture(checkerTexture, atIndex: 0) // THREADGROUPS computeEncoder.dispatchThreadgroups(WorkGroupCount, threadsPerThreadgroup: WorkGroupSize) computeEncoder.popDebugGroup() computeEncoder.endEncoding() commandBuffer.commit() } //-------------------------------------------------------------------- //-------------------------------------------------------------------- func render() { dispatch_semaphore_wait(resourceSemaphore, DISPATCH_TIME_FOREVER) //-------------------------------------------------------- //-------------------------------------------------------- self.renderFrameCycle = UInt(renderFrameCycle + 1) % UInt(RESOURCE_COUNT) let Current:CFTimeInterval = CACurrentMediaTime() let DeltaTime:CFTimeInterval = Current - previousTime previousTime = Current time += Float(0.2) * Float(DeltaTime) //-------------------------------------------------------- // renderFrameCycle //-------------------------------------------------------- let timeOffset = sizeof(PointData) * 4 + sizeof(V2f) + sizeof(Float) * Int(renderFrameCycle) //-------------------------------------------------------- // this updates time [0, 1, or 2] for the shader. //-------------------------------------------------------- let bufferPointer = data?.contents() memcpy(bufferPointer! + timeOffset, &time, Int(sizeof(Float))) let commandBuffer = commandQueue.commandBuffer() commandBuffer.label = "RenderFrameCommandBuffer" let renderPassDesc:MTLRenderPassDescriptor = currentFramebuffer() let RenderCommand = commandBuffer.renderCommandEncoderWithDescriptor( renderPassDesc ) RenderCommand.pushDebugGroup("Apply wave") let aViewport = MTLViewport(originX: 0.0, originY: 0.0, width: Double(renderLayer.drawableSize.width), height: Double(renderLayer.drawableSize.height), znear: 0.0, zfar: 1.0) RenderCommand.setViewport(aViewport) RenderCommand.setRenderPipelineState(colourPipeline!) RenderCommand.setVertexBuffer( data!, offset:0, //offsetof(BufferData, rect) atIndex:0 ) RenderCommand.setFragmentTexture(checkerTexture!, atIndex:0) RenderCommand.setFragmentBuffer(data!, offset:timeOffset, // offsetof(BufferData, time[renderFrameCycle]) atIndex:0 ) //-------------------------------------------------------------------- RenderCommand.drawPrimitives( MTLPrimitiveType.TriangleStrip, vertexStart:0, vertexCount:4 ) RenderCommand.popDebugGroup() RenderCommand.endEncoding() commandBuffer.presentDrawable(currentDrawable()!) //---------------------------------------------------------------- commandBuffer.addCompletedHandler{ [weak self] commandBuffer in if let strongSelf = self { dispatch_semaphore_signal(strongSelf.resourceSemaphore) } return } //---------------------------------------------------------------- commandBuffer.commit() renderPass = nil drawable = nil } //-------------------------------------------------------------------- func currentFramebuffer() -> MTLRenderPassDescriptor { if (renderPass == nil) { let Drawable = self.currentDrawable() if (Drawable != nil) { self.renderPass = MTLRenderPassDescriptor() renderPass!.colorAttachments[0].texture = Drawable!.texture renderPass!.colorAttachments[0].loadAction = MTLLoadAction.DontCare renderPass!.colorAttachments[0].storeAction = MTLStoreAction.Store } } return renderPass! } //-------------------------------------------------------------------- func currentDrawable() -> CAMetalDrawable? { while (self.drawable == nil) { self.drawable = renderLayer.nextDrawable() } return self.drawable } //-------------------------------------------------------------------- deinit { displayLink.invalidate() } //-------------------------------------------------------------------- } //--------------------------------------------------------------------------------
bsd-2-clause
6704887e4f6e6d9f932ca3238820c156
39.791557
108
0.470246
6.159363
false
false
false
false
tokyovigilante/CesiumKit
CesiumKit/Renderer/UniformState.swift
1
36358
// // UniformState.swift // CesiumKit // // Created by Ryan Walklin on 22/06/14. // Copyright (c) 2014 Test Toast. All rights reserved. // import Foundation import simd struct AutomaticUniformBufferLayout { var czm_a_viewRotation = float3x3() var czm_a_temeToPseudoFixed = float3x3() var czm_a_sunDirectionEC = float3() var czm_a_sunDirectionWC = float3() var czm_a_moonDirectionEC = float3() var czm_a_viewerPositionWC = float3() var czm_a_morphTime = Float() var czm_a_fogDensity = Float() var czm_a_frameNumber = Float() var czm_a_pass = Float() } struct FrustumUniformBufferLayout { var czm_f_viewportOrthographic = float4x4() var czm_f_viewportTransformation = float4x4() var czm_f_projection = float4x4() var czm_f_inverseProjection = float4x4() var czm_f_view = float4x4() var czm_f_modelView = float4x4() var czm_f_modelView3D = float4x4() var czm_f_inverseModelView = float4x4() var czm_f_modelViewProjection = float4x4() var czm_f_viewport = float4() var czm_f_normal = float3x3() var czm_f_normal3D = float3x3() var czm_f_entireFrustum = float2() } class UniformState { /** * @type {Texture} */ var globeDepthTexture: Texture? = nil /** * @private */ fileprivate var _viewport = Cartesian4() fileprivate var _viewportDirty = false fileprivate var _viewportOrthographicMatrix = Matrix4.identity fileprivate var _viewportTransformation = Matrix4.identity fileprivate var _model = Matrix4.identity fileprivate var _view = Matrix4.identity fileprivate var _inverseView = Matrix4.identity fileprivate var _projection = Matrix4.identity fileprivate var _infiniteProjection = Matrix4.identity fileprivate var _entireFrustum = Cartesian2() fileprivate var _currentFrustum = Cartesian2() fileprivate var _frustumPlanes = Cartesian4() /** * @memberof UniformState.prototype * @type {FrameState} * @readonly */ var frameState: FrameState! = nil fileprivate var _temeToPseudoFixed = Matrix3(fromMatrix4: Matrix4.identity) // Derived members fileprivate var _view3DDirty = true fileprivate var _view3D = Matrix4() fileprivate var _inverseView3DDirty = true fileprivate var _inverseView3D = Matrix4() fileprivate var _inverseModelDirty = true fileprivate var _inverseModel = Matrix4() fileprivate var _inverseTransposeModelDirty = true fileprivate var _inverseTransposeModel = Matrix3() fileprivate var _viewRotation = Matrix3() fileprivate var _inverseViewRotation = Matrix3() fileprivate var _viewRotation3D = Matrix3() fileprivate var _inverseViewRotation3D = Matrix3() fileprivate var _inverseProjectionDirty = true fileprivate var _inverseProjection = Matrix4() fileprivate var _inverseProjectionOITDirty = true fileprivate var _inverseProjectionOIT = Matrix4() fileprivate var _modelViewDirty = true fileprivate var _modelView = Matrix4() fileprivate var _modelView3DDirty = true fileprivate var _modelView3D = Matrix4() fileprivate var _modelViewRelativeToEyeDirty = true fileprivate var _modelViewRelativeToEye = Matrix4() fileprivate var _inverseModelViewDirty = true fileprivate var _inverseModelView = Matrix4() fileprivate var _inverseModelView3DDirty = true fileprivate var _inverseModelView3D = Matrix4() fileprivate var _viewProjectionDirty = true fileprivate var _viewProjection = Matrix4() fileprivate var _inverseViewProjectionDirty = true fileprivate var _inverseViewProjection = Matrix4() fileprivate var _modelViewProjectionDirty = true fileprivate var _modelViewProjection = Matrix4() fileprivate var _inverseModelViewProjectionDirty = true fileprivate var _inverseModelViewProjection = Matrix4() fileprivate var _modelViewProjectionRelativeToEyeDirty = true fileprivate var _modelViewProjectionRelativeToEye = Matrix4() fileprivate var _modelViewInfiniteProjectionDirty = true fileprivate var _modelViewInfiniteProjection = Matrix4() fileprivate var _normalDirty = true fileprivate var _normal = Matrix3() fileprivate var _normal3DDirty = true fileprivate var _normal3D = Matrix3() fileprivate var _inverseNormalDirty = true fileprivate var _inverseNormal = Matrix3() fileprivate var _inverseNormal3DDirty = true fileprivate var _inverseNormal3D = Matrix3() fileprivate var _encodedCameraPositionMCDirty = true fileprivate var _encodedCameraPositionMC = EncodedCartesian3() fileprivate var _cameraPosition = Cartesian3() fileprivate var _sunPositionWC = Cartesian3() fileprivate var _sunPositionColumbusView = Cartesian3() fileprivate var _sunDirectionWC = Cartesian3() fileprivate var _sunDirectionEC = Cartesian3() fileprivate var _moonDirectionEC = Cartesian3() fileprivate var _mode: SceneMode? = nil fileprivate var _mapProjection: MapProjection? = nil fileprivate var _cameraDirection = Cartesian3() fileprivate var _cameraRight = Cartesian3() fileprivate var _cameraUp = Cartesian3() fileprivate var _frustum2DWidth = 0.0 fileprivate var _eyeHeight2D = Cartesian2() fileprivate var _fogDensity: Float = 1.0 fileprivate var _pass: Pass = .compute /** * @memberof UniformState.prototype * @type {BoundingRectangle} */ var viewport: Cartesian4 { get { return _viewport } set (value) { _viewport = value _viewportDirty = true } } var viewportOrthographic: Matrix4 { cleanViewport() return _viewportOrthographicMatrix } var viewportTransformation: Matrix4 { cleanViewport() return _viewportTransformation } /** * @memberof UniformState.prototype * @type {Matrix4} */ var model: Matrix4 { get { return _model } set (value) { if _model == value { return } _model = value _modelView3DDirty = true _inverseModelView3DDirty = true _inverseModelDirty = true _inverseTransposeModelDirty = true _modelViewDirty = true _inverseModelViewDirty = true _viewProjectionDirty = true _inverseViewProjectionDirty = true _modelViewRelativeToEyeDirty = true _inverseModelViewDirty = true _modelViewProjectionDirty = true _inverseModelViewProjectionDirty = true _modelViewProjectionRelativeToEyeDirty = true _modelViewInfiniteProjectionDirty = true _normalDirty = true _inverseNormalDirty = true _normal3DDirty = true _inverseNormal3DDirty = true _encodedCameraPositionMCDirty = true } } /* /** * @memberof UniformState.prototype * @type {Matrix4} */ inverseModel : { get : function() { if (this._inverseModelDirty) { this._inverseModelDirty = false; Matrix4.inverse(this._model, this._inverseModel); } return this._inverseModel; } }, /** * @memberof UniformState.prototype * @private */ inverseTranposeModel : { get : function() { var m = this._inverseTransposeModel; if (this._inverseTransposeModelDirty) { this._inverseTransposeModelDirty = false; Matrix4.getRotation(this.inverseModel, m); Matrix3.transpose(m, m); } return m; } }, */ /** * @memberof UniformState.prototype * @type {Matrix4} */ var view: Matrix4 { return _view } /** * The 3D view matrix. In 3D mode, this is identical to {@link UniformState#view}, * but in 2D and Columbus View it is a synthetic matrix based on the equivalent position * of the camera in the 3D world. * @memberof UniformState.prototype * @type {Matrix4} */ var view3D: Matrix4 { updateView3D() return _view3D } /** * The 3x3 rotation matrix of the current view matrix ({@link UniformState#view}). * @memberof UniformState.prototype * @type {Matrix3} */ var viewRotation: Matrix3 { updateView3D() return _viewRotation } /** * @memberof UniformState.prototype * @type {Matrix3} */ var viewRotation3D: Matrix3 { let _ = view3D return _viewRotation3D } /** * @memberof UniformState.prototype * @type {Matrix4} */ var inverseView: Matrix4 { return _inverseView } /** * the 4x4 inverse-view matrix that transforms from eye to 3D world coordinates. In 3D mode, this is * identical to {@link UniformState#inverseView}, but in 2D and Columbus View it is a synthetic matrix * based on the equivalent position of the camera in the 3D world. * @memberof UniformState.prototype * @type {Matrix4} */ var inverseView3D: Matrix4 { updateInverseView3D() return _inverseView3D } /* /** * @memberof UniformState.prototype * @type {Matrix3} */ inverseViewRotation : { get : function() { return this._inverseViewRotation; } }, /** * The 3x3 rotation matrix of the current 3D inverse-view matrix ({@link UniformState#inverseView3D}). * @memberof UniformState.prototype * @type {Matrix3} */ inverseViewRotation3D : { get : function() { var inverseView = this.inverseView3D; return this._inverseViewRotation3D; } }, */ /** * @memberof UniformState.prototype * @type {Matrix4} */ var projection: Matrix4 { get { return _projection } set (value) { _projection = value _inverseProjectionDirty = true _inverseProjectionOITDirty = true _viewProjectionDirty = true _modelViewProjectionDirty = true _modelViewProjectionRelativeToEyeDirty = true } } /** * @memberof UniformState.prototype * @type {Matrix4} */ var inverseProjection: Matrix4 { get { cleanInverseProjection() return _inverseProjection } } /* /** * @memberof UniformState.prototype * @private */ inverseProjectionOIT : { get : function() { cleanInverseProjectionOIT(this); return this._inverseProjectionOIT; } }, */ /** * @memberof UniformState.prototype * @type {Matrix4} */ var infiniteProjection: Matrix4 { get { return _infiniteProjection } set (value) { _infiniteProjection = value _modelViewInfiniteProjectionDirty = true } } /** * @memberof UniformState.prototype * @type {Matrix4} */ var modelView: Matrix4 { get { cleanModelView() return _modelView } } /** * The 3D model-view matrix. In 3D mode, this is equivalent to {@link UniformState#modelView}. In 2D and * Columbus View, however, it is a synthetic matrix based on the equivalent position of the camera in the 3D world. * @memberof UniformState.prototype * @type {Matrix4} */ var modelView3D: Matrix4 { get { cleanModelView3D() return _modelView3D } } /* /** * Model-view relative to eye matrix. * * @memberof UniformState.prototype * @type {Matrix4} */ modelViewRelativeToEye : { get : function() { cleanModelViewRelativeToEye(this); return this._modelViewRelativeToEye; } }, */ /** * @memberof UniformState.prototype * @type {Matrix4} */ var inverseModelView: Matrix4 { get { cleanInverseModelView() return _inverseModelView } } /** * The inverse of the 3D model-view matrix. In 3D mode, this is equivalent to {@link UniformState#inverseModelView}. * In 2D and Columbus View, however, it is a synthetic matrix based on the equivalent position of the camera in the 3D world. * @memberof UniformState.prototype * @type {Matrix4} */ var inverseModelView3D: Matrix4 { get { cleanInverseModelView3D() return _inverseModelView3D } } /** * @memberof UniformState.prototype * @type {Matrix4} */ var viewProjection: Matrix4 { cleanViewProjection() return _viewProjection } /** * @memberof UniformState.prototype * @type {Matrix4} */ var inverseViewProjection: Matrix4 { cleanInverseViewProjection() return _inverseViewProjection } /** * @memberof UniformState.prototype * @type {Matrix4} */ var modelViewProjection: Matrix4 { cleanModelViewProjection() return _modelViewProjection } /* /** * @memberof UniformState.prototype * @type {Matrix4} */ inverseModelViewProjection : { get : function() { cleanInverseModelViewProjection(this); return this._inverseModelViewProjection; } }, /** * Model-view-projection relative to eye matrix. * * @memberof UniformState.prototype * @type {Matrix4} */ modelViewProjectionRelativeToEye : { get : function() { cleanModelViewProjectionRelativeToEye(this); return this._modelViewProjectionRelativeToEye; } }, /** * @memberof UniformState.prototype * @type {Matrix4} */ modelViewInfiniteProjection : { get : function() { cleanModelViewInfiniteProjection(this); return this._modelViewInfiniteProjection; } }, */ /** * A 3x3 normal transformation matrix that transforms normal vectors in model coordinates to * eye coordinates. * @memberof UniformState.prototype * @type {Matrix3} */ var normal: Matrix3 { cleanNormal() return _normal } /** * A 3x3 normal transformation matrix that transforms normal vectors in 3D model * coordinates to eye coordinates. In 3D mode, this is identical to * {@link UniformState#normal}, but in 2D and Columbus View it represents the normal transformation * matrix as if the camera were at an equivalent location in 3D mode. * @memberof UniformState.prototype * @type {Matrix3} */ var normal3D: Matrix3 { cleanNormal3D() return _normal3D } /* /** * An inverse 3x3 normal transformation matrix that transforms normal vectors in model coordinates * to eye coordinates. * @memberof UniformState.prototype * @type {Matrix3} */ inverseNormal : { get : function() { cleanInverseNormal(this); return this._inverseNormal; } }, /** * An inverse 3x3 normal transformation matrix that transforms normal vectors in eye coordinates * to 3D model coordinates. In 3D mode, this is identical to * {@link UniformState#inverseNormal}, but in 2D and Columbus View it represents the normal transformation * matrix as if the camera were at an equivalent location in 3D mode. * @memberof UniformState.prototype * @type {Matrix3} */ inverseNormal3D : { get : function() { cleanInverseNormal3D(this); return this._inverseNormal3D; } }, */ /** * The near distance (<code>x</code>) and the far distance (<code>y</code>) of the frustum defined by the camera. * This is the largest possible frustum, not an individual frustum used for multi-frustum rendering. * @memberof UniformState.prototype * @type {Cartesian2} */ var entireFrustum: Cartesian2 { return _entireFrustum } /* /** * The near distance (<code>x</code>) and the far distance (<code>y</code>) of the frustum defined by the camera. * This is the individual frustum used for multi-frustum rendering. * @memberof UniformState.prototype * @type {Cartesian2} */ currentFrustum : { get : function() { return this._currentFrustum; } }, /** The distances to the frustum planes. The top, bottom, left and right distances are * the x, y, z, and w components, respectively. * @memberof UniformState.prototype * @type {Cartesian4} */ frustumPlanes : { get : function() { return this._frustumPlanes; } }, /** * The the height (<code>x</code>) and the height squared (<code>y</code>) * in meters of the camera above the 2D world plane. This uniform is only valid * when the {@link SceneMode} equal to <code>SCENE2D</code>. * @memberof UniformState.prototype * @type {Cartesian2} */ eyeHeight2D : { get : function() { return this._eyeHeight2D; } }, /** * The sun position in 3D world coordinates at the current scene time. * @memberof UniformState.prototype * @type {Cartesian3} */ sunPositionWC : { get : function() { return this._sunPositionWC; } }, /** * The sun position in 2D world coordinates at the current scene time. * @memberof UniformState.prototype * @type {Cartesian3} */ sunPositionColumbusView : { get : function(){ return this._sunPositionColumbusView; } }, */ /** * A normalized vector to the sun in 3D world coordinates at the current scene time. Even in 2D or * Columbus View mode, this returns the position of the sun in the 3D scene. * @memberof UniformState.prototype * @type {Cartesian3} */ var sunDirectionWC: Cartesian3 { return _sunDirectionWC } /** * A normalized vector to the sun in eye coordinates at the current scene time. In 3D mode, this * returns the actual vector from the camera position to the sun position. In 2D and Columbus View, it returns * the vector from the equivalent 3D camera position to the position of the sun in the 3D scene. * @memberof UniformState.prototype * @type {Cartesian3} */ var sunDirectionEC: Cartesian3 { return _sunDirectionEC } /** * A normalized vector to the moon in eye coordinates at the current scene time. In 3D mode, this * returns the actual vector from the camera position to the moon position. In 2D and Columbus View, it returns * the vector from the equivalent 3D camera position to the position of the moon in the 3D scene. * @memberof UniformState.prototype * @type {Cartesian3} */ var moonDirectionEC: Cartesian3 { get { return _moonDirectionEC } } /* /** * The high bits of the camera position. * @memberof UniformState.prototype * @type {Cartesian3} */ encodedCameraPositionMCHigh : { get : function() { cleanEncodedCameraPositionMC(this); return this._encodedCameraPositionMC.high; } }, /** * The low bits of the camera position. * @memberof UniformState.prototype * @type {Cartesian3} */ encodedCameraPositionMCLow : { get : function() { cleanEncodedCameraPositionMC(this); return this._encodedCameraPositionMC.low; } }, */ /** * A 3x3 matrix that transforms from True Equator Mean Equinox (TEME) axes to the * pseudo-fixed axes at the Scene's current time. * @memberof UniformState.prototype * @type {Matrix3} */ var temeToPseudoFixedMatrix: Matrix3 { return _temeToPseudoFixed } /* /** * Gets the scaling factor for transforming from the canvas * pixel space to canvas coordinate space. * @memberof UniformState.prototype * @type {Number} */ resolutionScale : { get : function() { return this._resolutionScale; } } }); */ var fogDensity: Float { return _fogDensity } /** * @memberof UniformState.prototype * @type {Pass} */ var pass: Float { return Float(_pass.rawValue) } func setView(_ matrix: Matrix4) { _view = matrix _viewRotation = _view.rotation _view3DDirty = true _inverseView3DDirty = true _modelViewDirty = true _modelView3DDirty = true _modelViewRelativeToEyeDirty = true _inverseModelViewDirty = true _inverseModelView3DDirty = true _viewProjectionDirty = true _modelViewProjectionDirty = true _modelViewProjectionRelativeToEyeDirty = true _modelViewInfiniteProjectionDirty = true _normalDirty = true _inverseNormalDirty = true _normal3DDirty = true _inverseNormal3DDirty = true } func setInverseView(_ matrix: Matrix4) { _inverseView = matrix _inverseViewRotation = matrix.rotation } func setCamera(_ camera: Camera) { _cameraPosition = camera.positionWC _cameraDirection = camera.directionWC _cameraRight = camera.rightWC _cameraUp = camera.upWC _encodedCameraPositionMCDirty = true } //var transformMatrix = new Matrix3(); //var sunCartographicScratch = new Cartographic(); func setSunAndMoonDirections(_ frameState: FrameState) { var transformMatrix = Matrix3() if Transforms.computeIcrfToFixedMatrix(frameState.time) == nil { transformMatrix = Transforms.computeTemeToPseudoFixedMatrix(frameState.time) } _sunPositionWC = transformMatrix.multiplyByVector(Simon1994PlanetaryPositions.sharedInstance.computeSunPositionInEarthInertialFrame(frameState.time)) _sunDirectionWC = _sunPositionWC.normalize() _sunDirectionEC = viewRotation3D.multiplyByVector(_sunPositionWC).normalize() _moonDirectionEC = transformMatrix.multiplyByVector(Simon1994PlanetaryPositions.sharedInstance.computeMoonPositionInEarthInertialFrame(frameState.time)).normalize() //_moonDirectionEC = position /*Matrix3.multiplyByVector(transformMatrix, position, position); Matrix3.multiplyByVector(uniformState.viewRotation3D, position, position); Cartesian3.normalize(position, position); var projection = frameState.mapProjection; var ellipsoid = projection.ellipsoid; var sunCartographic = ellipsoid.cartesianToCartographic(uniformState._sunPositionWC, sunCartographicScratch); projection.project(sunCartographic, uniformState._sunPositionColumbusView)*/ } func updatePass (_ pass: Pass) { _pass = pass } /** * Synchronizes the frustum's state with the uniform state. This is called * by the {@link Scene} when rendering to ensure that automatic GLSL uniforms * are set to the right value. * * @param {Object} frustum The frustum to synchronize with. */ func updateFrustum (_ frustum: Frustum) { var frustum = frustum projection = frustum.projectionMatrix if frustum.infiniteProjectionMatrix != nil { infiniteProjection = frustum.infiniteProjectionMatrix! } _currentFrustum.x = frustum.near _currentFrustum.y = frustum.far if frustum.top != Double.nan { frustum = (frustum as! PerspectiveFrustum)._offCenterFrustum } _frustumPlanes.x = frustum.top _frustumPlanes.y = frustum.bottom _frustumPlanes.z = frustum.left _frustumPlanes.w = frustum.right } /** * Synchronizes frame state with the uniform state. This is called * by the {@link Scene} when rendering to ensure that automatic GLSL uniforms * are set to the right value. * * @param {FrameState} frameState The frameState to synchronize with. */ func update(_ context: Context, frameState: FrameState) { self.frameState = frameState _mode = self.frameState.mode _mapProjection = self.frameState.mapProjection let camera = frameState.camera! setView(camera.viewMatrix) setInverseView(camera.inverseViewMatrix) setCamera(camera) if self.frameState.mode == SceneMode.scene2D { _frustum2DWidth = camera.frustum.right - camera.frustum.left _eyeHeight2D.x = _frustum2DWidth * 0.5 _eyeHeight2D.y = _eyeHeight2D.x * _eyeHeight2D.x } else { _frustum2DWidth = 0.0 _eyeHeight2D.x = 0.0 _eyeHeight2D.y = 0.0 } //FIXME: setSunAndMoonDirections setSunAndMoonDirections(self.frameState) _entireFrustum.x = camera.frustum.near _entireFrustum.y = camera.frustum.far updateFrustum(camera.frustum) _fogDensity = Float(frameState.fog.density) _temeToPseudoFixed = Transforms.computeTemeToPseudoFixedMatrix(self.frameState.time!) } func setAutomaticUniforms (_ buffer: Buffer) { var layout = AutomaticUniformBufferLayout() layout.czm_a_viewRotation = viewRotation.floatRepresentation layout.czm_a_temeToPseudoFixed = temeToPseudoFixedMatrix.floatRepresentation layout.czm_a_sunDirectionEC = sunDirectionEC.floatRepresentation layout.czm_a_sunDirectionWC = sunDirectionWC.floatRepresentation layout.czm_a_moonDirectionEC = moonDirectionEC.floatRepresentation layout.czm_a_viewerPositionWC = inverseView.translation.floatRepresentation layout.czm_a_morphTime = Float(frameState.morphTime) layout.czm_a_fogDensity = fogDensity layout.czm_a_frameNumber = Float(frameState.frameNumber) layout.czm_a_pass = pass buffer.write(from: &layout, length: MemoryLayout<AutomaticUniformBufferLayout>.size) } func setFrustumUniforms (_ buffer: Buffer) { var layout = FrustumUniformBufferLayout() layout.czm_f_viewportOrthographic = viewportOrthographic.floatRepresentation layout.czm_f_viewportTransformation = viewportTransformation.floatRepresentation layout.czm_f_projection = projection.floatRepresentation layout.czm_f_inverseProjection = inverseProjection.floatRepresentation layout.czm_f_view = view.floatRepresentation layout.czm_f_modelView = modelView.floatRepresentation layout.czm_f_modelView3D = modelView3D.floatRepresentation layout.czm_f_inverseModelView = inverseModelView.floatRepresentation layout.czm_f_modelViewProjection = modelViewProjection.floatRepresentation layout.czm_f_viewport = viewport.floatRepresentation layout.czm_f_normal = normal.floatRepresentation layout.czm_f_normal3D = normal3D.floatRepresentation layout.czm_f_entireFrustum = entireFrustum.floatRepresentation buffer.write(from: &layout, length: MemoryLayout<FrustumUniformBufferLayout>.size) } func cleanViewport() { if _viewportDirty { _viewportOrthographicMatrix = Matrix4.computeOrthographicOffCenter(left: _viewport.x, right: _viewport.x + _viewport.width, bottom: _viewport.y, top: _viewport.y + _viewport.height) _viewportTransformation = Matrix4.computeViewportTransformation(_viewport) _viewportDirty = false } } func cleanInverseProjection() { if _inverseProjectionDirty { _inverseProjectionDirty = false _inverseProjection = _projection.inverse } } /* function cleanInverseProjectionOIT(uniformState) { if (uniformState._inverseProjectionOITDirty) { uniformState._inverseProjectionOITDirty = false; if (uniformState._mode !== SceneMode.SCENE2D && uniformState._mode !== SceneMode.MORPHING) { Matrix4.inverse(uniformState._projection, uniformState._inverseProjectionOIT); } else { Matrix4.clone(Matrix4.IDENTITY, uniformState._inverseProjectionOIT); } } } */ // Derived func cleanModelView() { if _modelViewDirty { _modelViewDirty = false _modelView = _view.multiply(_model) } } func cleanModelView3D() { if _modelView3DDirty { _modelView3DDirty = false _modelView3D = view3D.multiply(_model) } } func cleanInverseModelView() { if _inverseModelViewDirty { _inverseModelViewDirty = false _inverseModelView = modelView.inverse } } func cleanInverseModelView3D() { if _inverseModelView3DDirty { _inverseModelView3DDirty = false _inverseModelView3D = modelView3D.inverse } } func cleanViewProjection() { if (_viewProjectionDirty) { _viewProjectionDirty = false _viewProjection = _projection.multiply(_view) } } func cleanInverseViewProjection() { if (_inverseViewProjectionDirty) { _inverseViewProjectionDirty = false _inverseViewProjection = viewProjection.inverse } } func cleanModelViewProjection() { if _modelViewProjectionDirty { _modelViewProjectionDirty = false _modelViewProjection = _projection.multiply(modelView) } } /* function cleanModelViewRelativeToEye(uniformState) { if (uniformState._modelViewRelativeToEyeDirty) { uniformState._modelViewRelativeToEyeDirty = false; var mv = uniformState.modelView; var mvRte = uniformState._modelViewRelativeToEye; mvRte[0] = mv[0]; mvRte[1] = mv[1]; mvRte[2] = mv[2]; mvRte[3] = mv[3]; mvRte[4] = mv[4]; mvRte[5] = mv[5]; mvRte[6] = mv[6]; mvRte[7] = mv[7]; mvRte[8] = mv[8]; mvRte[9] = mv[9]; mvRte[10] = mv[10]; mvRte[11] = mv[11]; mvRte[12] = 0.0; mvRte[13] = 0.0; mvRte[14] = 0.0; mvRte[15] = mv[15]; } } function cleanInverseModelViewProjection(uniformState) { if (uniformState._inverseModelViewProjectionDirty) { uniformState._inverseModelViewProjectionDirty = false; Matrix4.inverse(uniformState.modelViewProjection, uniformState._inverseModelViewProjection); } } function cleanModelViewProjectionRelativeToEye(uniformState) { if (uniformState._modelViewProjectionRelativeToEyeDirty) { uniformState._modelViewProjectionRelativeToEyeDirty = false; Matrix4.multiply(uniformState._projection, uniformState.modelViewRelativeToEye, uniformState._modelViewProjectionRelativeToEye); } } function cleanModelViewInfiniteProjection(uniformState) { if (uniformState._modelViewInfiniteProjectionDirty) { uniformState._modelViewInfiniteProjectionDirty = false; Matrix4.multiply(uniformState._infiniteProjection, uniformState.modelView, uniformState._modelViewInfiniteProjection); } } */ func cleanNormal() { if (_normalDirty) { _normalDirty = false _normal = inverseModelView.rotation.transpose } } func cleanNormal3D() { if _normal3DDirty { _normal3DDirty = false; _normal3D = inverseModelView3D.rotation.transpose } } /* function cleanInverseNormal(uniformState) { if (uniformState._inverseNormalDirty) { uniformState._inverseNormalDirty = false; Matrix4.getRotation(uniformState.inverseModelView, uniformState._inverseNormal); } } function cleanInverseNormal3D(uniformState) { if (uniformState._inverseNormal3DDirty) { uniformState._inverseNormal3DDirty = false; Matrix4.getRotation(uniformState.inverseModelView3D, uniformState._inverseNormal3D); } } var cameraPositionMC = new Cartesian3(); function cleanEncodedCameraPositionMC(uniformState) { if (uniformState._encodedCameraPositionMCDirty) { uniformState._encodedCameraPositionMCDirty = false; Matrix4.multiplyByPoint(uniformState.inverseModel, uniformState._cameraPosition, cameraPositionMC); EncodedCartesian3.fromCartesian(cameraPositionMC, uniformState._encodedCameraPositionMC); } } var view2Dto3DPScratch = new Cartesian3(); var view2Dto3DRScratch = new Cartesian3(); var view2Dto3DUScratch = new Cartesian3(); var view2Dto3DDScratch = new Cartesian3(); var view2Dto3DCartographicScratch = new Cartographic(); var view2Dto3DCartesian3Scratch = new Cartesian3(); var view2Dto3DMatrix4Scratch = new Matrix4(); */ func view2Dto3D(_ position2D: Cartesian3, direction2D: Cartesian3, right2D: Cartesian3, up2D: Cartesian3, frustum2DWidth: Double, mode: SceneMode, projection: MapProjection) -> Matrix4 { // The camera position and directions are expressed in the 2D coordinate system where the Y axis is to the East, // the Z axis is to the North, and the X axis is out of the map. Express them instead in the ENU axes where // X is to the East, Y is to the North, and Z is out of the local horizontal plane. var p = Cartesian3(x: position2D.y, y: position2D.z, z: position2D.x) var r = Cartesian3(x: right2D.y, y: right2D.z, z: right2D.x) var u = Cartesian3(x: up2D.y, y: up2D.z, z: up2D.x) var d = Cartesian3(x: direction2D.y, y: direction2D.z, z: direction2D.x) // In 2D, the camera height is always 12.7 million meters. // The apparent height is equal to half the frustum width. if mode == .scene2D { p.z = frustum2DWidth * 0.5 } // Compute the equivalent camera position in the real (3D) world. // In 2D and Columbus View, the camera can travel outside the projection, and when it does so // there's not really any corresponding location in the real world. So clamp the unprojected // longitude and latitude to their valid ranges. var cartographic = projection.unproject(p) cartographic.longitude = Math.clamp(cartographic.longitude, min: -.pi, max: .pi) cartographic.latitude = Math.clamp(cartographic.latitude, min: -.pi/2, max: .pi/2) let position3D = projection.ellipsoid.cartographicToCartesian(cartographic) // Compute the rotation from the local ENU at the real world camera position to the fixed axes. let enuToFixed = Transforms.eastNorthUpToFixedFrame(position3D, ellipsoid: projection.ellipsoid) // Transform each camera direction to the fixed axes. r = enuToFixed.multiplyByPointAsVector(r) u = enuToFixed.multiplyByPointAsVector(u) d = enuToFixed.multiplyByPointAsVector(d) // Compute the view matrix based on the new fixed-frame camera position and directions. return Matrix4( r.x, u.x, -d.x, 0.0, r.y, u.y, -d.y, 0.0, r.z, u.z, -d.z, 0.0, -r.dot(position3D), -u.dot(position3D), d.dot(position3D), 1.0) } fileprivate func updateView3D () { if _view3DDirty { if _mode == .scene3D { _view3D = _view } else { _view3D = view2Dto3D(_cameraPosition, direction2D: _cameraDirection, right2D: _cameraRight, up2D: _cameraUp, frustum2DWidth: _frustum2DWidth, mode: _mode!, projection: _mapProjection!) } _viewRotation3D = _view3D.rotation _view3DDirty = false } } fileprivate func updateInverseView3D () { if _inverseView3DDirty { _inverseView3D = view3D.inverse _inverseViewRotation3D = _inverseView3D.rotation _inverseView3DDirty = false } } }
apache-2.0
19aac76d24e0190a79da83b3ececf537
30.560764
200
0.639282
4.236542
false
false
false
false
invalidstream/cocoaconfappextensionsclass
CocoaConf App Extensions Class/CocoaConfExtensions_07_Watch_End/CocoaConf Today/TodayViewController.swift
3
2952
// // TodayViewController.swift // CocoaConf Today // // Created by Chris Adamson on 3/25/15. // Copyright (c) 2015 Subsequently & Furthermore, Inc. All rights reserved. // import UIKit import NotificationCenter import CocoaConfFramework class TodayViewController: UIViewController, NCWidgetProviding { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view from its nib. let confs = cocoaConf2015Events var previousLabel : UILabel? = nil for (index, conf) in confs.enumerate() { let label = UILabel () label.translatesAutoresizingMaskIntoConstraints = false label.text = "\(conf.cityName): \(conf.relativeTime().rawValue)" label.textColor = UIColor.whiteColor() self.view?.addSubview(label) let xConstraints = NSLayoutConstraint.constraintsWithVisualFormat("|-5-[label]-5-|", options: [] as NSLayoutFormatOptions, metrics: nil, views: ["label" : label]) self.view.addConstraints(xConstraints) var yConstraints : [NSLayoutConstraint]? = nil if index == 0 { // first row yConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[label]", options: [] as NSLayoutFormatOptions, metrics: nil, views: ["label" : label]) } else if index == confs.count - 1 { // last row yConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[previousLabel]-[label]", options: [] as NSLayoutFormatOptions, metrics: nil, views: ["previousLabel" : previousLabel!, "label" : label]) yConstraints?.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("V:[label]-0-|", options: [] as NSLayoutFormatOptions, metrics: nil, views: ["label" : label])) } else { // middle row yConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[previousLabel]-[label]", options: [] as NSLayoutFormatOptions, metrics: nil, views: ["previousLabel" : previousLabel!, "label" : label]) } self.view.addConstraints(yConstraints!) previousLabel = label } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData completionHandler(NCUpdateResult.NewData) } }
cc0-1.0
b9974a955ee22d667948c82990dbb295
36.846154
110
0.623306
5.188049
false
false
false
false
jwebbed/osxgmp
LibWrappers/BigFloat/BigFloat.swift
1
6883
/* This file is part of OSXGMP. OSXGMP is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OSXGMP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OSXGMP. If not, see <http://www.gnu.org/licenses/>. */ // // BigFloat.swift // BigNumber // // Created by Otto van Verseveld on 10/26/14. // Copyright (c) 2014 Otto van Verseveld. All rights reserved. // import Foundation public class BigFloat : BigFloatObjC { deinit { // println("calling deinit of \(self)") } //- GMP Paragraph 7.1 Initialization Functions. override init() { super.init() } } /*----------------------------------------------------------------------------*\ | NOTE1: All possible operators are prefixed with BFOP_NN (BigFloat OPerator), | where NN=1,...,55 | | NOTE2: From e.g. | https://medium.com/swift-programming/facets-of-swift-part-5-custom-operators-1080bc78ccc | we learn that we can NOT overload the following: | // ternary-operator: | ? : | // infix-operators: | = is as as? ?? | // prefix-operator: | & | // postfix-operator: | ? ! | The related BFOP_NN operators start with the prefixed-comment "//X (BFOP_NN)". | NOTE3: Based on the Swift standard library operator overview from e.g. | http://nshipster.com/swift-operators/ and | https://developer.apple.com/library/ios/documentation/swift/conceptual/swift_programming_language/Expressions.html | all candidate operators to be implemented for BigFloat can be found. | The overview is sorted (descending) by precedence value. \*----------------------------------------------------------------------------*/ //MARK: - Prefix operators //- (BFOP_01) Increment: prefix operator ++ //- (BFOP_02) Decrement: prefix operator -- //- (BFOP_03) Unary plus: prefix operator + //- (BFOP_04) Unary minus: prefix operator - //- (BFOP_05) Logical NOT: prefix operator ! //- (BFOP_06) Bitwise NOT: prefix operator ~ //MARK: - Infix operators //MARK: -- Exponentiative //- (BFOP_07) Power: infix operator ** { associativity left precedence 160 } //- (BFOP_08) Bitwise left shift: infix operator << { associativity left precedence 160 } //- (BFOP_09) Bitwise right shift: infix operator >> { associativity left precedence 160 } //MARK: -- Multiplicative //- (BFOP_10) Multiply: infix operator * { associativity left precedence 150 } //- (BFOP_11) Divide: infix operator / { associativity left precedence 150 } //- (BFOP_12) Remainder: infix operator % { associativity left precedence 150 } //- (BFOP_13) Multiply, ignoring overflow: infix operator &* { associativity left precedence 150 } //- (BFOP_14) Divide, ignoring overflow: infix operator &/ { associativity left precedence 150 } //- (BFOP_15) Remainder, ignoring overflow: infix operator &% { associativity left precedence 150 } //- (BFOP_16) Bitwise AND: infix operator & { associativity left precedence 150 } //MARK: -- Additive //- (BFOP_17) Add: infix operator + { associativity left precedence 140 } //- (BFOP_18) Substract: infix operator - { associativity left precedence 140 } //- (BFOP_19) Add with overflow: infix operator &+ { associativity left precedence 140 } //- (BFOP_20) Substract with overflow: infix operator &- { associativity left precedence 140 } //- (BFOP_21) Bitwise OR: infix operator | { associativity left precedence 140 } //- (BFOP_22) Bitwise XOR: infix operator ^ { associativity left precedence 140 } //MARK: -- Range //- (BFOP_23) Half-open range: infix operator ..< { associativity none precedence 135 } //- (BFOP_24) Closed range: infix operator ... { associativity none precedence 135 } //MARK: -- Cast //X (BFOP_25) Type check: infix operator is { associativity none precedence 132 } //X (BFOP_26) Type cast: infix operator as { associativity none precedence 132 } //MARK: -- Comparative //- (BFOP_27) Less than: infix operator < { associativity none precedence 130 } //- (BFOP_28) Less than or equal: infix operator <= { associativity none precedence 130 } //- (BFOP_29) Greater than: infix operator > { associativity none precedence 130 } //- (BFOP_30) Greater than or equal: infix operator >= { associativity none precedence 130 } //- (BFOP_31) Equal: infix operator == { associativity none precedence 130 } //- (BFOP_32) Not equal: infix operator != { associativity none precedence 130 } //- (BFOP_33) Identical: infix operator === { associativity none precedence 130 } //- (BFOP_34) Not identical: infix operator !== { associativity none precedence 130 } //- (BFOP_35) Pattern match: infix operator ~= { associativity none precedence 130 } //MARK: -- Conjunctive //- (BFOP_36) Logical AND: infix operator && { associativity left precedence 120 } //MARK: -- Disjunctive //- (BFOP_37) Logical OR: infix operator || { associativity left precedence 110 } //MARK: -- Nil Coalescing //X (BFOP_38) Nil coalescing: infix operator ?? { associativity right precedence 110 } //MARK: -- Ternary Conditional //X (BFOP_39) Ternary conditional: infix operator ?: { associativity right precedence 100 } //MARK: -- Assignment //X (BFOP_40) Assign: infix operator = { associativity right precedence 90 } //- (BFOP_41) Multiply and assign: infix operator *= { associativity right precedence 90 } //- (BFOP_42) Divide and assign: infix operator /= { associativity right precedence 90 } //- (BFOP_43) Remainder and assign: infix operator %= { associativity right precedence 90 } //- (BFOP_44) Add and assign: infix operator += { associativity right precedence 90 } //- (BFOP_45) Substract and assign: infix operator -= { associativity right precedence 90 } //- (BFOP_46) Power and assign: infix operator **= { associativity right precedence 90 } //- (BFOP_47) Left bit shift and assign: infix operator <<= { associativity right precedence 90 } //- (BFOP_48) Right bit shift and assign: infix operator >>= { associativity right precedence 90 } //- (BFOP_49) Bitwise AND and assign: infix operator &= { associativity right precedence 90 } //- (BFOP_50) Bitwise XOR and assign: infix operator ^= { associativity right precedence 90 } //- (BFOP_51) Bitwise OR and assign: infix operator |= { associativity right precedence 90 } //- (BFOP_52) Logical AND and assign: infix operator &&= { associativity right precedence 90 } //- (BFOP_53) Logical OR and assign: infix operator ||= { associativity right precedence 90 } //MARK: - Postfix operators //- (BFOP_54) Increment: postfix operator ++ //- (BFOP_55) Decrement: postfix operator --
gpl-3.0
626a16681fea5a2251d6f06673ecf21f
46.798611
119
0.689815
3.974018
false
false
false
false
csontosgabor/Twitter_Post
Twitter_Post/GooglePlacesSearchController.swift
1
20092
// // GooglePlacesAutocomplete.swift // GooglePlacesAutocomplete // // Created by Howard Wilson on 10/02/2015. // Copyright (c) 2015 Howard Wilson. All rights reserved. // // // Created by Dmitry Shmidt on 6/28/15. // Copyright (c) 2015 Dmitry Shmidt. All rights reserved. import UIKit import CoreLocation public enum PlaceType: CustomStringConvertible { case all case geocode case address case establishment case regions case cities public var description : String { switch self { case .all: return "" case .geocode: return "geocode" case .address: return "address" case .establishment: return "establishment" case .regions: return "(regions)" case .cities: return "(cities)" } } } public typealias GooglePlaceSelectedClosure = (_ place: PlaceDetails) -> Void open class Place: NSObject { open let id: String open let desc: String? open let name: String? open var apiKey: String? override open var description: String { get { return desc! } } public init(id: String, terms: [String]?) { self.id = id if let terms = terms{ self.name = terms.first var tmpTerms = terms if terms.count > 0{ tmpTerms.remove(at: 0) self.desc = tmpTerms.joined(separator: ",") }else{ self.desc = "" } }else{ self.name = "" self.desc = "" } } convenience public init(prediction: [String: AnyObject], apiKey: String?) { var terms = [String]() if let items = prediction["terms"] as? [[String: AnyObject]]{ for item in items{ if let value = item["value"] as? String{ terms.append(value) } } } self.init( id: prediction["place_id"] as! String, terms: terms ) self.apiKey = apiKey } /** Call Google Place Details API to get detailed information for this place Requires that Place#apiKey be set :param: result Callback on successful completion with detailed place information */ open func getDetails(_ result: @escaping (PlaceDetails) -> ()) { GooglePlaceDetailsRequest(place: self).request(result) } } open class PlaceDetails: CustomStringConvertible { open let name: String open let formattedAddress: String open let formattedPhoneNo: String? open let coordinate: CLLocationCoordinate2D open var streetNumber = "" open var route = "" open var locality = "" open var subLocality = "" open var administrativeArea = "" open var administrativeAreaCode = "" open var subAdministrativeArea = "" open var postalCode = "" open var country = "" open var ISOcountryCode = "" open var state = "" let raw: [String: AnyObject] init(json: [String: AnyObject]) { func component(_ component: String, inArray array: [[String: AnyObject]], ofType: String) -> String{ for item in array { let types = item["types"] as! [String] if let type = types.first{ if type == component { if let value = item[ofType] as! String?{ return value } } } } return "" } let result = json["result"] as! [String: AnyObject] name = result["name"] as! String formattedAddress = result["formatted_address"] as! String formattedPhoneNo = result["formatted_phone_number"] as? String let geometry = result["geometry"] as! [String: AnyObject] let location = geometry["location"] as! [String: AnyObject] let latitude = location["lat"] as! CLLocationDegrees let longitude = location["lng"] as! CLLocationDegrees coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) // let addressComponents = result["address_components"] as! [[String: AnyObject]] // // streetNumber = component("street_number", inArray: addressComponents, ofType: "short_name") // route = component("route", inArray: addressComponents, ofType: "short_name") // subLocality = component("subLocality", inArray: addressComponents, ofType: "long_name") // locality = component("locality", inArray: addressComponents, ofType: "long_name") // postalCode = component("postal_code", inArray: addressComponents, ofType: "long_name") // administrativeArea = component("administrative_area_level_1", inArray: addressComponents, ofType: "long_name") // subAdministrativeArea = component("administrative_area_level_2", inArray: addressComponents, ofType: "long_name") // country = component("country", inArray: addressComponents, ofType: "long_name") // ISOcountryCode = component("country", inArray: addressComponents, ofType: "short_name") raw = json } open var description: String { return "\nPlace: \(name).\nAddress: \(formattedAddress).\ncoordinate: (\(coordinate.latitude), \(coordinate.longitude))\nPhone No.: \(formattedPhoneNo)\n" } } // MARK: - GooglePlacesAutocomplete open class GooglePlacesSearchController: UISearchController, UISearchBarDelegate { var gpaViewController: GooglePlacesAutocompleteContainer! fileprivate var googleSearchBar: UISearchBar? convenience public init(apiKey: String, placeType: PlaceType = .all, searchBar: UISearchBar? = nil, coordinate: CLLocationCoordinate2D = kCLLocationCoordinate2DInvalid, radius: CLLocationDistance = 0) { assert(!apiKey.isEmpty, apiKey) let gpaViewController = GooglePlacesAutocompleteContainer( apiKey: apiKey, placeType: placeType, coordinate: coordinate, radius: radius ) self.init(searchResultsController: gpaViewController) self.googleSearchBar = searchBar self.gpaViewController = gpaViewController self.view.backgroundColor = .white self.searchResultsUpdater = gpaViewController self.hidesNavigationBarDuringPresentation = false // self.dimsBackgroundDuringPresentation = false self.searchBar.placeholder = "Enter Address" } override open var searchBar: UISearchBar { get { return googleSearchBar ?? super.searchBar } } open func didSelectGooglePlace(_ completion : @escaping GooglePlaceSelectedClosure){ gpaViewController.closure = completion } } // MARK: - GooglePlacesAutocompleteContainer open class GooglePlacesAutocompleteContainer: UITableViewController, UISearchResultsUpdating { var closure: GooglePlaceSelectedClosure? fileprivate var apiKey: String? fileprivate var places = [Place]() fileprivate var placeType: PlaceType = .all fileprivate var coordinate: CLLocationCoordinate2D = kCLLocationCoordinate2DInvalid fileprivate var radius: Double = 0.0 var emptyImgName = "ic_search" var emptyTitle = "Search for places and tag yourself" var emptyDescription = "" weak var googleDelegate: GoogleDelegate? convenience init(apiKey: String, placeType: PlaceType = .all, coordinate: CLLocationCoordinate2D, radius: Double) { self.init() self.apiKey = apiKey self.placeType = placeType self.coordinate = coordinate self.radius = radius } // deinit { // NSNotificationCenter.defaultCenter().removeObserver(self, name: UIContentSizeCategoryDidChangeNotification, object: nil) // } override open func viewDidLoad() { super.viewDidLoad() tableView.register(GooglePlaceTableViewCell.self, forCellReuseIdentifier: "Cell") tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension tableView.emptyDataSetSource = self tableView.emptyDataSetDelegate = self //FIXME: Dynamic fonts updating //Dynamic fonts observer // NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("noteDynamicTypeSettingChanged"), name: UIContentSizeCategoryDidChangeNotification, object: nil) } // func noteDynamicTypeSettingChanged() { // UIContentSizeCategoryDidChangeNotification // tableView.reloadData() // } } // MARK: - GooglePlacesAutocompleteContainer private class GooglePlaceTableViewCell: UITableViewCell { var nameLabel = UILabel() var addressLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: .default, reuseIdentifier: reuseIdentifier) self.selectionStyle = UITableViewCellSelectionStyle.gray nameLabel.translatesAutoresizingMaskIntoConstraints = false addressLabel.translatesAutoresizingMaskIntoConstraints = false nameLabel.textColor = UIColor.black nameLabel.backgroundColor = UIColor.white nameLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline) addressLabel.textColor = UIColor(hue: 0.9972, saturation: 0, brightness: 0.54, alpha: 1.0) addressLabel.backgroundColor = UIColor.white addressLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.footnote) addressLabel.numberOfLines = 0 contentView.addSubview(nameLabel) contentView.addSubview(addressLabel) let viewsDict = [ "name" : nameLabel, "address" : addressLabel ] contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[name]-[address]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict)) contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[name]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict)) contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[address]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict)) } required init?(coder: NSCoder) { super.init(coder: coder) } } extension GooglePlacesAutocompleteContainer{ override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return places.count } override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! GooglePlaceTableViewCell // Get the corresponding candy from our candies array let place = self.places[(indexPath as NSIndexPath).row] // Configure the cell cell.nameLabel.text = place.name cell.addressLabel.text = place.description cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator return cell } override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let place = places[(indexPath as NSIndexPath).row] self.dismiss(animated: false , completion: { self.googleDelegate?.addPlace(place.name) }) // place.getDetails {[unowned self] details in // // self.closure?(details) // // } } } // MARK: - GooglePlacesAutocompleteContainer (UISearchBarDelegate) extension GooglePlacesAutocompleteContainer: UISearchBarDelegate { public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.characters.count > 0 { self.places = [] } else { getPlaces(searchText) } } fileprivate func escape(_ string: String) -> String { // let legalURLCharactersToBeEscaped: CFStringRef = ":/?&=;+!@#$()',*" // return (string as NSString).stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! return (string as NSString).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! // return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String } /** Call the Google Places API and update the view with results. :param: searchString The search query */ fileprivate func getPlaces(_ searchString: String) { var params = [ "input": escape(searchString), "types": placeType.description, "key": apiKey ?? "" ] if CLLocationCoordinate2DIsValid(self.coordinate) { params["location"] = "\(coordinate.latitude),\(coordinate.longitude)" if radius > 0{ params["radius"] = "\(radius)" } } GooglePlacesRequestHelpers.doRequest( "https://maps.googleapis.com/maps/api/place/autocomplete/json", params: params ) { json in if let predictions = json["predictions"] as? Array<[String: Any]> { self.places = predictions.map { (prediction: [String: Any]) -> Place in return Place(prediction: prediction as [String : AnyObject], apiKey: self.apiKey) } } if let predictions = json["predictions"] as? [[String: AnyObject]] { self.places = predictions.map { (prediction: [String: AnyObject]) -> Place in return Place(prediction: prediction, apiKey: self.apiKey) } self.tableView.reloadData() } } } } extension GooglePlacesAutocompleteContainer { @objc(updateSearchResultsForSearchController:) public func updateSearchResults(for searchController: UISearchController) { if let searchText = searchController.searchBar.text , searchText.characters.count > 0 { getPlaces(searchText) } else { self.places = [] } } } // MARK: - GooglePlaceDetailsRequest class GooglePlaceDetailsRequest { let place: Place init(place: Place) { self.place = place } func request(_ result: @escaping (PlaceDetails) -> ()) { GooglePlacesRequestHelpers.doRequest( "https://maps.googleapis.com/maps/api/place/details/json", params: [ "placeid": place.id, "key": place.apiKey ?? "" ] ) { json in result(PlaceDetails(json: json as! [String: AnyObject])) } } } // MARK: - GooglePlacesRequestHelpers class GooglePlacesRequestHelpers { /** Build a query string from a dictionary :param: parameters Dictionary of query string parameters :returns: The properly escaped query string */ fileprivate class func query(_ parameters: [String: String]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sorted() { let value: String! = parameters[key] components += [(key, "\(value!)")] } return components.map{"\($0)=\($1)"}.joined(separator: "&") } fileprivate class func doRequest(_ urlString: String, params: [String: String], success: @escaping (NSDictionary) -> ()) { let urlString = "\(urlString)?\(query(params as [String : String]))" if let url = URL(string: urlString){ let request = URLRequest(url: url) let config = URLSessionConfiguration.default let session = URLSession(configuration: config) let task = session.dataTask(with: request, completionHandler: { (data, response, error) in do { if let data = data, let _ = try? JSONSerialization.jsonObject(with: data, options: [] ) as? [String: Any] { } } self.handleResponse(data, response: response, error: error as NSError!, success: success) }) task.resume() } } fileprivate class func handleResponse(_ data: Data!, response: URLResponse!, error: NSError!, success: @escaping (NSDictionary) -> ()) { if let error = error { print("GooglePlaces Error: \(error.localizedDescription)") return } if response == nil { print("GooglePlaces Error: No response from API") return } if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode != 200 { print("GooglePlaces Error: Invalid status code \(httpResponse.statusCode) from API") return } } let json: NSDictionary? do { json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary } catch { json = nil print("GooglePlaces Error") return } if let status = json?["status"] as? String { if status != "OK" { print("GooglePlaces API Error: \(status)") return } } // Perform table updates on UI thread DispatchQueue.main.async(execute: { UIApplication.shared.isNetworkActivityIndicatorVisible = false success(json!) }) } } extension GooglePlacesAutocompleteContainer: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate { public func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool { return true } public func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! { return UIImage(named: emptyImgName) } public func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { let attribs = [ NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18), NSForegroundColorAttributeName: UIColor.darkGray ] return NSAttributedString(string: emptyTitle, attributes: attribs) } // public func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { // // // let para = NSMutableParagraphStyle() // para.lineBreakMode = NSLineBreakMode.byWordWrapping // para.alignment = NSTextAlignment.center // // let attribs = [ // NSFontAttributeName: UIFont.systemFont(ofSize: 14), // NSForegroundColorAttributeName: UIColor.lightGray, // NSParagraphStyleAttributeName: para // ] // // return NSAttributedString(string: emptyDescription, attributes: attribs) // } } protocol GoogleDelegate: class { func addPlace(_ place: String?) }
mit
f586718d6cbb90dc46bf52ec2b7ab477
33.345299
206
0.598845
5.431738
false
false
false
false
huangboju/AsyncDisplay_Study
AsyncDisplay/Controllers/ASDKLayoutTransition.swift
1
5295
// // ASDKLayoutTransition.swift // AsyncDisplay // // Created by 伯驹 黄 on 2017/4/20. // Copyright © 2017年 伯驹 黄. All rights reserved. // import AsyncDisplayKit class TransitionNode: ASDisplayNode { var isEnabled = false var buttonNode: ASButtonNode! var textNodeOne: ASTextNode! var textNodeTwo: ASTextNode! override init() { super.init() defaultLayoutTransitionDuration = 1 textNodeOne = ASTextNode() textNodeOne.attributedText = NSAttributedString(string: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled") textNodeTwo = ASTextNode() textNodeTwo.attributedText = NSAttributedString(string: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English.") // Setup button let buttonTitle = "Start Layout Transition" let buttonFont = UIFont.systemFont(ofSize:16.0) let buttonColor = UIColor.blue buttonNode = ASButtonNode() buttonNode.setTitle(buttonTitle, with: buttonFont, with: buttonColor, for: .normal) buttonNode.setTitle(buttonTitle, with: buttonFont, with: buttonColor.withAlphaComponent(0.5), for: .highlighted) addSubnode(buttonNode) // Some debug colors textNodeOne.backgroundColor = UIColor.orange textNodeTwo.backgroundColor = UIColor.green // 自动管理node automaticallyManagesSubnodes = true } override func didLoad() { super.didLoad() buttonNode.addTarget(self, action: #selector(buttonPressed), forControlEvents: .touchUpInside) } // MARK: - Actions @objc func buttonPressed() { isEnabled = !isEnabled transitionLayout(withAnimation: true, shouldMeasureAsync: false, measurementCompletion: nil) } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { let nextTextNode = isEnabled ? textNodeTwo : textNodeOne nextTextNode!.style.flexGrow = 1.0 nextTextNode!.style.flexShrink = 1.0 // 搞不懂为什么要包一层 let horizontalStackLayout = ASStackLayoutSpec.horizontal() horizontalStackLayout.children = [nextTextNode!] buttonNode.style.alignSelf = .center let verticalStackLayout = ASStackLayoutSpec.vertical() verticalStackLayout.spacing = 10.0 verticalStackLayout.children = [horizontalStackLayout, buttonNode] return ASInsetLayoutSpec(insets: UIEdgeInsets.init(top: 15.0, left: 15.0, bottom: 15.0, right: 15.0), child: verticalStackLayout) } override func animateLayoutTransition(_ context: ASContextTransitioning) { let fromNode = context.removedSubnodes()[0] let toNode = context.insertedSubnodes()[0] var tempbuttonNode: ASButtonNode? for node in context.subnodes(forKey: ASTransitionContextToLayoutKey) { if let node = node as? ASButtonNode { tempbuttonNode = node break } } var toNodeFrame = context.finalFrame(for: toNode) let width = isEnabled ? toNodeFrame.width : -toNodeFrame.width toNodeFrame.origin.x += width toNode.frame = toNodeFrame toNode.alpha = 0.0 var fromNodeFrame = fromNode.frame let width1 = isEnabled ? -fromNodeFrame.width : fromNodeFrame.width fromNodeFrame.origin.x += width1 // We will use the same transition duration as the default transition UIView.animate(withDuration: defaultLayoutTransitionDuration, animations: { toNode.alpha = 1.0 fromNode.alpha = 0.0 // Update frame of self let fromSize = context.layout(forKey: ASTransitionContextFromLayoutKey)!.size let toSize = context.layout(forKey: ASTransitionContextToLayoutKey)!.size let isResized = fromSize != toSize if isResized { self.frame.size = toSize } tempbuttonNode?.frame = context.finalFrame(for: tempbuttonNode!) }, completion: { context.completeTransition($0) }) } } class ASDKLayoutTransition: UIViewController { var transitionNode = TransitionNode() override func viewDidLoad() { super.viewDidLoad() view.addSubnode(transitionNode) transitionNode.backgroundColor = UIColor.gray } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let size = transitionNode.layoutThatFits(ASSizeRange(min: .zero, max: view.frame.size)).size transitionNode.frame = CGRect(x: 0, y: 100, width: size.width, height: size.height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
c1eed289dbbf088e150eddfb7cb15c9c
34.486486
372
0.666794
4.899254
false
false
false
false
hodinkee/iris
Iris/NSColor.swift
1
666
// // NSColor.swift // Iris // // Created by Caleb Davenport on 1/10/17. // Copyright © 2017 HODINKEE. All rights reserved. // #if os(macOS) public typealias Color = NSColor extension NSColor { @nonobjc var hexadecimalColorString: String? { guard let color = usingColorSpace(.sRGB) else { return nil } var a: CGFloat = 0 var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 color.getRed(&r, green: &g, blue: &b, alpha: &a) return String(format: "%02X%02X%02X%02X", ((Int)(a * 255)), ((Int)(r * 255)), ((Int)(g * 255)), ((Int)(b * 255))) } } #endif // os(macOS)
mit
2818269282644fc90b60fbce2607a98e
19.78125
121
0.550376
3.228155
false
false
false
false
ilyathewhite/Euler
EulerSketch/EulerSketch/Figure.swift
1
11316
// // Figure.swift // Euler // // Created by Ilya Belenkiy on 7/1/15. // Copyright © 2015 Ilya Belenkiy. All rights reserved. // /// The top level scripting APIs refer to figures by name, using geometry naming conventions. /// The figure name prefix ensures that these names are unique in the figure lookup dictionary. public enum FigureNamePrefix: String { case point = "point_" case segment = "segment_" case line = "line_" case ray = "ray_" case angle = "angle_" case circle = "circle_" case triangle = "triangle_" /// the prefix for a point where the figure drawing stops even though the drawing could be extended. /// For example, a ray needs one handle to tell where the ray drawing should stop. Handles /// help create line and ray drawings of the right length. case Handle = "handle_" /// the prefix for a figure that is part of another figure. For example, there are 2 ray parts in an angle. case Part = "part_" case None = "" /// Returns the full name from the geometric name. For example, triangle_ABC. func fullName(_ name: String) -> String { return rawValue + name } /// Returns the kind of figure for the name prefix. var figureKind: FigureKind? { switch self { case .point: return .point case .segment: return .segment case .line: return .line case .ray: return .ray case .angle: return .angle case .circle: return .circle case .triangle: return .triangle default: return nil } } /// The separator between the name prefix and the rest of the name. The separator is part of the prefix. static let lastChar: Character = "_" var nameWithoutLastChar: String { let str = rawValue let lastIdx = str.index(str.endIndex, offsetBy: -1) return String(str[..<lastIdx]) } } // The types of figures supported by Euler. public enum FigureKind: String { case point case segment case line case ray case angle case circle case triangle case vector /// Returns the name prefix for the kind of figure. var figureNamePrefix: FigureNamePrefix { switch self { case .point: return .point case .segment: return .segment case .line: return .line case .ray: return .ray case .angle: return .angle case .circle: return .circle case .triangle: return .triangle default: return .None } } /// Returns the full name from the given short name. func fullName(_ name: String) -> String { return figureNamePrefix.fullName(name) } } /// The type of function that updates a figure while dragging from `point` by `vector`. /// The point can be `nil` when the drag propagates to another figure due to dependencies. typealias DragUpdateFunc = (_ from: Point?, _ by: Vector) -> () /// The protocol that describes how to draw a figure. protocol Drawable: class { /// Whether the figure is hidden. var hidden: Bool { get set } /// The drawing style (for example, this may affect line thickness or color). var drawingStyle: DrawingStyle? { get set } /// Draws the figure via `renderer` by decomposing the drawing into primitives /// that `renderer` can draw directly. func draw(_ renderer: Renderer) } /// The protocol for dragging. protocol Draggable: class { /// The drag update function. `nil` if the figure is not draggable var dragUpdateFunc: DragUpdateFunc? { get set } /// Applies the drag update function. The implementation may need to do more than /// simply calling `dragUpdateFunc`. It also has to ensure that the function is not called /// more than onace per update (this could happen if dragging means updating other figures /// as well. func applyUpdateFunc(from point: Point?, by: Vector) } extension Draggable { /// Whether the specific instance of `Draggable` can be dragged. For example, points are /// draggable, but if a point is an intersection of 2 figures, it may not be draggable. var draggable: Bool { return dragUpdateFunc != nil } } /// The protocol for evaluating figures. The protocol assumes that the evaluation is expensive and /// allows to skip the computation if it's not neccesary. It also assumes that the evaluation may /// fail and provides an API to roll back to an earlier good state. protocol Evaluable: class { /// Whether the evaluation is necessary. var needsEval: Bool { get set } /// Evaluate the figure. func eval() /// Commit the result of evaluation. func commit() /// Rollback to the state before the last evaluation. func rollback() } /// The protocol that describes a figure. A figure must be a class because /// figures form a dependency graph, and many figures may need to reference /// the same figure and react to changes in that figure. protocol FigureType: Shape, Drawable, Draggable, Evaluable { /// The sketch that owns the figure. var sketch: Sketch? { get set } /// Adds `figure` as a dependent figure. This means that any changes in /// this figure trigger reevaluation of `figure`. func addDependentFigure(_ figure: FigureType) /// Removes `figure` as a dependent figure. This is necessary when deleting `figure`. func removeDependentFigure(_ figure: FigureType) /// The geometric name (for example `ABC` for a triangle). var name: String { get } /// The unique geometric name (for example, triangle_ABC). var fullNamePrefix: FigureNamePrefix { get } /// The message printed at the end of dragging the figure. This can be useful /// to show updated information about the figure, for example a new angle or radius. var dragEndMessage: String { get } } extension FigureType { /// A name that uniquely identifies a figure. Used for figure lookup table. var fullName: String { return fullNamePrefix.fullName(name) } /// A short figure summary. Useful for playgrounds and quick look. var summaryName: String { return fullNamePrefix.nameWithoutLastChar + " \(name)" } } /// A box to work around a SWift compiler error. The compiler accepts an array of /// different types of `FigureType` implementations as an array of `FigureType` objects, /// but accessing the array creates a crash at runtime. struct FigureSet { fileprivate var figures: [FigureType] = [] /// Adds `figure` to the set. mutating func add(_ figure: FigureType) { figures.append(figure) } /// Removes `figure` from the set. mutating func remove(_ figure: FigureType) { guard let index = figures.firstIndex(where: { $0 === figure }) else { return } figures.remove(at: index) } /// Returns an array of all figures in the set. var all: [FigureType] { return figures } init() {} init(_ figure: FigureType) { self.figures = [figure] } init(_ figures: [FigureType]) { self.figures = figures } init<T: FigureType>(_ figures: [T]) { self.figures = figures.map { $0 as FigureType } } } /// Describes the possible update states to ensure that a figure is /// updated exactly once. private enum FigureUpdateState { case ready, started, done } // The generic implementation of `FigureType` based on its shape. class Figure<F: Shape>: FigureType { weak var sketch: Sketch? var name: String var fullNamePrefix: FigureNamePrefix { return F.namePrefix() } // dependent figures fileprivate var dependentFigures = FigureSet() func addDependentFigure(_ figure: FigureType) { dependentFigures.add(figure) } func removeDependentFigure(_ figure: FigureType) { dependentFigures.remove(figure) } func notifyFigureDidChange() { for figure in dependentFigures.all { figure.needsEval = true } } // drag var dragUpdateFunc: DragUpdateFunc? fileprivate var updateState: FigureUpdateState = .ready func applyUpdateFunc(from point: Point?, by vector: Vector) { guard let dragUpdateFunc = dragUpdateFunc, (updateState == .ready) else { return } updateState = .started dragUpdateFunc(point, vector) updateState = .done } fileprivate static func defaultUpdateFunc(_ usedFigures: [FigureType]) -> DragUpdateFunc? { guard usedFigures.count == 1 else { return nil } let usedFigure = usedFigures.first! return { (point, vector) in usedFigure.applyUpdateFunc(from: point, by: vector) } } var dragEndMessage: String { return "finished dragging \(fullName)" } // shape func distanceFromPoint(_ point: Point) -> (Double, Point) { return value.distanceFromPoint(point) } func translateInPlace(by vector: Vector) { value.translateInPlace(by: vector) } func translateToPoint(_ point: Point) { let (_, closestPoint) = distanceFromPoint(point) translateInPlace(by: vector(closestPoint, point)) } // eval var needsEval = true fileprivate var freeVal = true var value: F! { didSet { self.notifyFigureDidChange() } } fileprivate var savedValue: F! class func namePrefix() -> FigureNamePrefix { return F.namePrefix() } typealias EvalFunc = () -> F? var evalFunc: EvalFunc? { didSet { needsEval = true } } var free: Bool { return freeVal && (evalFunc == nil) } func eval() { updateState = .ready if (!needsEval) { return } needsEval = false if let f = evalFunc { if let newValue = f() { value = newValue } else { sketch?.setNeedsRollback() } } } func commit() { savedValue = value } func rollback() { value = savedValue } // draw var hidden = false var drawingStyle: DrawingStyle? func draw(_ renderer: Renderer) { guard !hidden else { return } renderer.setStyle(drawingStyle) } // init /// Whether the figure is draggable. var draggable: Bool { return free || (dragUpdateFunc != nil) } /// Constructs a figure with a given name and value. init(name: String, value: F) { self.name = name self.value = value dragUpdateFunc = { [unowned self] (point, vector) in self.translateInPlace(by: vector) } } /// Constructs a figure with a given name from `evalFunc`, and for each figure in `usedFigures`, // adds the new figure as a dependent figure. init(name: String, usedFigures: FigureSet, evalFunc: @escaping EvalFunc) throws { self.name = name freeVal = (usedFigures.all.count == 0) for figure in usedFigures.all { figure.addDependentFigure(self) } let translateFunc: DragUpdateFunc = { [unowned self] (point, vector) in self.translateInPlace(by: vector) } dragUpdateFunc = usedFigures.all.count > 0 ? Figure.defaultUpdateFunc(usedFigures.all) : translateFunc guard let value = evalFunc() else { throw SketchError.figureNotCreated(name: name, kind: F.namePrefix().figureKind!) } self.value = value self.evalFunc = evalFunc } }
mit
453f5250227a3298bf7a9fb9977337f8
29.254011
113
0.653999
4.341903
false
false
false
false
daniel-barros/TV-Calendar
TV Calendar/CalendarActionTableViewCell.swift
1
4764
// // CalendarActionTableViewCell.swift // TV Calendar // // Created by Daniel Barros López on 2/8/17. // Copyright © 2017 Daniel Barros. All rights reserved. // import ExtendedUIKit protocol CalendarActionTableViewCellDelegate: class { func didPressButton(in cell: CalendarActionTableViewCell) } /// A cell containing a button that initiates actions related to the default calendar settings or that affect all shows at once. /// If the action related to the cell is disabled because of the show's settings, the disabled button changes its text and serves as a explanatory message. class CalendarActionTableViewCell: UITableViewCell, Reusable { enum ActionType { case setDefaultSettings, resetToDefaultSettings, disableCalendarEventsForAll, enableCalendarEventsForAll } enum BottomMarginSize { case regular, medium, large } fileprivate enum Constants { static let mediumBottomMargin: CGFloat = 16 static let largeBottomMargin: CGFloat = 28 } @IBOutlet weak var button: UIButton! @IBOutlet weak var separator: UIView! // Custom separator since table view doesn't allow some with and others without it var show: Show? var calendarSettingsManager: CalendarSettingsManager? weak var delegate: CalendarActionTableViewCellDelegate? var type = ActionType.setDefaultSettings var defaultBottomMargin: CGFloat required init?(coder aDecoder: NSCoder) { defaultBottomMargin = 0 super.init(coder: aDecoder) defaultBottomMargin = contentView.layoutMargins.bottom } func configure(with show: Show, type: ActionType, bottomMarginSize: BottomMarginSize = .regular, showsSeparator: Bool = true, settingsManager: CalendarSettingsManager?) { self.show = show self.type = type self.calendarSettingsManager = settingsManager configure() updateBottomMargin(withSize: bottomMarginSize) separator.isHidden = !showsSeparator } /// Like `configure(with:type:bottomMarginSize:showsSeparator)` updates the cell UI but keeping current show and type. That function needs to be called first at some point though so the show, type and margin are properly set. func configure() { updateEnabledState() updateButtonTitle() } @IBAction func buttonPressed(_ sender: UIButton) { delegate?.didPressButton(in: self) } } // MARK: Helpers fileprivate extension CalendarActionTableViewCell { func updateButtonTitle() { switch type { case .setDefaultSettings: if button.isEnabled { button.setTitle("Make These the Default Settings for all Shows", for: .normal) } else { button.setTitle("This show is using the default settings", for: .normal) } case .resetToDefaultSettings: if button.isEnabled { button.setTitle("Reset to Default Settings", for: .normal) } else { button.setTitle("This show is using the default settings", for: .normal) } case .disableCalendarEventsForAll: if button.isEnabled { button.setTitle("Disable Calendar Events for all Shows", for: .normal) } else { button.setTitle("Calendar events are disabled for all shows", for: .normal) } case .enableCalendarEventsForAll: if button.isEnabled { button.setTitle("Enable Calendar Events for all Shows", for: .normal) } else { button.setTitle("All shows have calendar events enabled", for: .normal) } } } func updateBottomMargin(withSize size: BottomMarginSize) { switch size { case .regular: contentView.layoutMargins.bottom = defaultBottomMargin case .medium: contentView.layoutMargins.bottom = Constants.mediumBottomMargin case .large: contentView.layoutMargins.bottom = Constants.largeBottomMargin } } func updateEnabledState() { guard let show = show, let calendarSettingsManager = calendarSettingsManager else { return } // If all default is true and all shows have calendar events enabled, disable the button if (type == .enableCalendarEventsForAll && calendarSettingsManager.isCreateCalendarEventsDefaultAndEnabledForAllShows) || (type == .setDefaultSettings && calendarSettingsManager.showHasSameSettingsAsDefault(show)) || (type == .resetToDefaultSettings && calendarSettingsManager.showHasDefaultSettings(show)) { button.isEnabled = false } else { button.isEnabled = true } } }
gpl-3.0
e8fe9a47d8da4a842063a2fe5461a204
39.016807
229
0.673877
5.380791
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/API/Requests/Message/GetMessageRequest.swift
1
857
// // GetMessageRequest.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 10/04/19. // Copyright © 2019 Rocket.Chat. All rights reserved. // import Foundation import SwiftyJSON final class GetMessageRequest: APIRequest { typealias APIResourceType = GetMessageResource let requiredVersion = Version(0, 47, 0) let method: HTTPMethod = .get let path = "/api/v1/chat.getMessage" var query: String? init(msgId: String) { self.query = "msgId=\(msgId)" } } final class GetMessageResource: APIResource { var message: Message? { if let object = raw?["message"] { let message = Message() message.map(object, realm: nil) return message } return nil } var success: Bool { return raw?["success"].boolValue ?? false } }
mit
da352788104acd21ed552083cf5ccec1
19.380952
54
0.620327
4.07619
false
false
false
false
waltflanagan/AdventOfCode
2017/AdventOfCode.playground/Pages/2018 Day 6.xcplaygroundpage/Contents.swift
1
2300
//: [Previous](@previous) import Foundation let fakeInput = [[1, 1], [1, 6], [8, 3], [3, 4], [5, 5], [8, 9]] let realInput = [[81, 252], [67, 186], [206, 89], [97, 126], [251, 337], [93, 101], [193, 113], [101, 249], [276, 304], [127, 140], [289, 189], [289, 264], [79, 66], [178, 248], [91, 231], [75, 157], [260, 221], [327, 312], [312, 141], [112, 235], [97, 354], [50, 200], [192, 303], [108, 127], [281, 359], [128, 209], [50, 306], [67, 314], [358, 270], [87, 122], [311, 83], [166, 192], [170, 307], [322, 320], [352, 265], [167, 342], [296, 145], [231, 263], [340, 344], [134, 132], [72, 281], [135, 352], [140, 119], [58, 325], [247, 123], [256, 346], [330, 356], [281, 177], [216, 145], [278, 98]] let input = realInput let coordinates = input.map { Point(x: $0.first!, y: $0.last!) } //let areas = areasOf(coordinates) // //let sorted = areas.sorted { (left, right) -> Bool in // return left.value < right.value //} //print("\(sorted.map({ $0.value }))") let region = safeRegion(coordinates) //let closestCoordinate = coordinates.reduce(Point(x: 1000000, y: 1000000)) { (currentPoint, testPoint) -> Point in // return testPoint.distanceTo(smallestPoint) < currentPoint.distanceTo(smallestPoint) ? testPoint : currentPoint //} region //: [Next](@next)
mit
55b5af86351050e382e3bc6745fd9a0a
25.136364
116
0.320435
4.40613
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/NaturalLanguageUnderstandingV1/Models/EntitiesOptions.swift
1
2426
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** Whether or not to return important people, places, geopolitical, and other entities detected in the analyzed content. */ public struct EntitiesOptions: Encodable { /// Maximum number of entities to return. public var limit: Int? /// Set this to true to return locations of entity mentions. public var mentions: Bool? /// Enter a custom model ID to override the standard entity detection model. public var model: String? /// Set this to true to return sentiment information for detected entities. public var sentiment: Bool? /// Set this to true to analyze emotion for detected keywords. public var emotion: Bool? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case limit = "limit" case mentions = "mentions" case model = "model" case sentiment = "sentiment" case emotion = "emotion" } /** Initialize a `EntitiesOptions` with member variables. - parameter limit: Maximum number of entities to return. - parameter mentions: Set this to true to return locations of entity mentions. - parameter model: Enter a custom model ID to override the standard entity detection model. - parameter sentiment: Set this to true to return sentiment information for detected entities. - parameter emotion: Set this to true to analyze emotion for detected keywords. - returns: An initialized `EntitiesOptions`. */ public init(limit: Int? = nil, mentions: Bool? = nil, model: String? = nil, sentiment: Bool? = nil, emotion: Bool? = nil) { self.limit = limit self.mentions = mentions self.model = model self.sentiment = sentiment self.emotion = emotion } }
mit
21c6599ab25b970a0b1e1dd42c7b6eae
36.323077
127
0.698269
4.64751
false
false
false
false
danielgindi/ios-charts
ChartsDemo-iOS/Swift/Demos/LineChart2ViewController.swift
2
7618
// // LineChart2ViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // #if canImport(UIKit) import UIKit #endif import Charts class LineChart2ViewController: DemoBaseViewController { @IBOutlet var chartView: LineChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Line Chart 2" self.options = [.toggleValues, .toggleFilled, .toggleCircles, .toggleCubic, .toggleHorizontalCubic, .toggleStepped, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleAutoScaleMinMax, .toggleData] chartView.delegate = self chartView.chartDescription.enabled = false chartView.dragEnabled = true chartView.setScaleEnabled(true) chartView.pinchZoomEnabled = true let l = chartView.legend l.form = .line l.font = UIFont(name: "HelveticaNeue-Light", size: 11)! l.textColor = .white l.horizontalAlignment = .left l.verticalAlignment = .bottom l.orientation = .horizontal l.drawInside = false let xAxis = chartView.xAxis xAxis.labelFont = .systemFont(ofSize: 11) xAxis.labelTextColor = .white xAxis.drawAxisLineEnabled = false let leftAxis = chartView.leftAxis leftAxis.labelTextColor = UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1) leftAxis.axisMaximum = 200 leftAxis.axisMinimum = 0 leftAxis.drawGridLinesEnabled = true leftAxis.granularityEnabled = true let rightAxis = chartView.rightAxis rightAxis.labelTextColor = .red rightAxis.axisMaximum = 900 rightAxis.axisMinimum = -200 rightAxis.granularityEnabled = false sliderX.value = 20 sliderY.value = 30 slidersValueChanged(nil) chartView.animate(xAxisDuration: 2.5) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value + 1), range: UInt32(sliderY.value)) } func setDataCount(_ count: Int, range: UInt32) { let yVals1 = (0..<count).map { (i) -> ChartDataEntry in let mult = range / 2 let val = Double(arc4random_uniform(mult) + 50) return ChartDataEntry(x: Double(i), y: val) } let yVals2 = (0..<count).map { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 450) return ChartDataEntry(x: Double(i), y: val) } let yVals3 = (0..<count).map { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 500) return ChartDataEntry(x: Double(i), y: val) } let set1 = LineChartDataSet(entries: yVals1, label: "DataSet 1") set1.axisDependency = .left set1.setColor(UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1)) set1.setCircleColor(.white) set1.lineWidth = 2 set1.circleRadius = 3 set1.fillAlpha = 65/255 set1.fillColor = UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1) set1.highlightColor = UIColor(red: 244/255, green: 117/255, blue: 117/255, alpha: 1) set1.drawCircleHoleEnabled = false let set2 = LineChartDataSet(entries: yVals2, label: "DataSet 2") set2.axisDependency = .right set2.setColor(.red) set2.setCircleColor(.white) set2.lineWidth = 2 set2.circleRadius = 3 set2.fillAlpha = 65/255 set2.fillColor = .red set2.highlightColor = UIColor(red: 244/255, green: 117/255, blue: 117/255, alpha: 1) set2.drawCircleHoleEnabled = false let set3 = LineChartDataSet(entries: yVals3, label: "DataSet 3") set3.axisDependency = .right set3.setColor(.yellow) set3.setCircleColor(.white) set3.lineWidth = 2 set3.circleRadius = 3 set3.fillAlpha = 65/255 set3.fillColor = UIColor.yellow.withAlphaComponent(200/255) set3.highlightColor = UIColor(red: 244/255, green: 117/255, blue: 117/255, alpha: 1) set3.drawCircleHoleEnabled = false let data: LineChartData = [set1, set2, set3] data.setValueTextColor(.white) data.setValueFont(.systemFont(ofSize: 9)) chartView.data = data } override func optionTapped(_ option: Option) { guard let data = chartView.data else { return } switch option { case .toggleFilled: for case let set as LineChartDataSet in data { set.drawFilledEnabled = !set.drawFilledEnabled } chartView.setNeedsDisplay() case .toggleCircles: for case let set as LineChartDataSet in data { set.drawCirclesEnabled = !set.drawCirclesEnabled } chartView.setNeedsDisplay() case .toggleCubic: for case let set as LineChartDataSet in data { set.mode = (set.mode == .cubicBezier) ? .linear : .cubicBezier } chartView.setNeedsDisplay() case .toggleStepped: for case let set as LineChartDataSet in data { set.mode = (set.mode == .stepped) ? .linear : .stepped } chartView.setNeedsDisplay() case .toggleHorizontalCubic: for case let set as LineChartDataSet in data { set.mode = (set.mode == .cubicBezier) ? .horizontalBezier : .cubicBezier } chartView.setNeedsDisplay() default: super.handleOption(option, forChartView: chartView) } } @IBAction func slidersValueChanged(_ sender: Any?) { sliderTextX.text = "\(Int(sliderX.value))" sliderTextY.text = "\(Int(sliderY.value))" self.updateChartData() } //} // TODO: Declarations in extensions cannot override yet. //extension LineChart2ViewController { override func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) { super.chartValueSelected(chartView, entry: entry, highlight: highlight) self.chartView.centerViewToAnimated(xValue: entry.x, yValue: entry.y, axis: self.chartView.data![highlight.dataSetIndex].axisDependency, duration: 1) //[_chartView moveViewToAnimatedWithXValue:entry.x yValue:entry.y axis:[_chartView.data getDataSetByIndex:dataSetIndex].axisDependency duration:1.0]; //[_chartView zoomAndCenterViewAnimatedWithScaleX:1.8 scaleY:1.8 xValue:entry.x yValue:entry.y axis:[_chartView.data getDataSetByIndex:dataSetIndex].axisDependency duration:1.0]; } }
apache-2.0
bf1d98aed7eddc3b34e3332ab8946744
36.338235
186
0.583957
4.808712
false
false
false
false
jcfausto/transit-app
TransitApp/TransitAppTests/RouteSpecs.swift
1
4116
// // RouteSpecs.swift // TransitApp // // Created by Julio Cesar Fausto on 24/02/16. // Copyright © 2016 Julio Cesar Fausto. All rights reserved. // import Quick import Nimble @testable import TransitApp class RouteSpecs: QuickSpec { //MARK: Support routines func createSegmentOne() -> Segment { let stopOne = Stop(name: "", latitude: 52.530227, longitude: 52.530227, time: NSDate(datetimeString: "2015-04-17T13:30:00+02:00")) let stopTwo = Stop(name: "U Rosa-Luxemburg-Platz", latitude: 52.528187, longitude: 13.410404, time: NSDate(datetimeString: "2015-04-17T13:38:00+02:00")) let stops = [stopOne, stopTwo] let travelMode = "Walking" //Used an extension here let color = UIColor(hexString: "#b1ecc") let iconUrl = "https://d3m2tfu2xpiope.cloudfront.net/vehicles/walking.svg" let polyline = "uvr_I{yxpABuAFcAp@yHvAwNr@iGPwAh@a@jAg@" return Segment(name: "", numStops: 0, description: "", stops: stops, travelMode: travelMode, color: color, iconUrl: iconUrl, polyline: polyline) } func createSegmentTwo() -> Segment { let stopOne = Stop(name: "U Rosa-Luxemburg-Platz", latitude: 52.528187, longitude: 13.410404, time: NSDate(datetimeString: "2015-04-17T13:38:00+02:00")) let stopTwo = Stop(name: "S+U Alexanderplatz", latitude: 52.522074, longitude: 13.413595, time: NSDate(datetimeString: "2015-04-17T13:40:00+02:00")) let stops = [stopOne, stopTwo] let travelMode = "Subway" //Used an extension here let color = UIColor(hexString: "#d64820") let iconUrl = "https://d3m2tfu2xpiope.cloudfront.net/vehicles/subway.svg" let polyline = "elr_I_fzpAfe@_Sf]dFr_@~UjCbg@yKvj@lFfb@`C|c@hNjc@" return Segment(name: "U2", numStops: 2, description: "S+U Potsdamer Platz", stops: stops, travelMode: travelMode, color: color, iconUrl: iconUrl, polyline: polyline) } //MARK: Testing routines override func spec() { describe("Route"){ var route: Route! beforeEach { let type = "public_transport" let provider = "vbb" let segmentOne = self.createSegmentOne() let segmentTwo = self.createSegmentTwo() let segments = [segmentOne, segmentTwo] let price = Price(amount: 0.0, currency: "EUR") route = Route(type: type, provider: provider, segments: segments, price: price) } it("has a type"){ expect(route.type).to(equal("public_transport")) } it("has a provider"){ expect(route.provider).to(equal("vbb")) } it("has two segments"){ expect(route.segments.count).to(equal(2)) } it("has a price"){ expect(route.price!.amount).to(equal(0.0)) } it("has a duration"){ let start = NSDate(datetimeString: "2015-04-17T13:30:00+02:00") let finish = NSDate(datetimeString: "2015-04-17T13:40:00+02:00") let expected_duration = finish.timeIntervalSinceDate(start) expect(route.duration).to(equal(expected_duration)) } it("has a timestring representation of starting point"){ expect(route.timeStringRepresentation(.Start)).to(equal("8:30")) } it("has a timestring representation of finishing point"){ expect(route.timeStringRepresentation(.Finish)).to(equal("8:40")) } it("has a summary"){ expect(route.summary).to(equal("EUR: 0.0 | 8:30 -> 8:40")) } } } }
mit
2918ff6cb5c4251ca8018dfb115c1d98
34.782609
173
0.538518
4.034314
false
false
false
false
robertcash/RCActivityIndicator
RCActivityIndicator.swift
1
1892
// // RCActivityIndicator.swift // Meet // // Created by Robert Cash on 8/13/16. // Copyright © 2016 Robert Cash. All rights reserved. // import UIKit class RCActivityIndicator: UIView { static var currentOverlay : UIView? static func show(overlayTarget : UIView) { show(overlayTarget: overlayTarget, loadingText: nil) } static func show(overlayTarget : UIView, loadingText: String?) { // Clear it first in case it was already shown hide() // Create the overlay let overlay = UIView(frame: overlayTarget.frame) overlay.center = overlayTarget.center overlay.alpha = 0 overlay.backgroundColor = UIColor.black overlayTarget.addSubview(overlay) overlayTarget.bringSubview(toFront: overlay) // Create and animate the activity indicator let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white) indicator.center = overlay.center indicator.startAnimating() overlay.addSubview(indicator) // Create label if let textString = loadingText { let label = UILabel() label.text = textString label.textColor = UIColor.white label.sizeToFit() label.center = CGPoint(x: indicator.center.x, y: indicator.center.y + 30) overlay.addSubview(label) } // Animate the overlay to show UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(0.5) overlay.alpha = overlay.alpha > 0 ? 0 : 0.5 UIView.commitAnimations() currentOverlay = overlay } static func hide() { if currentOverlay != nil { currentOverlay?.removeFromSuperview() currentOverlay = nil } } }
mit
312c7959f015624931ae6c9e3e2f2ed5
29.015873
107
0.61449
5.042667
false
false
false
false
kongtomorrow/ProjectEuler-Swift
ProjectEuler/p34.swift
1
884
// // p34.swift // ProjectEuler // // Created by Ken Ferry on 8/11/14. // Copyright (c) 2014 Understudy. All rights reserved. // import Foundation extension Problems { func p34() -> Int { /* 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included. */ // consider adding a digit d to number X to get Xd // Xd == 10*X + d // sum(factorials(digits(Xd))) = sum(factorials(digits(X))) + factorial(d) // so, var sum = 0 for i in 3...3628800 { if i == digits(i).map(factorial).reduce(0,+) { sum += i*** } } return sum // 40730 } }
mit
7b12a798df1496fc92977655ecb7c487
24.285714
96
0.493213
3.63786
false
false
false
false
prebid/prebid-mobile-ios
Example/PrebidDemo/PrebidDemoSwift/Examples/MAX/MAXVideoInterstitialViewController.swift
1
2978
/* Copyright 2019-2022 Prebid.org, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import PrebidMobile import PrebidMobileMAXAdapters import AppLovinSDK fileprivate let storedImpVideoInterstitial = "imp-prebid-video-interstitial-320-480" fileprivate let storedResponseRenderingVideoInterstitial = "response-prebid-video-interstitial-320-480" fileprivate let maxAdUnitVideoInterstitial = "98e49039f26d7f00" class MAXVideoInterstitialViewController: InterstitialBaseViewController, MAAdDelegate { // Prebid private var maxAdUnit: MediationInterstitialAdUnit! private var maxMediationDelegate: MAXMediationInterstitialUtils! // MAX private var maxInterstitial: MAInterstitialAd! override func loadView() { super.loadView() Prebid.shared.storedAuctionResponse = storedResponseRenderingVideoInterstitial createAd() } func createAd() { // 1. Create a MAInterstitialAd maxInterstitial = MAInterstitialAd(adUnitIdentifier: maxAdUnitVideoInterstitial) // 2. Create a MAXMediationInterstitialUtils maxMediationDelegate = MAXMediationInterstitialUtils(interstitialAd: maxInterstitial) // 3. Create a MediationInterstitialAdUnit maxAdUnit = MediationInterstitialAdUnit(configId: storedImpVideoInterstitial, mediationDelegate: maxMediationDelegate) maxAdUnit.adFormats = [.video] // 4. Make a bid request to Prebid Server maxAdUnit.fetchDemand(completion: { [weak self] result in PrebidDemoLogger.shared.info("Prebid demand fetch result \(result.name())") guard let self = self else { return } // 5. Load the interstitial ad self.maxInterstitial.delegate = self self.maxInterstitial.load() }) } // MARK: - MAAdDelegate func didLoad(_ ad: MAAd) { if let maxInterstitial = maxInterstitial, maxInterstitial.isReady { maxInterstitial.show() } } func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) { PrebidDemoLogger.shared.error("\(error.message)") } func didFail(toDisplay ad: MAAd, withError error: MAError) { PrebidDemoLogger.shared.error("\(error.message)") } func didDisplay(_ ad: MAAd) {} func didHide(_ ad: MAAd) {} func didClick(_ ad: MAAd) {} }
apache-2.0
678a5f1152dc672b6d8c721b34afc41a
34.452381
126
0.700134
4.81877
false
false
false
false
qiulang/PeerKit
example/Pods/SwiftyBeaver/sources/ConsoleDestination.swift
2
1441
// // ConsoleDestination.swift // SwiftyBeaver // // Created by Sebastian Kreutzberger on 05.12.15. // Copyright © 2015 Sebastian Kreutzberger // Some rights reserved: http://opensource.org/licenses/MIT // import Foundation public class ConsoleDestination: BaseDestination { public var useNSLog = false override public var defaultHashValue: Int { return 1 } public override init() { super.init() // use colored Emojis for better visual distinction // of log level for Xcode 8 levelColor.verbose = "💜 " // silver levelColor.debug = "💚 " // green levelColor.info = "💙 " // blue levelColor.warning = "💛 " // yellow levelColor.error = "❤️ " // red } // print to Xcode Console. uses full base class functionality override public func send(_ level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int) -> String? { let formattedString = super.send(level, msg: msg, thread: thread, file: file, function: function, line: line) if let str = formattedString { if useNSLog { #if os(Linux) print(str) #else NSLog("%@", str) #endif } else { print(str) } } return formattedString } }
mit
46e931c06c7d7a78ed4ec600f708610b
28.061224
117
0.5625
4.578778
false
false
false
false
wuleijun/Zeus
Zeus/ViewControllers/活动/ClientInviteVC.swift
1
3183
// // ClientInviteVC.swift // Zeus // // Created by 吴蕾君 on 16/5/5. // Copyright © 2016年 rayjuneWu. All rights reserved. // import UIKit class ClientInviteVC: BaseViewController { let clientInviteCellID = "ClientInviteCell" @IBOutlet weak var topView: UIView!{ didSet{ topView.backgroundColor = UIColor.zeusNavigationBarTintColor() } } @IBOutlet weak var tableView: UITableView!{ didSet{ tableView.registerNib(UINib(nibName: clientInviteCellID, bundle: nil), forCellReuseIdentifier: clientInviteCellID) tableView.rowHeight = ClientInviteCell.heightOfCell() } } @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var progressViewHeightConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() hideNavigationBarShadow() progressViewHeightConstraint.constant = ZeusConfig.CommonUI.progressViewHeight // Do any additional setup after loading the view. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) UIView.animateWithDuration(1.0) { self.progressView.progress = 0.5 self.progressView.layoutIfNeeded() } } @IBAction func addClient_Touch(sender: AnyObject) { let chooseClientVC = UIViewController.controllerWith(storyboardName: "ChooseClientVC", viewControllerId: "ChooseClientVC") as! ChooseClientVC navigationController?.pushViewController(chooseClientVC, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } // MARK: TableView DataSource extension ClientInviteVC : UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let clientInviteCell = tableView.dequeueReusableCellWithIdentifier(clientInviteCellID) as! ClientInviteCell return clientInviteCell } } // MARK: TableView Delegate extension ClientInviteVC : UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { defer { tableView.deselectRowAtIndexPath(indexPath, animated: false) } let clientDetailVC = UIViewController.controllerWith(storyboardName: "EditClientVC", viewControllerId: "EditClientVC") as! EditClientVC clientDetailVC.type = ControllerType.ClientInviteStatus navigationController?.pushViewController(clientDetailVC, animated: true) } }
mit
5fe259d2dca928d871787ad22ba88b50
32.410526
149
0.701953
5.281198
false
false
false
false
cailingyun2010/swift-weibo
微博-S/Classes/Home/HomeRefreshControl.swift
1
3639
// // HomeRefreshControl.swift // 微博-S // // Created by nimingM on 16/3/30. // Copyright © 2016年 蔡凌云. All rights reserved. // import UIKit class HomeRefreshControl: UIRefreshControl { override init() { super.init() setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { // 添加子控件 addSubview(refreshView) // 布局子控件 refreshView.xmg_AlignHorizontal(type: XMG_AlignType.Center, referView: self, size: CGSize(width: 170, height: 60)) addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil) } deinit { removeObserver(self, forKeyPath: "frame") } /// 定义变量记录是否需要旋转监听 private var rotationArrowFlag = false /// 定义变量记录当前是否正在执行圈圈动画 private var loadingViewAnimFlag = false override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { // print(frame.origin.y) // 过滤掉不需要的数据 if frame.origin.y >= 0 { return } // 判断是否已经触发刷新事件 if refreshing && !loadingViewAnimFlag { print("圈圈动画") loadingViewAnimFlag = true // 显示圈圈, 并且让圈圈执行动画 refreshView.startAnim() return } if frame.origin.y >= -50 && rotationArrowFlag { print("翻转回来") rotationArrowFlag = false refreshView.rotationArrow(rotationArrowFlag) }else if frame.origin.y < -50 && !rotationArrowFlag { print("翻转") rotationArrowFlag = true refreshView.rotationArrow(rotationArrowFlag) } } override func endRefreshing() { super.endRefreshing() // 结束刷新后关闭动画 refreshView.stopLoadingViewAnim() loadingViewAnimFlag = false } // MARK: - 懒加载 private lazy var refreshView: homeRefreshView = homeRefreshView.refreshView() } class homeRefreshView: UIView { @IBOutlet weak var arrow: UIImageView! @IBOutlet weak var tipView: UIView! @IBOutlet weak var loadingView: UIImageView! class func refreshView() -> homeRefreshView { return NSBundle.mainBundle().loadNibNamed("HomeRefreshControl", owner: nil, options: nil).last as! homeRefreshView } /** 旋转箭头 */ func rotationArrow(flag: Bool) { var angle = M_PI angle += flag ? -0.01 : 0.01 UIView.animateWithDuration(0.2) { () -> Void in self.arrow.transform = CGAffineTransformRotate(self.arrow.transform, CGFloat(angle)) } } /** 开始动画 */ func startAnim() { tipView.hidden = true let anim = CABasicAnimation(keyPath: "transform.rotation") anim.toValue = 2 * M_PI anim.duration = 1 anim.repeatCount = MAXFLOAT // 设置默认属性,执行完毕就移除 anim.removedOnCompletion = false loadingView.layer.addAnimation(anim, forKey: nil) } /** * 停止转圈动画 */ func stopLoadingViewAnim() { tipView.hidden = false loadingView.layer.removeAllAnimations() } }
apache-2.0
af2b4d48d5aeeae97fa8d93e22993a3d
25.367188
157
0.581802
4.578019
false
false
false
false
lvogelzang/Blocky
Blocky/Levels/Level97.swift
1
877
// // Level97.swift // Blocky // // Created by Lodewijck Vogelzang on 07-12-18 // Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved. // import UIKit final class Level97: Level { let levelNumber = 97 var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]] let cameraFollowsBlock = false let blocky: Blocky let enemies: [Enemy] let foods: [Food] init() { blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1)) let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0) let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1) enemies = [enemy0, enemy1] foods = [] } }
mit
aa4f06648a2c7d17caf002adbebbded7
24.794118
89
0.573546
2.649547
false
false
false
false
jacobwhite/firefox-ios
Client/Frontend/Browser/SessionRestoreHelper.swift
3
1216
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit protocol SessionRestoreHelperDelegate: class { func sessionRestoreHelper(_ helper: SessionRestoreHelper, didRestoreSessionForTab tab: Tab) } class SessionRestoreHelper: TabContentScript { weak var delegate: SessionRestoreHelperDelegate? fileprivate weak var tab: Tab? required init(tab: Tab) { self.tab = tab } func scriptMessageHandlerName() -> String? { return "sessionRestoreHelper" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let tab = tab, let params = message.body as? [String: AnyObject] { if params["name"] as! String == "didRestoreSession" { DispatchQueue.main.async { self.delegate?.sessionRestoreHelper(self, didRestoreSessionForTab: tab) } } } } class func name() -> String { return "SessionRestoreHelper" } }
mpl-2.0
a64e85cc961a0bde4a7b5da1b14f2b6d
31.864865
132
0.671875
4.963265
false
false
false
false
shorlander/firefox-ios
SyncTests/MockSyncServer.swift
9
17786
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import GCDWebServers import SwiftyJSON @testable import Sync import XCTest private let log = Logger.syncLogger private func optTimestamp(x: AnyObject?) -> Timestamp? { guard let str = x as? String else { return nil } return decimalSecondsStringToTimestamp(str) } private func optStringArray(x: AnyObject?) -> [String]? { guard let str = x as? String else { return nil } return str.components(separatedBy: ",").map { $0.trimmingCharacters(in:NSCharacterSet.whitespacesAndNewlines) } } private struct SyncRequestSpec { let collection: String let id: String? let ids: [String]? let limit: Int? let offset: String? let sort: SortOption? let newer: Timestamp? let full: Bool static func fromRequest(request: GCDWebServerRequest) -> SyncRequestSpec? { // Input is "/1.5/user/storage/collection", possibly with "/id" at the end. // That means we get five or six path components here, the first being empty. let parts = request.path!.components(separatedBy: "/").filter { !$0.isEmpty } let id: String? let query = request.query as! [String: AnyObject] let ids = optStringArray(x: query["ids"]) let newer = optTimestamp(x: query["newer"]) let full: Bool = query["full"] != nil let limit: Int? if let lim = query["limit"] as? String { limit = Int(lim) } else { limit = nil } let offset = query["offset"] as? String let sort: SortOption? switch query["sort"] as? String ?? "" { case "oldest": sort = SortOption.OldestFirst case "newest": sort = SortOption.NewestFirst case "index": sort = SortOption.Index default: sort = nil } if parts.count < 4 { return nil } if parts[2] != "storage" { return nil } // Use dropFirst, you say! It's buggy. switch parts.count { case 4: id = nil case 5: id = parts[4] default: // Uh oh. return nil } return SyncRequestSpec(collection: parts[3], id: id, ids: ids, limit: limit, offset: offset, sort: sort, newer: newer, full: full) } } struct SyncDeleteRequestSpec { let collection: String? let id: GUID? let ids: [GUID]? let wholeCollection: Bool static func fromRequest(request: GCDWebServerRequest) -> SyncDeleteRequestSpec? { // Input is "/1.5/user{/storage{/collection{/id}}}". // That means we get four, five, or six path components here, the first being empty. return SyncDeleteRequestSpec.fromPath(path: request.path!, withQuery: request.query as! [NSString : AnyObject]) } static func fromPath(path: String, withQuery query: [NSString: AnyObject]) -> SyncDeleteRequestSpec? { let parts = path.components(separatedBy: "/").filter { !$0.isEmpty } let queryIDs: [GUID]? = (query["ids"] as? String)?.components(separatedBy: ",") guard [2, 4, 5].contains(parts.count) else { return nil } if parts.count == 2 { return SyncDeleteRequestSpec(collection: nil, id: nil, ids: queryIDs, wholeCollection: true) } if parts[2] != "storage" { return nil } if parts.count == 4 { let hasIDs = queryIDs != nil return SyncDeleteRequestSpec(collection: parts[3], id: nil, ids: queryIDs, wholeCollection: !hasIDs) } return SyncDeleteRequestSpec(collection: parts[3], id: parts[4], ids: queryIDs, wholeCollection: false) } } private struct SyncPutRequestSpec { let collection: String let id: String static func fromRequest(request: GCDWebServerRequest) -> SyncPutRequestSpec? { // Input is "/1.5/user/storage/collection/id}}}". // That means we get six path components here, the first being empty. let parts = request.path!.components(separatedBy: "/").filter { !$0.isEmpty } guard parts.count == 5 else { return nil } if parts[2] != "storage" { return nil } return SyncPutRequestSpec(collection: parts[3], id: parts[4]) } } class MockSyncServer { let server = GCDWebServer() let username: String var offsets: Int = 0 var continuations: [String: [EnvelopeJSON]] = [:] var collections: [String: (modified: Timestamp, records: [String: EnvelopeJSON])] = [:] var baseURL: String! init(username: String) { self.username = username } class func makeValidEnvelope(guid: GUID, modified: Timestamp) -> EnvelopeJSON { let clientBody: [String: Any] = [ "id": guid, "name": "Foobar", "commands": [], "type": "mobile", ] let clientBodyString = JSON(object: clientBody).stringValue()! let clientRecord: [String : Any] = [ "id": guid, "collection": "clients", "payload": clientBodyString, "modified": Double(modified) / 1000, ] return EnvelopeJSON(JSON(object: clientRecord).stringValue()!) } class func withHeaders(response: GCDWebServerResponse, lastModified: Timestamp? = nil, records: Int? = nil, timestamp: Timestamp? = nil) -> GCDWebServerResponse { let timestamp = timestamp ?? Date.now() let xWeaveTimestamp = millisecondsToDecimalSeconds(timestamp) response.setValue("\(xWeaveTimestamp)", forAdditionalHeader: "X-Weave-Timestamp") if let lastModified = lastModified { let xLastModified = millisecondsToDecimalSeconds(lastModified) response.setValue("\(xLastModified)", forAdditionalHeader: "X-Last-Modified") } if let records = records { response.setValue("\(records)", forAdditionalHeader: "X-Weave-Records") } return response } func storeRecords(records: [EnvelopeJSON], inCollection collection: String, now: Timestamp? = nil) { let now = now ?? Date.now() let coll = self.collections[collection] var out = coll?.records ?? [:] records.forEach { out[$0.id] = $0.withModified(now) } let newModified = max(now, coll?.modified ?? 0) self.collections[collection] = (modified: newModified, records: out) } private func splitArray<T>(items: [T], at: Int) -> ([T], [T]) { return (Array(items.dropLast(items.count - at)), Array(items.dropFirst(at))) } private func recordsMatchingSpec(spec: SyncRequestSpec) -> (records: [EnvelopeJSON], offsetID: String?)? { // If we have a provided offset, handle that directly. if let offset = spec.offset { log.debug("Got provided offset \(offset).") guard let remainder = self.continuations[offset] else { log.error("Unknown offset.") return nil } // Remove the old one. self.continuations.removeValue(forKey: offset) // Handle the smaller-than-limit or no-provided-limit cases. guard let limit = spec.limit, limit < remainder.count else { log.debug("Returning all remaining items.") return (remainder, nil) } // Record the next continuation and return the first slice of records. let next = "\(self.offsets)" self.offsets += 1 let (returned, remaining) = splitArray(items: remainder, at: limit) self.continuations[next] = remaining log.debug("Returning \(limit) items; next continuation is \(next).") return (returned, next) } guard let records = self.collections[spec.collection]?.records.values else { // No matching records. return ([], nil) } var items = Array(records) log.debug("Got \(items.count) candidate records.") if spec.newer ?? 0 > 0 { items = items.filter { $0.modified > spec.newer! } } if let ids = spec.ids { let ids = Set(ids) items = items.filter { ids.contains($0.id) } } if let sort = spec.sort { switch sort { case SortOption.NewestFirst: items = items.sorted { $0.modified > $1.modified } log.debug("Sorted items newest first: \(items.map { $0.modified })") case SortOption.OldestFirst: items = items.sorted { $0.modified < $1.modified } log.debug("Sorted items oldest first: \(items.map { $0.modified })") case SortOption.Index: log.warning("Index sorting not yet supported.") } } if let limit = spec.limit, items.count > limit { let next = "\(self.offsets)" self.offsets += 1 let (returned, remaining) = splitArray(items: items, at: limit) self.continuations[next] = remaining return (returned, next) } return (items, nil) } private func recordResponse(record: EnvelopeJSON) -> GCDWebServerResponse { let body = record.asJSON().stringValue()! let bodyData = body.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json") return MockSyncServer.withHeaders(response: response!, lastModified: record.modified) } private func modifiedResponse(timestamp: Timestamp) -> GCDWebServerResponse { let body = JSON(object: ["modified": timestamp]).stringValue() let bodyData = body?.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json")! return MockSyncServer.withHeaders(response: response) } func modifiedTimeForCollection(collection: String) -> Timestamp? { return self.collections[collection]?.modified } func removeAllItemsFromCollection(collection: String, atTime: Timestamp) { if self.collections[collection] != nil { self.collections[collection] = (atTime, [:]) } } func start() { let basePath = "/1.5/\(self.username)" let storagePath = "\(basePath)/storage/" let infoCollectionsPath = "\(basePath)/info/collections" server?.addHandler(forMethod: "GET", path: infoCollectionsPath, request: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in var ic = [String: Any]() var lastModified: Timestamp = 0 for collection in self.collections.keys { if let timestamp = self.modifiedTimeForCollection(collection: collection) { ic[collection] = Double(timestamp) / 1000 lastModified = max(lastModified, timestamp) } } let body = JSON(object: ic).stringValue() let bodyData = body?.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json")! return MockSyncServer.withHeaders(response: response, lastModified: lastModified, records: ic.count) } let matchPut: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in guard method == "PUT", path?.startsWith(basePath) ?? false else { return nil } return GCDWebServerDataRequest(method: method, url: url, headers: headers, path: path, query: query) } server?.addHandler(match: matchPut) { (request) -> GCDWebServerResponse! in guard let request = request as? GCDWebServerDataRequest else { return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 400)) } guard let spec = SyncPutRequestSpec.fromRequest(request: request) else { return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 400)) } var body = JSON(object: request.jsonObject) body["modified"] = JSON(stringLiteral: millisecondsToDecimalSeconds(Date.now())) let record = EnvelopeJSON(body) self.storeRecords(records: [record], inCollection: spec.collection) let timestamp = self.modifiedTimeForCollection(collection: spec.collection)! let response = GCDWebServerDataResponse(data: millisecondsToDecimalSeconds(timestamp).utf8EncodedData, contentType: "application/json") return MockSyncServer.withHeaders(response: response!) } let matchDelete: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in guard method == "DELETE" && (path?.startsWith(basePath))! else { return nil } return GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query) } server?.addHandler(match: matchDelete) { (request) -> GCDWebServerResponse! in guard let spec = SyncDeleteRequestSpec.fromRequest(request: request!) else { return GCDWebServerDataResponse(statusCode: 400) } if let collection = spec.collection, let id = spec.id { guard var items = self.collections[collection]?.records else { // Unable to find the requested collection. return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 404)) } guard let item = items[id] else { // Unable to find the requested id. return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 404)) } items.removeValue(forKey: id) return self.modifiedResponse(timestamp: item.modified) } if let collection = spec.collection { if spec.wholeCollection { self.collections.removeValue(forKey: collection) } else { if let ids = spec.ids, var map = self.collections[collection]?.records { for id in ids { map.removeValue(forKey: id) } self.collections[collection] = (Date.now(), records: map) } } return self.modifiedResponse(timestamp: Date.now()) } self.collections = [:] return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(data: "{}".utf8EncodedData, contentType: "application/json")) } let match: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in guard method == "GET", path?.startsWith(storagePath) ?? false else { return nil } return GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query) } server?.addHandler(match: match) { (request) -> GCDWebServerResponse! in // 1. Decide what the URL is asking for. It might be a collection fetch or // an individual record, and it might have query parameters. guard let spec = SyncRequestSpec.fromRequest(request: request!) else { return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 400)) } // 2. Grab the matching set of records. Prune based on TTL, exclude with X-I-U-S, etc. if let id = spec.id { guard let collection = self.collections[spec.collection], let record = collection.records[id] else { // Unable to find the requested collection/id. return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 404)) } return self.recordResponse(record: record) } guard let (items, offset) = self.recordsMatchingSpec(spec: spec) else { // Unable to find the provided offset. return MockSyncServer.withHeaders(response: GCDWebServerDataResponse(statusCode: 400)) } // TODO: TTL // TODO: X-I-U-S let body = JSON(object: items.map { $0.asJSON() }).stringValue() let bodyData = body?.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json") // 3. Compute the correct set of headers: timestamps, X-Weave-Records, etc. if let offset = offset { response?.setValue(offset, forAdditionalHeader: "X-Weave-Next-Offset") } let timestamp = self.modifiedTimeForCollection(collection: spec.collection)! log.debug("Returning GET response with X-Last-Modified for \(items.count) records: \(timestamp).") return MockSyncServer.withHeaders(response: response!, lastModified: timestamp, records: items.count) } if server?.start(withPort: 0, bonjourName: nil) == false { XCTFail("Can't start the GCDWebServer.") } baseURL = "http://localhost:\(server!.port)\(basePath)" } }
mpl-2.0
f58c4c444222595651c8d8ca02e32316
38.262693
166
0.596368
4.921417
false
false
false
false
zom/Zom-iOS
Zom/Zom/Classes/View Controllers/ZomProfileViewController.swift
1
20956
// // ZomProfileViewController.swift // Zom // // Created by David Chiles on 12/12/16. // // import Foundation import PureLayout import OTRAssets import MobileCoreServices import FormatterKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } extension OTRBuddy { func zom_inviteLink(_ fingerprint:Fingerprint?) -> URL? { guard let jid = XMPPJID(string: self.username) else { return nil } var queryItems = [URLQueryItem]() if let fprint = fingerprint { switch fprint { case .OTR(let otrFingerprint): queryItems.append(URLQueryItem(name: OTRAccount.fingerprintStringType(for: .OTR)!, value: (otrFingerprint.fingerprint as NSData).humanReadableFingerprint())) break default: break } } return NSURL.otr_shareLink(NSURL.otr_shareBase, jid: jid , queryItems: queryItems) } } enum Fingerprint { case OTR(OTRFingerprint) case OMEMO(OMEMODevice) func fingerprintString() -> String { switch self { case .OTR(let fingerprint): return (fingerprint.fingerprint as NSData).humanReadableFingerprint() case .OMEMO(let device): return device.humanReadableFingerprint } } func isTrusted() -> Bool { switch self { case .OTR(let fingerprint): return fingerprint.isTrusted() case .OMEMO(let device): return device.isTrusted() } } func lastSeen() -> Date { switch self { case .OTR: return Date.distantPast case .OMEMO(let device): return device.lastSeenDate } } func lastSeenDisplayString() -> String { switch self { case .OTR: return "OTR" case .OMEMO(let device): let intervalFormatter = TTTTimeIntervalFormatter() let interval = -Date().timeIntervalSince(device.lastSeenDate) let since = intervalFormatter.string(forTimeInterval: interval) return "OMEMO: " + since! } } } struct FingerprintCellInfo: ZomProfileViewCellInfoProtocol { let fingerprint:Fingerprint let qrAction:((_ info:FingerprintCellInfo)->Void)? let shareAction:((_ info:FingerprintCellInfo)->Void)? fileprivate let shareImage = UIImage(named: "OTRShareIcon", in: OTRAssets.resourcesBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) let showLastSeen:Bool func configure(_ cell: UITableViewCell) { guard let fingerprintCell = cell as? ZomFingerprintCell else { return } fingerprintCell.shareButton.setImage(self.shareImage, for: UIControlState()) fingerprintCell.qrButton.setImage(UIImage(named: "zom_qrcode_placeholder", in: Bundle.main, compatibleWith: nil), for: UIControlState()) fingerprintCell.fingerprintLabel.text = fingerprint.fingerprintString() if showLastSeen { fingerprintCell.lastSeenLabel.text = fingerprint.lastSeenDisplayString() fingerprintCell.lastSeenLabelHeight.constant = 20 } else { fingerprintCell.lastSeenLabel.text = "" fingerprintCell.lastSeenLabelHeight.constant = 0 } fingerprintCell.qrAction = {cell in if let action = self.qrAction { action(self) } } fingerprintCell.shareAction = {cell in if let action = self.shareAction { action(self) } } } func cellIdentifier() -> ZomProfileViewCellIdentifier { return .FingerprintCell } func cellHeight() -> CGFloat? { var height:CGFloat = 90 if showLastSeen { height += 20 } return height } } class ZomProfileTableViewSource:NSObject, UITableViewDataSource, UITableViewDelegate { let tableSections:[TableSectionInfo] var info:ZomProfileViewControllerInfo var controller:ZomProfileViewController var relaodData:(() -> Void)? init(info:ZomProfileViewControllerInfo, tableSections:[TableSectionInfo], controller:ZomProfileViewController) { self.info = info self.tableSections = tableSections self.controller = controller } //MARK: UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return tableSections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableSections[section].cells?.count ?? 0; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let object = self.tableSections.infoAtIndexPath(indexPath) { let cell = tableView.dequeueReusableCell(withIdentifier: object.cellIdentifier().rawValue, for: indexPath) // Lay it out cell.setNeedsUpdateConstraints() cell.updateConstraintsIfNeeded() cell.setNeedsLayout() cell.layoutIfNeeded() object.configure(cell) return cell } //This should never happen return tableView.dequeueReusableCell(withIdentifier: "", for: indexPath) } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.tableSections.sectionAtIndex(section)?.title } //MARK: UITableviewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.tableSections.infoAtIndexPath(indexPath)?.cellHeight() ?? UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let object = self.tableSections.infoAtIndexPath(indexPath) as? ButtonCellInfo else { return } switch object.type { case .refresh: //TODO: We should at some point listen for encryption change notification to refresh the table view with new fingerprint informatoin guard let username = self.info.otrKitInfo.username else { return } self.info.otrKit.initiateEncryption(withUsername: username, accountName: self.info.otrKitInfo.accountName, protocol: self.info.otrKitInfo.protocolString) break case .startChat: //TODO: We should at some point listen for encryption change notification to refresh the table view with new fingerprint informatoin // TODO: close and start chat! Possibly via if let appDelegate = UIApplication.shared.delegate as? ZomAppDelegate { switch self.info.user { case let .buddy(buddy) : _ = controller.navigationController?.popToRootViewController(animated: true) appDelegate.splitViewCoordinator.enterConversationWithBuddy(buddy.uniqueId) default: return } } break case .addFriend(_): switch self.info.user { case .buddy(let buddy as OTRXMPPBuddy) : let vc = ZomAddFriendViewController() vc.setBuddy(buddy) vc.delegate = controller vc.modalPresentationStyle = .overFullScreen vc.modalTransitionStyle = .crossDissolve controller.present(vc, animated: true, completion: nil) break default: return } break case .showCodes(_): switch self.info.user { case .buddy(let buddy as OTRXMPPBuddy) : var account:OTRAccount? = nil OTRDatabaseManager.shared.readConnection?.read({ (transaction) in if buddy.isYou(transaction: transaction) { account = buddy.account(with: transaction) } }) var vc:UIViewController? = nil if let account = account as? OTRXMPPAccount { vc = GlobalTheme.shared.keyManagementViewController(account: account) } else { vc = GlobalTheme.shared.keyManagementViewController(buddy: buddy) } if let vc = vc { let nav = UINavigationController(rootViewController: vc) controller.present(nav, animated: true, completion: nil) } break default: break } break } } } open class ZomProfileViewController : UIViewController { fileprivate var avatarPicker:OTRAttachmentPicker? = nil let tableView = UITableView(frame: CGRect.zero, style: .grouped) fileprivate var tableViewSource:ZomProfileTableViewSource? = nil fileprivate var tableViewNoAccountSource:ZomNoAccountTableViewSource? = nil var profileObserver:ZomProfileViewObserver? = nil var passwordChangeDelegate:PasswordChangeTextFieldDelegate? = nil override open func viewDidLoad() { super.viewDidLoad() self.tableView.translatesAutoresizingMaskIntoConstraints = false ZomProfileViewCellIdentifier.allValues.forEach { (cellIdentifier) in switch ZomProfileViewCellIdentifier.classOrNib(cellIdentifier) { case let .class(cellClass) : self.tableView.register(cellClass, forCellReuseIdentifier: cellIdentifier.rawValue) break case let .nib(cellNib): self.tableView.register(cellNib, forCellReuseIdentifier: cellIdentifier.rawValue) break } } self.view.addSubview(self.tableView) self.tableView.autoPinEdgesToSuperviewEdges() } func setupWithInfo(info:ZomProfileViewControllerInfo) { let qrAction:(FingerprintCellInfo)->Void = { [weak self] fingerprintInfo in User.shareURL(info.user, fingerprint: fingerprintInfo.fingerprint , completion: { (url) in guard let inviteURL = url else { return } guard let qrViewController = OTRQRCodeViewController(qrString: inviteURL.absoluteString) else { return } let navigationController = UINavigationController(rootViewController: qrViewController) self?.present(navigationController, animated: true, completion: nil) }) } let shareAction:(FingerprintCellInfo) -> Void = { [weak self] fingerprintInfo in User.shareURL(info.user, fingerprint: fingerprintInfo.fingerprint, completion: { (url) in guard let inviteURL = url else { return } let activityViewController = UIActivityViewController(activityItems: [inviteURL], applicationActivities: nil) if let view = self?.view { activityViewController.popoverPresentationController?.sourceView = view; activityViewController.popoverPresentationController?.sourceRect = view.bounds; } self?.present(activityViewController, animated: true, completion: nil) }) } self.profileObserver = ZomProfileViewObserver(info:info,qrAction:qrAction,shareAction:shareAction) self.profileObserver?.delegate = self self.updateTableView() } func updateTableView() { guard let info = self.profileObserver?.info, let tableSections = self.profileObserver?.tableSections else { return } self.tableViewSource = ZomProfileTableViewSource(info: info, tableSections: tableSections, controller: self) self.tableViewSource?.relaodData = { [weak self] in self?.profileObserver?.reloadInfo() self?.updateTableView() } self.tableView.dataSource = self.tableViewSource self.tableView.delegate = self.tableViewSource self.tableView.reloadData() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIApplication.shared.setStatusBarHidden(false, with: .none) } @IBAction func didPressChangePasswordButton(_ sender: UIButton) { let alert = UIAlertController(title: NSLocalizedString("Change password", comment: "Title for change password alert"), message: NSLocalizedString("Please enter your new password", comment: "Message for change password alert"), preferredStyle: UIAlertControllerStyle.alert) passwordChangeDelegate = PasswordChangeTextFieldDelegate(alert: alert) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "OK button"), style: UIAlertActionStyle.default, handler: {(action: UIAlertAction!) in if let user = self.profileObserver?.info.user { switch user { case let .account(account): if let xmppManager = OTRProtocolManager.sharedInstance().protocol(for: account) as? XMPPManager, let newPassword = alert.textFields?.first?.text { xmppManager.changePassword(newPassword, completion: { (success, error) in DispatchQueue.main.async(execute: { //Update password textfield with new password self.tableViewSource?.relaodData?() }) }) } break default: break } } })) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button"), style: UIAlertActionStyle.cancel, handler: nil)) alert.addTextField(configurationHandler: {(textField: UITextField!) in textField.placeholder = NSLocalizedString("Password:", comment: "Prompt for new password") textField.isSecureTextEntry = true textField.addTarget(self.passwordChangeDelegate, action: #selector(PasswordChangeTextFieldDelegate.textFieldDidChange(_:)), for: UIControlEvents.editingChanged) }) alert.addTextField(configurationHandler: {(textField: UITextField!) in textField.placeholder = NSLocalizedString("Confirm New Password", comment: "Prompt for confirm password") textField.isSecureTextEntry = true textField.addTarget(self.passwordChangeDelegate, action: #selector(PasswordChangeTextFieldDelegate.textFieldDidChange(_:)), for: UIControlEvents.editingChanged) }) alert.actions[0].isEnabled = false self.present(alert, animated: true, completion: nil) } class PasswordChangeTextFieldDelegate: NSObject, UITextFieldDelegate { var alert:UIAlertController @objc func textFieldDidChange(_ textField: UITextField){ guard let tf1 = alert.textFields?[0] else { return } guard let tf2 = alert.textFields?[1] else { return } if (tf1.text?.count > 0 && tf2.text?.count > 0 && tf1.text!.compare(tf2.text!) == ComparisonResult.orderedSame) { alert.actions[0].isEnabled = true } else { alert.actions[0].isEnabled = false } } init( alert:UIAlertController ) { self.alert = alert } } @IBAction func didTapAvatarImageWithSender(_ sender: UIButton) { if let user = self.profileObserver?.info.user { switch user { case .account(_): // Keep strong reference if let parentViewController = self.tabBarController?.navigationController { avatarPicker = OTRAttachmentPicker(parentViewController: parentViewController as! UIViewController & UIPopoverPresentationControllerDelegate, delegate: self) avatarPicker!.showAlertController(fromSourceView: sender, withCompletion: nil) } break default: break } } } } extension ZomProfileViewController: OTRAttachmentPickerDelegate { public func attachmentPicker(_ attachmentPicker: OTRAttachmentPicker, gotVideoURL videoURL: URL) { } public func attachmentPicker(_ attachmentPicker: OTRAttachmentPicker, gotPhoto photo: UIImage, withInfo info: [AnyHashable: Any]) { if let user = self.profileObserver?.info.user { switch user { case let .account(account): if let xmppManager = OTRProtocolManager.sharedInstance().protocol(for: account) as? XMPPManager { xmppManager.setAvatar(photo, completion: { (success) in }) } break default: break } } } public func attachmentPicker(_ attachmentPicker: OTRAttachmentPicker, preferredMediaTypesFor source: UIImagePickerControllerSourceType) -> [String] { return [kUTTypeImage as String] } } extension ZomProfileViewController: ZomProfileViewObserverDelegate { func didUpdateTableSections(observer: ZomProfileViewObserver) { self.updateTableView() } func didRemoveTableSections(observer: ZomProfileViewObserver) { self.tableViewNoAccountSource = ZomNoAccountTableViewSource() self.tableView.dataSource = tableViewNoAccountSource self.tableView.delegate = tableViewNoAccountSource self.tableView.reloadData() } } fileprivate class ZomNoAccountTableViewSource: NSObject, UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel?.text = NEW_ACCOUNT_STRING() cell.imageView?.image = UIImage(named: "31-circle-plus-large.png", in: OTRAssets.resourcesBundle, compatibleWith: nil) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let app = ZomAppDelegate.appDelegate app.conversationViewController.hasPresentedOnboarding = false app.conversationViewController.showOnboardingIfNeeded() app.conversationViewController.hasPresentedOnboarding = true } } extension ZomProfileViewController : ZomAddFriendViewControllerDelegate { func didSelectBuddy(_ buddy: OTRXMPPBuddy, from viewController: UIViewController) { var manager:XMPPManager? = nil OTRDatabaseManager.shared.connections?.ui.read { (transaction) in if let account = buddy.account(with: transaction) { manager = OTRProtocolManager.shared.protocol(for: account) as? XMPPManager } } if let manager = manager { manager.addBuddies([buddy]) DispatchQueue.main.async { let vc = ZomAddFriendRequestedViewController() vc.modalPresentationStyle = .overFullScreen vc.modalTransitionStyle = .crossDissolve viewController.dismiss(animated: true) { self.present(vc, animated: true, completion: { // Reload profile view if let reload = self.tableViewSource?.relaodData { reload() } }) } } } // else TODO handle error case } func didNotSelectBuddy(from viewController: UIViewController) { } }
mpl-2.0
52f1217659080589c52b568d67631ca0
39.455598
280
0.6203
5.558621
false
false
false
false
hulu001/ImagePickerSheetController
ImagePickerSheetController/ImagePickerSheetController/ImagePickerSheetController.swift
2
19085
// // ImagePickerController.swift // ImagePickerSheet // // Created by Laurin Brandner on 24/05/15. // Copyright (c) 2015 Laurin Brandner. All rights reserved. // import Foundation import Photos private let previewCollectionViewInset: CGFloat = 5 /// The media type an instance of ImagePickerSheetController can display public enum ImagePickerMediaType { case Image case Video case ImageAndVideo } @available(iOS 8.0, *) public class ImagePickerSheetController: UIViewController { private lazy var sheetController: SheetController = { let controller = SheetController(previewCollectionView: self.previewCollectionView) controller.actionHandlingCallback = { [weak self] in self?.dismissViewControllerAnimated(true, completion: nil) } return controller }() var sheetCollectionView: UICollectionView { return sheetController.sheetCollectionView } private(set) lazy var previewCollectionView: PreviewCollectionView = { let collectionView = PreviewCollectionView() collectionView.accessibilityIdentifier = "ImagePickerSheetPreview" collectionView.backgroundColor = .clearColor() collectionView.allowsMultipleSelection = true collectionView.imagePreviewLayout.sectionInset = UIEdgeInsetsMake(previewCollectionViewInset, previewCollectionViewInset, previewCollectionViewInset, previewCollectionViewInset) collectionView.imagePreviewLayout.showsSupplementaryViews = false collectionView.dataSource = self collectionView.delegate = self collectionView.showsHorizontalScrollIndicator = false collectionView.alwaysBounceHorizontal = true collectionView.registerClass(PreviewCollectionViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(PreviewCollectionViewCell.self)) collectionView.registerClass(PreviewSupplementaryView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: NSStringFromClass(PreviewSupplementaryView.self)) return collectionView }() private var supplementaryViews = [Int: PreviewSupplementaryView]() lazy var backgroundView: UIView = { let view = UIView() view.accessibilityIdentifier = "ImagePickerSheetBackground" view.backgroundColor = UIColor(white: 0.0, alpha: 0.3961) view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "cancel")) return view }() /// All the actions. The first action is shown at the top. public var actions: [ImagePickerAction] { return sheetController.actions } /// Maximum selection of images. public var maximumSelection: Int? private var selectedImageIndices = [Int]() { didSet { sheetController.numberOfSelectedImages = selectedImageIndices.count } } /// The selected image assets public var selectedImageAssets: [PHAsset] { return selectedImageIndices.map { self.assets[$0] } } /// The media type of the displayed assets public let mediaType: ImagePickerMediaType private var assets = [PHAsset]() private lazy var requestOptions: PHImageRequestOptions = { let options = PHImageRequestOptions() options.deliveryMode = .HighQualityFormat options.resizeMode = .Fast return options }() private let imageManager = PHCachingImageManager() /// Whether the image preview has been elarged. This is the case when at least once /// image has been selected. public private(set) var enlargedPreviews = false private let minimumPreviewHeight: CGFloat = 129 private var maximumPreviewHeight: CGFloat = 129 private var previewCheckmarkInset: CGFloat { guard #available(iOS 9, *) else { return 3.5 } return 12.5 } // MARK: - Initialization public init(mediaType: ImagePickerMediaType) { self.mediaType = mediaType super.init(nibName: nil, bundle: nil) initialize() } public required init?(coder aDecoder: NSCoder) { self.mediaType = .ImageAndVideo super.init(coder: aDecoder) initialize() } private func initialize() { modalPresentationStyle = .Custom transitioningDelegate = self NSNotificationCenter.defaultCenter().addObserver(self, selector: "cancel", name: UIApplicationDidEnterBackgroundNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - View Lifecycle override public func loadView() { super.loadView() view.addSubview(backgroundView) view.addSubview(sheetCollectionView) } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) preferredContentSize = CGSize(width: 400, height: view.frame.height) if PHPhotoLibrary.authorizationStatus() == .Authorized { prepareAssets() } } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if PHPhotoLibrary.authorizationStatus() == .NotDetermined { PHPhotoLibrary.requestAuthorization() { status in if status == .Authorized { dispatch_async(dispatch_get_main_queue()) { self.prepareAssets() self.previewCollectionView.reloadData() self.sheetCollectionView.reloadData() self.view.setNeedsLayout() // Explicitely disable animations so it wouldn't animate either // if it was in a popover CATransaction.begin() CATransaction.setDisableActions(true) self.view.layoutIfNeeded() CATransaction.commit() } } } } } // MARK: - Actions /// Adds an new action. /// If the passed action is of type Cancel, any pre-existing Cancel actions will be removed. /// Always arranges the actions so that the Cancel action appears at the bottom. public func addAction(action: ImagePickerAction) { sheetController.addAction(action) view.setNeedsLayout() } @objc private func cancel() { sheetController.handleCancelAction() } // MARK: - Images private func sizeForAsset(asset: PHAsset, scale: CGFloat = 1) -> CGSize { let proportion = CGFloat(asset.pixelWidth)/CGFloat(asset.pixelHeight) let imageHeight = maximumPreviewHeight - 2 * previewCollectionViewInset let imageWidth = floor(proportion * imageHeight) return CGSize(width: imageWidth * scale, height: imageHeight * scale) } private func prepareAssets() { fetchAssets() reloadMaximumPreviewHeight() reloadCurrentPreviewHeight(invalidateLayout: false) // Filter out the assets that are too thin. This can't be done before becuase // we don't know how tall the images should be let minImageWidth = 2 * previewCheckmarkInset + (PreviewSupplementaryView.checkmarkImage?.size.width ?? 0) assets = assets.filter { asset in let size = sizeForAsset(asset) return size.width >= minImageWidth } } private func fetchAssets() { let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] switch mediaType { case .Image: options.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue) case .Video: options.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Video.rawValue) case .ImageAndVideo: options.predicate = NSPredicate(format: "mediaType = %d OR mediaType = %d", PHAssetMediaType.Image.rawValue, PHAssetMediaType.Video.rawValue) } let fetchLimit = 50 if #available(iOS 9, *) { options.fetchLimit = fetchLimit } let result = PHAsset.fetchAssetsWithOptions(options) result.enumerateObjectsUsingBlock { obj, _, _ in if let asset = obj as? PHAsset where self.assets.count < fetchLimit { self.assets.append(asset) } } } private func requestImageForAsset(asset: PHAsset, completion: (image: UIImage?) -> ()) { let targetSize = sizeForAsset(asset, scale: UIScreen.mainScreen().scale) // Workaround because PHImageManager.requestImageForAsset doesn't work for burst images if asset.representsBurst { imageManager.requestImageDataForAsset(asset, options: requestOptions) { data, _, _, _ in let image = data.flatMap { UIImage(data: $0) } completion(image: image) } } else { imageManager.requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: requestOptions) { image, _ in completion(image: image) } } } private func prefetchImagesForAsset(asset: PHAsset) { let targetSize = sizeForAsset(asset, scale: UIScreen.mainScreen().scale) imageManager.startCachingImagesForAssets([asset], targetSize: targetSize, contentMode: .AspectFill, options: requestOptions) } // MARK: - Layout public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() backgroundView.frame = view.bounds reloadMaximumPreviewHeight() reloadCurrentPreviewHeight(invalidateLayout: true) let sheetHeight = sheetController.preferredSheetHeight let sheetSize = CGSize(width: view.bounds.width, height: sheetHeight) // This particular order is necessary so that the sheet is layed out // correctly with and without an enclosing popover preferredContentSize = sheetSize sheetCollectionView.frame = CGRect(origin: CGPoint(x: view.bounds.minX, y: view.bounds.maxY-sheetHeight), size: sheetSize) } private func reloadCurrentPreviewHeight(invalidateLayout invalidate: Bool) { if assets.count <= 0 { sheetController.setPreviewHeight(0, invalidateLayout: invalidate) } else if assets.count > 0 && enlargedPreviews { sheetController.setPreviewHeight(maximumPreviewHeight, invalidateLayout: invalidate) } else { sheetController.setPreviewHeight(minimumPreviewHeight, invalidateLayout: invalidate) } } private func reloadMaximumPreviewHeight() { let maxHeight: CGFloat = 400 let maxImageWidth = sheetController.preferredSheetWidth - 2 * previewCollectionViewInset let assetRatios = assets.map { CGSize(width: max($0.pixelHeight, $0.pixelWidth), height: min($0.pixelHeight, $0.pixelWidth)) } .map { $0.height / $0.width } let assetHeights = assetRatios.map { $0 * maxImageWidth } .filter { $0 < maxImageWidth && $0 < maxHeight } // Make sure the preview isn't too high eg for squares .sort(>) let assetHeight = round(assetHeights.first ?? 0) // Just a sanity check, to make sure this doesn't exceed 400 points let scaledHeight = max(min(assetHeight, maxHeight), 200) maximumPreviewHeight = scaledHeight + 2 * previewCollectionViewInset } // MARK: - func enlargePreviewsByCenteringToIndexPath(indexPath: NSIndexPath?, completion: (Bool -> ())?) { enlargedPreviews = true previewCollectionView.imagePreviewLayout.invalidationCenteredIndexPath = indexPath reloadCurrentPreviewHeight(invalidateLayout: false) view.setNeedsLayout() let animationDuration: NSTimeInterval if #available(iOS 9, *) { animationDuration = 0.2 } else { animationDuration = 0.3 } UIView.animateWithDuration(animationDuration, animations: { self.sheetCollectionView.reloadSections(NSIndexSet(index: 0)) self.view.layoutIfNeeded() }, completion: completion) } } // MARK: - UICollectionViewDataSource extension ImagePickerSheetController: UICollectionViewDataSource { public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return assets.count } public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(NSStringFromClass(PreviewCollectionViewCell.self), forIndexPath: indexPath) as! PreviewCollectionViewCell let asset = assets[indexPath.section] cell.videoIndicatorView.hidden = asset.mediaType != .Video requestImageForAsset(asset) { image in cell.imageView.image = image } cell.selected = selectedImageIndices.contains(indexPath.section) return cell } public func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: NSStringFromClass(PreviewSupplementaryView.self), forIndexPath: indexPath) as! PreviewSupplementaryView view.userInteractionEnabled = false view.buttonInset = UIEdgeInsetsMake(0.0, previewCheckmarkInset, previewCheckmarkInset, 0.0) view.selected = selectedImageIndices.contains(indexPath.section) supplementaryViews[indexPath.section] = view return view } } // MARK: - UICollectionViewDelegate extension ImagePickerSheetController: UICollectionViewDelegate { public func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { let nextIndex = indexPath.item+1 if nextIndex < assets.count { let asset = assets[nextIndex] self.prefetchImagesForAsset(asset) } } public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if let maximumSelection = maximumSelection { if selectedImageIndices.count >= maximumSelection, let previousItemIndex = selectedImageIndices.first { supplementaryViews[previousItemIndex]?.selected = false selectedImageIndices.removeAtIndex(0) } } // Just to make sure the image is only selected once selectedImageIndices = selectedImageIndices.filter { $0 != indexPath.section } selectedImageIndices.append(indexPath.section) if !enlargedPreviews { enlargePreviewsByCenteringToIndexPath(indexPath) { _ in self.sheetController.reloadActionItems() self.previewCollectionView.imagePreviewLayout.showsSupplementaryViews = true } } else { // scrollToItemAtIndexPath doesn't work reliably if let cell = collectionView.cellForItemAtIndexPath(indexPath) { var contentOffset = CGPointMake(cell.frame.midX - collectionView.frame.width / 2.0, 0.0) contentOffset.x = max(contentOffset.x, -collectionView.contentInset.left) contentOffset.x = min(contentOffset.x, collectionView.contentSize.width - collectionView.frame.width + collectionView.contentInset.right) collectionView.setContentOffset(contentOffset, animated: true) } sheetController.reloadActionItems() } supplementaryViews[indexPath.section]?.selected = true } public func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { if let index = selectedImageIndices.indexOf(indexPath.section) { selectedImageIndices.removeAtIndex(index) sheetController.reloadActionItems() } supplementaryViews[indexPath.section]?.selected = false } } // MARK: - UICollectionViewDelegateFlowLayout extension ImagePickerSheetController: UICollectionViewDelegateFlowLayout { public func collectionView(collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let asset = assets[indexPath.section] let size = sizeForAsset(asset) // Scale down to the current preview height, sizeForAsset returns the original size let currentImagePreviewHeight = sheetController.previewHeight - 2 * previewCollectionViewInset let scale = currentImagePreviewHeight / size.height return CGSize(width: size.width * scale, height: currentImagePreviewHeight) } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { let inset = 2.0 * previewCheckmarkInset let size = self.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAtIndexPath: NSIndexPath(forItem: 0, inSection: section)) let imageWidth = PreviewSupplementaryView.checkmarkImage?.size.width ?? 0 return CGSizeMake(imageWidth + inset, size.height) } } // MARK: - UIViewControllerTransitioningDelegate extension ImagePickerSheetController: UIViewControllerTransitioningDelegate { public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return AnimationController(imagePickerSheetController: self, presenting: true) } public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return AnimationController(imagePickerSheetController: self, presenting: false) } }
mit
8fe38a7bbbe5ce0d33cf42f418c833f4
38.843424
235
0.664711
5.845329
false
false
false
false
AzenXu/ReactNativeTest
TestDemos/ios/GradientView-master/GradientView/GradientView.swift
1
6866
// // GradientView.swift // Gradient View // // Created by Sam Soffes on 10/27/09. // Copyright (c) 2009-2014 Sam Soffes. All rights reserved. // import UIKit /// Simple view for drawing gradients and borders. @IBDesignable public class GradientView: UIView { // MARK: - Types /// The mode of the gradient. public enum Type { /// A linear gradient. case Linear /// A radial gradient. case Radial } /// The direction of the gradient. public enum Direction { /// The gradient is vertical. case Vertical /// The gradient is horizontal case Horizontal } // MARK: - Properties /// An optional array of `UIColor` objects used to draw the gradient. If the value is `nil`, the `backgroundColor` /// will be drawn instead of a gradient. The default is `nil`. public var colors: [UIColor]? { didSet { updateGradient() } } /// An array of `UIColor` objects used to draw the dimmed gradient. If the value is `nil`, `colors` will be /// converted to grayscale. This will use the same `locations` as `colors`. If length of arrays don't match, bad /// things will happen. You must make sure the number of dimmed colors equals the number of regular colors. /// /// The default is `nil`. public var dimmedColors: [UIColor]? { didSet { updateGradient() } } /// Automatically dim gradient colors when prompted by the system (i.e. when an alert is shown). /// /// The default is `true`. public var automaticallyDims: Bool = true /// An optional array of `CGFloat`s defining the location of each gradient stop. /// /// The gradient stops are specified as values between `0` and `1`. The values must be monotonically increasing. If /// `nil`, the stops are spread uniformly across the range. /// /// Defaults to `nil`. public var locations: [CGFloat]? { didSet { updateGradient() } } /// The mode of the gradient. The default is `.Linear`. @IBInspectable public var mode: Type = .Linear { didSet { setNeedsDisplay() } } /// The direction of the gradient. Only valid for the `Mode.Linear` mode. The default is `.Vertical`. @IBInspectable public var direction: Direction = .Vertical { didSet { setNeedsDisplay() } } /// 1px borders will be drawn instead of 1pt borders. The default is `true`. @IBInspectable public var drawsThinBorders: Bool = true { didSet { setNeedsDisplay() } } /// The top border color. The default is `nil`. @IBInspectable public var topBorderColor: UIColor? { didSet { setNeedsDisplay() } } /// The right border color. The default is `nil`. @IBInspectable public var rightBorderColor: UIColor? { didSet { setNeedsDisplay() } } /// The bottom border color. The default is `nil`. @IBInspectable public var bottomBorderColor: UIColor? { didSet { setNeedsDisplay() } } /// The left border color. The default is `nil`. @IBInspectable public var leftBorderColor: UIColor? { didSet { setNeedsDisplay() } } // MARK: - UIView override public func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() let size = bounds.size // Gradient if let gradient = gradient { let options: CGGradientDrawingOptions = [.DrawsAfterEndLocation] if mode == .Linear { let startPoint = CGPointZero let endPoint = direction == .Vertical ? CGPoint(x: 0, y: size.height) : CGPoint(x: size.width, y: 0) CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, options) } else { let center = CGPoint(x: bounds.midX, y: bounds.midY) CGContextDrawRadialGradient(context, gradient, center, 0, center, min(size.width, size.height) / 2, options) } } let screen: UIScreen = window?.screen ?? UIScreen.mainScreen() let borderWidth: CGFloat = drawsThinBorders ? 1.0 / screen.scale : 1.0 // Top border if let color = topBorderColor { CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, CGRect(x: 0, y: 0, width: size.width, height: borderWidth)) } let sideY: CGFloat = topBorderColor != nil ? borderWidth : 0 let sideHeight: CGFloat = size.height - sideY - (bottomBorderColor != nil ? borderWidth : 0) // Right border if let color = rightBorderColor { CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, CGRect(x: size.width - borderWidth, y: sideY, width: borderWidth, height: sideHeight)) } // Bottom border if let color = bottomBorderColor { CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, CGRect(x: 0, y: size.height - borderWidth, width: size.width, height: borderWidth)) } // Left border if let color = leftBorderColor { CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, CGRect(x: 0, y: sideY, width: borderWidth, height: sideHeight)) } } override public func tintColorDidChange() { super.tintColorDidChange() if automaticallyDims { updateGradient() } } override public func didMoveToWindow() { super.didMoveToWindow() contentMode = .Redraw } // MARK: - Private private var gradient: CGGradientRef? private func updateGradient() { gradient = nil setNeedsDisplay() let colors = gradientColors() if let colors = colors { let colorSpace = CGColorSpaceCreateDeviceRGB() let colorSpaceModel = CGColorSpaceGetModel(colorSpace) let gradientColors: NSArray = colors.map { (color: UIColor) -> AnyObject! in let cgColor = color.CGColor let cgColorSpace = CGColorGetColorSpace(cgColor) // The color's color space is RGB, simply add it. if CGColorSpaceGetModel(cgColorSpace).rawValue == colorSpaceModel.rawValue { return cgColor as AnyObject! } // Convert to RGB. There may be a more efficient way to do this. var red: CGFloat = 0 var blue: CGFloat = 0 var green: CGFloat = 0 var alpha: CGFloat = 0 color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return UIColor(red: red, green: green, blue: blue, alpha: alpha).CGColor as AnyObject! } // TODO: This is ugly. Surely there is a way to make this more concise. if let locations = locations { gradient = CGGradientCreateWithColors(colorSpace, gradientColors, locations) } else { gradient = CGGradientCreateWithColors(colorSpace, gradientColors, nil) } } } private func gradientColors() -> [UIColor]? { if tintAdjustmentMode == .Dimmed { if let dimmedColors = dimmedColors { return dimmedColors } if automaticallyDims { if let colors = colors { return colors.map { var hue: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 $0.getHue(&hue, saturation: nil, brightness: &brightness, alpha: &alpha) return UIColor(hue: hue, saturation: 0, brightness: brightness, alpha: alpha) } } } } return colors } }
mit
b02e74bc8dc2bbb48982b588806f3ba2
25.407692
116
0.690504
3.725448
false
false
false
false
hughbe/swift
benchmark/single-source/BitCount.swift
8
1160
//===--- BitCount.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks performance of Swift bit count. // and mask operator. // rdar://problem/22151678 import Foundation import TestsUtils func countBitSet(_ num: Int) -> Int { let bits = MemoryLayout<Int>.size * 8 var cnt: Int = 0 var mask: Int = 1 for _ in 0...bits { if num & mask != 0 { cnt += 1 } mask <<= 1 } return cnt } @inline(never) public func run_BitCount(_ N: Int) { var sum = 0 for _ in 1...1000*N { // Check some results. sum = sum &+ countBitSet(getInt(1)) &+ countBitSet(getInt(2)) &+ countBitSet(getInt(2457)) } CheckResults(sum == 8 * 1000 * N) }
apache-2.0
28878d8c9f4694e3951c90df4884af5f
26.619048
80
0.559483
4.128114
false
false
false
false
lsonlee/Swift_MVVM
Swift_Project/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallClipRotateMultiple.swift
2
4103
// // NVActivityIndicatorAnimationBallClipRotateMultiple.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // 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 NVActivityIndicatorAnimationBallClipRotateMultiple: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let bigCircleSize: CGFloat = size.width let smallCircleSize: CGFloat = size.width / 2 let longDuration: CFTimeInterval = 1 let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) circleOf(shape: .ringTwoHalfHorizontal, duration: longDuration, timingFunction: timingFunction, layer: layer, size: bigCircleSize, color: color, reverse: false) circleOf(shape: .ringTwoHalfVertical, duration: longDuration, timingFunction: timingFunction, layer: layer, size: smallCircleSize, color: color, reverse: true) } func createAnimationIn(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, reverse: Bool) -> CAAnimation { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.6, 1] scaleAnimation.duration = duration // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.timingFunctions = [timingFunction, timingFunction] if !reverse { rotateAnimation.values = [0, CGFloat.pi, 2 * CGFloat.pi] } else { rotateAnimation.values = [0, -CGFloat.pi, -2 * CGFloat.pi] } rotateAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false return animation } func circleOf(shape: NVActivityIndicatorShape, duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGFloat, color: UIColor, reverse: Bool) { let circle = shape.layerWith(size: CGSize(width: size, height: size), color: color) let frame = CGRect(x: (layer.bounds.size.width - size) / 2, y: (layer.bounds.size.height - size) / 2, width: size, height: size) let animation = createAnimationIn(duration: duration, timingFunction: timingFunction, reverse: reverse) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
mit
0f9d8cb907b084b786d955c203b09f6b
41.739583
179
0.679259
5.174023
false
false
false
false
wfalkwallace/GithubPulse
widget/GithubPulse/Other Sources/GithubUpdate.swift
1
4208
// // GithubUpdate.swift // GithubPulse // // Created by Tadeu Zagallo on 1/19/15. // Copyright (c) 2015 Tadeu Zagallo. All rights reserved. // import Foundation class GithubUpdate { var bundleVersion:String? var repoName:String? var githubVersion:String? var install:Bool = false class func check() { GithubUpdate().check() } class func check(install:Bool) { let instance = GithubUpdate() instance.install = install instance.check() } func check() { self.getBundleInfo() self.getGithubVersion() } func getBundleInfo() { let bundle = NSBundle.mainBundle() self.bundleVersion = bundle.objectForInfoDictionaryKey("CFBundleVersion") as String? self.repoName = bundle.objectForInfoDictionaryKey("GithubRepo") as String? } func getGithubVersion() { if self.repoName == nil { return } let url = NSURL(string: "https://api.github.com/repos/\(self.repoName!)/tags") let request = NSURLRequest(URL: url!) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) in if data == nil || error != nil { return } if let tags = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSArray? { if tags.count > 0 { let lastTag = tags[0]["name"] as String println("Latest version is \(lastTag)") if EDSemver(string: lastTag).isGreaterThan(EDSemver(string: self.bundleVersion!)) { NSUserDefaults.standardUserDefaults().setValue("{\"data\":true}", forKey: "update_available") self.download(lastTag) } else { NSUserDefaults.standardUserDefaults().setValue("{\"data\":false}", forKey: "update_available") } } } } } func download(tag:String) { let fileManager = NSFileManager.defaultManager() let url = NSURL(string: "https://github.com/tadeuzagallo/GithubPulse/raw/\(tag)/dist/GithubPulse.zip") let request = NSURLRequest(URL: url!) let folder = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Contents/Versions") if !fileManager.fileExistsAtPath(folder) { fileManager.createDirectoryAtPath(folder, withIntermediateDirectories: false, attributes: nil, error: nil) } let path = folder.stringByAppendingPathComponent("\(tag).zip") if !fileManager.fileExistsAtPath(path) { println("Downloading \(tag)...") NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (_, data, _) in println("Download complete!") data.writeToFile(path, atomically: true) if self.install { self.extract(folder, tag: tag, path: path) } } } else { println("Version \(tag) is already on the cache!") if self.install { self.extract(folder, tag: tag, path: path) } } } func extract(folder:String, tag:String, path:String) { let fileManager = NSFileManager.defaultManager() let versionFolder = folder.stringByAppendingPathComponent(tag) if !fileManager.fileExistsAtPath(versionFolder) { fileManager.createDirectoryAtPath(versionFolder, withIntermediateDirectories: false, attributes: nil, error: nil) println("Unziping \(tag) to \(versionFolder)") SSZipArchive.unzipFileAtPath(path, toDestination: versionFolder) } self.copy(tag) } func copy(tag:String) { let relaunchPath = NSBundle.mainBundle().executablePath let currentPath = NSBundle.mainBundle().bundlePath println("Replacing old version by \(tag)") system("rm -rf /tmp/GithubPulse.app && mv \(currentPath) /tmp && mv /tmp/GithubPulse.app/Contents/Versions/\(tag)/GithubPulse.app \(currentPath.stringByDeletingLastPathComponent)") self.relaunch(relaunchPath!) } func relaunch(path:String) { NSUserDefaults.standardUserDefaults().setValue("{\"data\":false}", forKey: "update_available") println("Relaunching at \(path)...") NSTask.launchedTaskWithLaunchPath(path, arguments: [NSString(format: "%d", getpid())]) exit(0) } }
mit
d0a8ba70fc43e0b167539370985cdd73
32.404762
184
0.661597
4.505353
false
false
false
false
josefdolezal/iconic
Sources/IconicKit/parsers/IconsFontFileParser.swift
1
2561
// // File.swift // Iconic // // Created by Josef Dolezal on 17/05/2017. // // import Foundation import CoreText enum IconsFontFileParserError: Error { case cannotReadFont(URL) case scalarUndefined(Int) case glyphNotAccessible(UniChar) case unknownName(CGGlyph) } public final class IconsFontFileParser: IconParsing { private(set) public var familyName: String? = "" private(set) public var icons = [Icon]() public init() { } public func parseFile(atUrl url: URL) throws { guard let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL), let descriptor = (descriptors as? [CTFontDescriptor])?.first else { throw IconsFontFileParserError.cannotReadFont(url) } let ctFont = CTFontCreateWithFontDescriptorAndOptions(descriptor, 0.0, nil, [.preventAutoActivation]) familyName = CTFontCopyFamilyName(ctFont) as String icons = try extractGlyphs(fromFont: ctFont).sorted() { $0.name.compare($1.name) == .orderedAscending } } private func extractGlyphs(fromFont font: CTFont) throws -> [Icon] { let privateUseArea = 0xE000...0xF8FF let characterSet = CTFontCopyCharacterSet(font) let cgFont = CTFontCopyGraphicsFont(font, nil) // Examine all characters from Private Use Area (PUA) // Defined in https://en.wikipedia.org/wiki/Private_Use_Areas#Assignment return try privateUseArea.flatMap { unicode in guard let unicodeScalar = UnicodeScalar(unicode), let uniChar = UniChar(unicodeScalar.value) as UniChar? else { throw IconsFontFileParserError.scalarUndefined(unicode) } // Check if unicode character is member of charset if !CFCharacterSetIsCharacterMember(characterSet, uniChar) { return nil } var codePoint: [UniChar] = [uniChar] var glyphs: [CGGlyph] = [0, 0] // Gets the Glyph CTFontGetGlyphsForCharacters(font, &codePoint, &glyphs, 1) if glyphs.count == 0 { throw IconsFontFileParserError.glyphNotAccessible(uniChar) } // Gets the name of the Glyph, to be used as key guard let name = cgFont.name(for: glyphs[0]) else { throw IconsFontFileParserError.unknownName(glyphs[0]) } return Icon(name: name as String, unicode: String(format: "%X", unicode)) } } }
mit
6a484128aa1f455534f2aa49da8cdbf5
31.833333
110
0.62788
4.469459
false
false
false
false
IvanVorobei/TwitterLaunchAnimation
TwitterLaunchAnimation - project/TwitterLaucnhAnimation/sparrow/ui/views/collectionViews/layouts/SPPageItemsCollectionViewLayout.swift
1
6490
// // File.swift // ExchangeRates // // Created by Ivan Vorobei on 2/24/17. // Copyright © 2017 Ivan Vorobei. All rights reserved. // import UIKit class SPPageItemsCollectionViewLayout: UICollectionViewFlowLayout { var itemSpacingFactor: CGFloat = 0.11 var minItemSpace: CGFloat = 0 var maxItemSpace: CGFloat = 100 var scalingOffset: CGFloat = 200 var minimumAlphaFactor: CGFloat = 0.5 var minimumScaleFactor: CGFloat = 0.8 var yCenteringTranslation: CGFloat = 0 var cellSideRatio: CGFloat = 1 var maxWidth: CGFloat = 350 var widthFactor: CGFloat = 0.9 var maxHeight: CGFloat = 350 var heightFactor: CGFloat = 0.9 var scaleItems: Bool = false var pageWidth: CGFloat { get { return self.itemSize.width + self.minimumLineSpacing } } var pageHeight: CGFloat { get { return self.itemSize.height + self.minimumLineSpacing } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init() { super.init() scrollDirection = .horizontal } public override func targetContentOffset( forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { switch self.scrollDirection { case .horizontal: let rawPageValue = (self.collectionView!.contentOffset.x) / self.pageWidth let currentPage = (velocity.x > 0.0) ? floor(rawPageValue) : ceil(rawPageValue); let nextPage = (velocity.x > 0.0) ? ceil(rawPageValue) : floor(rawPageValue); let pannedLessThanAPage = fabs(1 + currentPage - rawPageValue) > 0.5; let flicked = fabs(velocity.x) > 0.3 var proposedContentOffset = proposedContentOffset if (pannedLessThanAPage && flicked) { proposedContentOffset.x = nextPage * self.pageWidth } else { proposedContentOffset.x = round(rawPageValue) * self.pageWidth } return proposedContentOffset; case .vertical: let rawPageValue = (self.collectionView!.contentOffset.y) / self.pageHeight let currentPage = (velocity.y > 0.0) ? floor(rawPageValue) : ceil(rawPageValue); let nextPage = (velocity.y > 0.0) ? ceil(rawPageValue) : floor(rawPageValue); let pannedLessThanAPage = fabs(1 + currentPage - rawPageValue) > 0.5; let flicked = fabs(velocity.y) > 0.3 var proposedContentOffset = proposedContentOffset if (pannedLessThanAPage && flicked) { proposedContentOffset.y = nextPage * self.pageHeight } else { proposedContentOffset.y = round(rawPageValue) * self.pageHeight } return proposedContentOffset; } } override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let collectionView = self.collectionView, let superAttributes = super.layoutAttributesForElements(in: rect) else { return super.layoutAttributesForElements(in: rect) } let contentOffset = collectionView.contentOffset let size = collectionView.bounds.size guard case let newAttributesArray as [UICollectionViewLayoutAttributes] = NSArray(array: superAttributes, copyItems: true) else { return nil } switch self.scrollDirection { case .horizontal: let visibleRect = CGRect.init(x: contentOffset.x, y: contentOffset.y, width: size.width, height: size.height) let visibleCenterX = visibleRect.midX newAttributesArray.forEach { let distanceFromCenter = visibleCenterX - $0.center.x let absDistanceFromCenter = min(abs(distanceFromCenter), self.scalingOffset) if self.scaleItems { let scale = absDistanceFromCenter * (self.minimumScaleFactor - 1) / self.scalingOffset + 1 $0.transform3D = CATransform3DScale(CATransform3DIdentity, scale, scale, 1) } let alpha = absDistanceFromCenter * (self.minimumAlphaFactor - 1) / self.scalingOffset + 1 $0.alpha = alpha } case .vertical: let visibleRect = CGRect.init(x: contentOffset.x, y: contentOffset.y, width: size.width, height: size.height) let visibleCenterY: CGFloat = visibleRect.midY + self.yCenteringTranslation for owner in newAttributesArray { let distanceFromCenter = visibleCenterY - owner.center.y let absDistanceFromCenter = min(abs(distanceFromCenter), self.scalingOffset) if self.scaleItems { let scale = absDistanceFromCenter * (self.minimumScaleFactor - 1) / self.scalingOffset + 1 owner.transform3D = CATransform3DScale(CATransform3DIdentity, scale, scale, 1) } let alpha = absDistanceFromCenter * (self.minimumAlphaFactor - 1) / self.scalingOffset + 1 owner.alpha = alpha } } return newAttributesArray } override public func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override public func prepare() { super.prepare() guard let collectionView = self.collectionView else { return } collectionView.decelerationRate = UIScrollViewDecelerationRateFast self.itemSize = SPLayout.sizeWith(widthFactor: self.widthFactor, maxWidth: self.maxWidth, heightFactor: self.heightFactor, maxHeight: self.maxHeight, relativeSideFactor: self.cellSideRatio, from: collectionView.bounds.size) switch self.scrollDirection { case .horizontal: self.minimumLineSpacing = collectionView.frame.width * itemSpacingFactor case .vertical: self.minimumLineSpacing = collectionView.frame.height * itemSpacingFactor } self.minimumLineSpacing.setIfMore(when: self.maxItemSpace) self.minimumLineSpacing.setIfFewer(when: self.minItemSpace) } }
mit
4fc8d1260498aa3b2e3687bbf7ccd27a
40.06962
231
0.620126
5.109449
false
false
false
false
liangbo707/LB-SwiftProject
LBPersonalApp/Main/SinaBlog/LBSinaBaseController.swift
1
1301
// // LBSinaBaseController.swift // LBPersonalApp // // Created by MR on 16/6/12. // Copyright © 2016年 LB. All rights reserved. // import UIKit class LBSinaBaseController: UITableViewController,LoginViewDelegate { var userLogin = LBUserAccount.isUserLogin var loginView : LBLoginView? //替换根试图要在loadView 里替换 override func loadView() { userLogin ? super.loadView() : setLoginView() } // MARK:登录视图 private func setLoginView() { loginView = LBLoginView() loginView?.delegate = self view = loginView //设置navBar navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: "visitorLoginButtonClicked") navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "visitorRegisterButtonClicked") } // MARK: 协议 func visitorRegisterButtonClicked() { print("注册") } func visitorLoginButtonClicked() { let oauthVc = LBSinaOAuthController() let nav = UINavigationController(rootViewController: oauthVc) presentViewController(nav, animated: true, completion: nil) } }
apache-2.0
c01b12a19ec4048d51d61aaf732c236d
28.761905
160
0.6768
4.699248
false
false
false
false
gabemdev/GMDKit
GMDKit/Classes/UICollectionView+GMDKit.swift
1
5576
// // UICollectionViewUtils.swift // Pods // // Created by Gabriel Morales on 3/7/17. // // import UIKit // MARK: Reusable support for UICollectionView public extension UICollectionView { /** Register a NIB-Based `UICollectionViewCell` subclass (conforming to `Reusable` & `NibLoadable`) - parameter cellType: the `UICollectionViewCell` (`Reusable` & `NibLoadable`-conforming) subclass to register - seealso: `register(_:,forCellWithReuseIdentifier:)` */ final func register<T: UICollectionViewCell>(cellType: T.Type) where T: Reusable & NibLoadable { self.register(cellType.nib, forCellWithReuseIdentifier: cellType.reuseIdentifier) } /** Register a Class-Based `UICollectionViewCell` subclass (conforming to `Reusable`) - parameter cellType: the `UICollectionViewCell` (`Reusable`-conforming) subclass to register - seealso: `register(_:,forCellWithReuseIdentifier:)` */ final func register<T: UICollectionViewCell>(cellType: T.Type) where T: Reusable { self.register(cellType.self, forCellWithReuseIdentifier: cellType.reuseIdentifier) } /** Returns a reusable `UICollectionViewCell` object for the class inferred by the return-type - parameter indexPath: The index path specifying the location of the cell. - parameter cellType: The cell class to dequeue - returns: A `Reusable`, `UICollectionViewCell` instance - note: The `cellType` parameter can generally be omitted and infered by the return type, except when your type is in a variable and cannot be determined at compile time. - seealso: `dequeueReusableCell(withReuseIdentifier:,for:)` */ final func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath, cellType: T.Type = T.self) -> T where T: Reusable { let bareCell = self.dequeueReusableCell(withReuseIdentifier: cellType.reuseIdentifier, for: indexPath) guard let cell = bareCell as? T else { fatalError( "Failed to dequeue a cell with identifier \(cellType.reuseIdentifier) matching type \(cellType.self). " + "Check that the reuseIdentifier is set properly in your XIB/Storyboard " + "and that you registered the cell beforehand" ) } return cell } /** Register a NIB-Based `UICollectionReusableView` subclass (conforming to `Reusable` & `NibLoadable`) as a Supplementary View - parameter supplementaryViewType: the `UIView` (`Reusable` & `NibLoadable`-conforming) subclass to register as Supplementary View - parameter elementKind: The kind of supplementary view to create. - seealso: `register(_:,forSupplementaryViewOfKind:,withReuseIdentifier:)` */ final func register<T: UICollectionReusableView>(supplementaryViewType: T.Type, ofKind elementKind: String) where T: Reusable & NibLoadable { self.register( supplementaryViewType.nib, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: supplementaryViewType.reuseIdentifier ) } /** Register a Class-Based `UICollectionReusableView` subclass (conforming to `Reusable`) as a Supplementary View - parameter supplementaryViewType: the `UIView` (`Reusable`-conforming) subclass to register as Supplementary View - parameter elementKind: The kind of supplementary view to create. - seealso: `register(_:,forSupplementaryViewOfKind:,withReuseIdentifier:)` */ final func register<T: UICollectionReusableView>(supplementaryViewType: T.Type, ofKind elementKind: String) where T: Reusable { self.register( supplementaryViewType.self, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: supplementaryViewType.reuseIdentifier ) } /** Returns a reusable `UICollectionReusableView` object for the class inferred by the return-type - parameter elementKind: The kind of supplementary view to retrieve. - parameter indexPath: The index path specifying the location of the cell. - parameter viewType: The view class to dequeue - returns: A `Reusable`, `UICollectionReusableView` instance - note: The `viewType` parameter can generally be omitted and infered by the return type, except when your type is in a variable and cannot be determined at compile time. - seealso: `dequeueReusableSupplementaryView(ofKind:,withReuseIdentifier:,for:)` */ final func dequeueReusableSupplementaryView<T: UICollectionReusableView> (ofKind elementKind: String, for indexPath: IndexPath, viewType: T.Type = T.self) -> T where T: Reusable { let view = self.dequeueReusableSupplementaryView( ofKind: elementKind, withReuseIdentifier: viewType.reuseIdentifier, for: indexPath ) guard let typedView = view as? T else { fatalError( "Failed to dequeue a supplementary view with identifier \(viewType.reuseIdentifier) " + "matching type \(viewType.self). " + "Check that the reuseIdentifier is set properly in your XIB/Storyboard " + "and that you registered the supplementary view beforehand" ) } return typedView } }
mit
417ceaca7bb14168fca0c17a32bc25f9
47.486957
123
0.667504
5.620968
false
false
false
false
bermudadigitalstudio/Redshot
Sources/RedShot/RedisCommands.swift
1
9524
// // This source file is part of the RedShot open source project // // Copyright (c) 2017 Bermuda Digital Studio // Licensed under MIT // // See https://github.com/bermudadigitalstudio/Redshot/blob/master/LICENSE for license information // // Created by Laurent Gaches on 13/06/2017. // import Foundation extension Redis { /// Request for authentication in a password-protected Redis server. /// /// - Parameter password: The password. /// - Returns: OK status code ( Simple String) /// - Throws: if the password no match public func auth(password: String) throws -> RedisType { return try sendCommand("AUTH", values: [password]) } /// Request for authentication in a password-protected Redis server. /// /// - Parameter password: The password. /// - Returns: true if the password match, otherwise false /// - Throws: any other errors public func auth(password: String) throws -> Bool { do { let response: RedisType = try self.auth(password: password) guard let resp = response as? String else { return false } return resp == "OK" } catch RedisError.response { return false } } /// Posts a message to the given channel. /// /// - Parameters: /// - channel: The channel. /// - message: The message. /// - Returns: The number of clients that received the message. /// - Throws: something bad happened. public func publish(channel: String, message: String) throws -> RedisType { return try sendCommand("PUBLISH", values: [channel, message]) } /// Get the value of a key. /// /// - Parameter key: The key. /// - Returns: the value of key, or NSNull when key does not exist. /// - Throws: something bad happened. public func get(key: String) throws -> RedisType { return try sendCommand("GET", values: [key]) } /// Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. /// Any previous time to live associated with the key is discarded on successful SET operation. /// /// - Parameters: /// - key: The key. /// - value: The value to set /// - exist: if true Only set the key if it already exist. if false Only set the key if it does not already exist. /// - expire: If not nil, set the specified expire time, in milliseconds. /// - Returns: A simple string reply OK if SET was executed correctly. /// - Throws: something bad happened. public func set(key: String, value: String, exist: Bool? = nil, expire: TimeInterval? = nil) throws -> RedisType { var cmd = [key, value] if let exist = exist { cmd.append(exist ? "XX" : "NX") } if let expire = expire { cmd.append("PX \(Int(expire * 1000.0))") } return try sendCommand("SET", values: cmd) } /// Add the specified members to the set stored at key. /// Specified members that are already a member of this set are ignored. /// If key does not exist, a new set is created before adding the specified members. /// An error is returned when the value stored at key is not a set. /// /// - Parameters: /// - key: The key. /// - values: The values /// - Returns: Integer reply - the number of elements that were added to the set, /// not including all the elements already present into the set. /// - Throws: a RedisError. public func sadd(key: String, values: String...) throws -> RedisType { var vals = [key] vals.append(contentsOf: values) return try sendCommand("SADD", values: vals) } /// Returns all the members of the set value stored at key. /// /// - Parameter key: The keys. /// - Returns: Array reply - all elements of the set. /// - Throws: a RedisError. public func smbembers(key: String) throws -> RedisType { return try sendCommand("SMEMBERS", values: [key]) } /// Insert all the specified values at the head of the list stored at key. /// If key does not exist, it is created as empty list before performing the push operations. /// When key holds a value that is not a list, an error is returned. /// /// It is possible to push multiple elements using a single command call just specifying multiple arguments /// at the end of the command. Elements are inserted one after the other to the head of the list, /// from the leftmost element to the rightmost element. /// So for instance the command LPUSH mylist a b c will result into a list containing c as first element, /// b as second element and a as third element. /// /// - Parameters: /// - key: The key. /// - values: the values /// - Returns: Integer reply - the length of the list after the push operations. /// - Throws: a RedisError. public func lpush(key: String, values: String...) throws -> RedisType { var vals = [key] vals.append(contentsOf: values) return try sendCommand("LPUSH", values: vals) } /// Removes and returns the first element of the list stored at key. /// /// - Parameter key: The key. /// - Returns: Bulk string reply - the value of the first element, or nil when key does not exist. /// - Throws: a RedisError. public func lpop(key: String) throws -> RedisType { return try sendCommand("LPOP", values: [key]) } /// The CLIENT SETNAME command assigns a name to the current connection. /// The assigned name is displayed in the output of CLIENT LIST /// so that it is possible to identify the client that performed a given connection. /// /// - Parameter clientName: the name to assign /// - Returns: Simple string reply - OK if the connection name was successfully set. /// - Throws: a RedisError public func clientSetName(clientName: String) throws -> RedisType { return try sendCommand("CLIENT", values: ["SETNAME", clientName]) } /// Increments the number stored at key by one. /// If the key does not exist, it is set to 0 before performing the operation. /// An error is returned if the key contains a value of the wrong type /// or contains a string that can not be represented as integer. /// This operation is limited to 64 bit signed integers. /// Note: this is a string operation because Redis does not have a dedicated integer type. /// The string stored at the key is interpreted as a base-10 64 bit signed integer to execute the operation. /// Redis stores integers in their integer representation, so for string values that actually hold an integer, /// there is no overhead for storing the string representation of the integer. /// /// - Parameter key: The key. /// - Returns: Integer reply - the value of key after the increment /// - Throws: a RedisError public func incr(key: String) throws -> RedisType { return try sendCommand("INCR", values: [key]) } /// Select the Redis logical database having the specified zero-based numeric index. /// New connections always use the database 0. /// /// - Parameter databaseIndex: the index to select. /// - Returns: A simple string reply OK if SELECT was executed correctly. /// - Throws: a RedisError. public func select(databaseIndex: Int) throws -> RedisType { return try sendCommand("SELECT", values: ["\(databaseIndex)"]) } /// Sets field in the hash stored at key to value. /// If key does not exist, a new key holding a hash is created. /// If field already exists in the hash, it is overwritten. /// /// - Parameters: /// - key: The key. /// - field: The field in the hash. /// - value: The value to set. /// - Returns: Integer reply, specifically: /// 1 if field is a new field in the hash and value was set. /// 0 if field already exists in the hash and the value was updated. /// - Throws: a RedisError public func hset(key: String, field: String, value: String) throws -> RedisType { return try sendCommand("HSET", values: [key, field, value]) } /// Returns the value associated with `field` in the hash stored at `key`. /// /// - Parameters: /// - key: The key. /// - field: The field in the hash /// - Returns: Bulk string reply: the value associated with field, or nil when field is not present in the hash /// or key does not exist. /// - Throws: a RedisError public func hget(key: String, field: String) throws -> RedisType { return try sendCommand("HGET", values: [key, field]) } /// Returns all fields and values of the hash stored at key. /// /// - Parameter key: The key. /// - Returns: a dictionary. /// - Throws: a RedisError public func hgetAll(key: String) throws -> [String: String] { var dictionary: [String: String] = [:] if let result = try sendCommand("HGETALL", values: [key]) as? Array<String> { let tuples = stride(from: 0, to: result.count, by: 2).map { num in return (result[num], result[num + 1]) } for (key, value) in tuples { dictionary[key] = value } return dictionary } else { throw RedisError.emptyResponse } } }
mit
6a10271cf02360477b8649c1c4d0db22
40.77193
120
0.626312
4.344891
false
false
false
false
per-dalsgaard/20-apps-in-20-weeks
App 16 - Devslopes Social/Devslopes Social/DropShadowView.swift
1
551
// // DropShadowView.swift // Devslopes Social // // Created by Per Kristensen on 24/04/2017. // Copyright © 2017 Per Dalsgaard. All rights reserved. // import UIKit class DropShadowView: UIView { override func awakeFromNib() { super.awakeFromNib() layer.shadowColor = UIColor(red: SHADOW_GREY, green: SHADOW_GREY, blue: SHADOW_GREY, alpha: 1).cgColor layer.shadowOpacity = 0.8 layer.shadowOffset = CGSize(width: 1, height: 1) layer.shadowRadius = 5 layer.cornerRadius = 2 } }
mit
6ce4170337dfc912754b7d5d1fc72c55
22.913043
110
0.645455
3.793103
false
false
false
false
alisidd/iOS-WeJ
Pods/NVActivityIndicatorView/Source/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationCubeTransition.swift
1
4052
// // NVActivityIndicatorAnimationCubeTransition.swift // NVActivityIndicatorView // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // 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 NVActivityIndicatorAnimationCubeTransition: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let squareSize = size.width / 5 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let deltaX = size.width - squareSize let deltaY = size.height - squareSize let duration: CFTimeInterval = 1.6 let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [0, -0.8] let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.25, 0.5, 0.75, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction, timingFunction, timingFunction] scaleAnimation.values = [1, 0.5, 1, 0.5, 1] scaleAnimation.duration = duration // Translate animation let translateAnimation = CAKeyframeAnimation(keyPath: "transform.translation") translateAnimation.keyTimes = scaleAnimation.keyTimes translateAnimation.timingFunctions = scaleAnimation.timingFunctions translateAnimation.values = [ NSValue(cgSize: CGSize(width: 0, height: 0)), NSValue(cgSize: CGSize(width: deltaX, height: 0)), NSValue(cgSize: CGSize(width: deltaX, height: deltaY)), NSValue(cgSize: CGSize(width: 0, height: deltaY)), NSValue(cgSize: CGSize(width: 0, height: 0)) ] translateAnimation.duration = duration // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.timingFunctions = scaleAnimation.timingFunctions rotateAnimation.values = [0, -Double.pi / 2, -Double.pi, -1.5 * Double.pi, -2 * Double.pi] rotateAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, translateAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw squares for i in 0 ..< 2 { let square = NVActivityIndicatorShape.rectangle.layerWith(size: CGSize(width: squareSize, height: squareSize), color: color) let frame = CGRect(x: x, y: y, width: squareSize, height: squareSize) animation.beginTime = beginTime + beginTimes[i] square.frame = frame square.add(animation, forKey: "animation") layer.addSublayer(square) } } }
gpl-3.0
38903be8fbafbf60f2ea42d95b384b70
43.043478
136
0.693978
4.941463
false
false
false
false
practicalswift/swift
validation-test/Reflection/reflect_Float.swift
13
1739
// RUN: %empty-directory(%t) // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Float // RUN: %target-codesign %t/reflect_Float // RUN: %target-run %target-swift-reflection-test %t/reflect_Float | %FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop // REQUIRES: executable_test import SwiftReflectionTest class TestClass { var t: Float init(t: Float) { self.t = t } } var obj = TestClass(t: 123.45) reflect(object: obj) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_Float.TestClass) // CHECK-64: Type info: // CHECK-64: (class_instance size=20 alignment=4 stride=20 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=t offset=16 // CHECK-64: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))) // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_Float.TestClass) // CHECK-32: Type info: // CHECK-32: (class_instance size=12 alignment=4 stride=12 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=t offset=8 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
apache-2.0
706330f4e66ac1f566cf99de9ff6d7a5
33.098039
119
0.691777
3.122083
false
true
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/ObjectMapper/Sources/IntegerOperators.swift
18
4913
// // IntegerOperators.swift // ObjectMapper // // Created by Suyeol Jeon on 17/02/2017. // // The MIT License (MIT) // // Copyright (c) 2014-2018 Tristan Himmelman // // 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 // MARK: - Signed Integer /// SignedInteger mapping public func <- <T: SignedInteger>(left: inout T, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: let value: T = toSignedInteger(right.currentValue) ?? 0 FromJSON.basicType(&left, object: value) case .toJSON: left >>> right default: () } } /// Optional SignedInteger mapping public func <- <T: SignedInteger>(left: inout T?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: let value: T? = toSignedInteger(right.currentValue) FromJSON.basicType(&left, object: value) case .toJSON: left >>> right default: () } } // Code targeting the Swift 4.1 compiler and below. #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) /// ImplicitlyUnwrappedOptional SignedInteger mapping public func <- <T: SignedInteger>(left: inout T!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: let value: T! = toSignedInteger(right.currentValue) FromJSON.basicType(&left, object: value) case .toJSON: left >>> right default: () } } #endif // MARK: - Unsigned Integer /// UnsignedInteger mapping public func <- <T: UnsignedInteger>(left: inout T, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: let value: T = toUnsignedInteger(right.currentValue) ?? 0 FromJSON.basicType(&left, object: value) case .toJSON: left >>> right default: () } } /// Optional UnsignedInteger mapping public func <- <T: UnsignedInteger>(left: inout T?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: let value: T? = toUnsignedInteger(right.currentValue) FromJSON.basicType(&left, object: value) case .toJSON: left >>> right default: () } } // Code targeting the Swift 4.1 compiler and below. #if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))) /// ImplicitlyUnwrappedOptional UnsignedInteger mapping public func <- <T: UnsignedInteger>(left: inout T!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: let value: T! = toUnsignedInteger(right.currentValue) FromJSON.basicType(&left, object: value) case .toJSON: left >>> right default: () } } #endif // MARK: - Casting Utils /// Convert any value to `SignedInteger`. private func toSignedInteger<T: SignedInteger>(_ value: Any?) -> T? { guard let value = value, case let number as NSNumber = value else { return nil } if T.self == Int.self, let x = Int(exactly: number.int64Value) { return T.init(x) } if T.self == Int8.self, let x = Int8(exactly: number.int64Value) { return T.init(x) } if T.self == Int16.self, let x = Int16(exactly: number.int64Value) { return T.init(x) } if T.self == Int32.self, let x = Int32(exactly: number.int64Value) { return T.init(x) } if T.self == Int64.self, let x = Int64(exactly: number.int64Value) { return T.init(x) } return nil } /// Convert any value to `UnsignedInteger`. private func toUnsignedInteger<T: UnsignedInteger>(_ value: Any?) -> T? { guard let value = value, case let number as NSNumber = value else { return nil } if T.self == UInt.self, let x = UInt(exactly: number.uint64Value) { return T.init(x) } if T.self == UInt8.self, let x = UInt8(exactly: number.uint64Value) { return T.init(x) } if T.self == UInt16.self, let x = UInt16(exactly: number.uint64Value) { return T.init(x) } if T.self == UInt32.self, let x = UInt32(exactly: number.uint64Value) { return T.init(x) } if T.self == UInt64.self, let x = UInt64(exactly: number.uint64Value) { return T.init(x) } return nil }
mit
10574cac0743bcc5012422860a3ad6d0
27.730994
81
0.69998
3.342177
false
false
false
false
linkedin/LayoutKit
LayoutKitSampleApp/FeedBaseViewController.swift
6
1572
// Copyright 2016 LinkedIn Corp. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import UIKit import LayoutKit import ExampleLayouts /// A base class for various view controllers that display a fake feed. class FeedBaseViewController: UIViewController { private var cachedFeedItems: [Layout]? func getFeedItems() -> [Layout] { if let cachedFeedItems = cachedFeedItems { return cachedFeedItems } let profileCard = ProfileCardLayout( name: "Nick Snyder", connectionDegree: "1st", headline: "Software Engineer at LinkedIn", timestamp: "5 minutes ago", profileImageName: "50x50" ) let content = ContentLayout(title: "Chuck Norris", domain: "chucknorris.com") let feedItem = FeedItemLayout( actionText: "Sergei Tauger commented on this", posterProfile: profileCard, posterComment: "Check it out", contentLayout: content, actorComment: "Awesome!" ) let feedItems = [Layout](repeating: feedItem, count: 1000) cachedFeedItems = feedItems return feedItems } }
apache-2.0
da9287dcd8836b60792769095fa73f72
33.933333
131
0.660941
4.569767
false
false
false
false
Caiflower/SwiftWeiBo
花菜微博/花菜微博/Classes/Tools(工具)/CFAddition(Swift)/Foundation/Array-Addition.swift
1
741
// // Array-Addition.swift // 花菜微博 // // Created by 花菜ChrisCai on 2016/12/5. // Copyright © 2016年 花菜ChrisCai. All rights reserved. // import Foundation extension Array { // 将数组随机打乱 var randomArray: Array { var tmp = self var count = tmp.count while (count > 0) { // 获取随机角标 let index = (Int)(arc4random_uniform((UInt32)(count - 1))) // 获取角标对应的值 let value = tmp[index] // 交换数组元素位置 tmp[index] = tmp[count - 1] tmp[count - 1] = value count -= 1 } // 返回打乱顺序之后的数组 return tmp } }
apache-2.0
9a3ba51d3c5fa70b56662958fbd38a26
19.709677
70
0.496885
3.48913
false
false
false
false
heigong/Shared
iOS/UIRefreshControlDemo/UIRefreshControlDemo/MyTableViewController.swift
1
1749
// // MyTableViewController.swift // UIRefreshControlDemo // // Created by Di Chen on 8/5/15. // Copyright (c) 2015 Di Chen. All rights reserved. // import Foundation import UIKit class MyTableViewController: UITableViewController { //var freshControl: UIRefreshControl! var items: [NSDate]! override func viewDidLoad() { super.viewDidLoad() items = [NSDate]() refreshControl = UIRefreshControl() refreshControl!.addTarget(self, action: "handleRefresh:", forControlEvents: .ValueChanged) tableView.addSubview(refreshControl!) } func handleRefresh(sender: UIRefreshControl){ let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC)) dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in self.items.append(NSDate()) self.refreshControl!.endRefreshing() let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items!.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell var index = items.count - 1 - Int(indexPath.row) cell.textLabel!.text = "\(items[index])" return cell } }
mit
bf05d43700224726c54c1a5fdb7af6b6
29.172414
118
0.632361
5.283988
false
false
false
false
silence0201/Swift-Study
Note/Day 01/08-逻辑分支(switch的使用).playground/Contents.swift
2
1715
//: Playground - noun: a place where people can play import UIKit /* 1.switch的基本使用 1> switch()可以省略 2> case结束可以不加break 2.基本使用补充 1> case后面可以跟上多个条件 2> 如果希望产生case穿透,可以在case结束时fallthrough 3.可以判断多种类型 1> 浮点型 2> 字符串 3> 区间类型 */ // 1.switch基本使用 /* 和OC的区别 1> switch后面的()可以省略 2> case语句结束时,可以不加break */ let sex = 1 // sex 0 : 男 1 : 女 switch sex { case 0: print("男") case 1: print("女") default: print("其它") } // 2.基本用法补充 // 1> 在swift中,switch后面case可以判断多个条件 // 2> 如果希望case结束时,产生case穿透.case结束时,加上fallthrough switch sex { case 0, 1: print("正常人") fallthrough default: print("非正常人") } // 3.switch判断其它类型 // 3.1.判断浮点型 let m = 3.14 switch m { case 3.14: print("和π相等") default: print("和π不相等") } // 3.2.判断字符串 let a = 20 let b = 30 let oprationStr = "*" var result = 0 switch oprationStr { case "+": result = a + b case "-": result = a - b case "*": result = a * b case "/": result = a / b default: print("不合理的操作符") } // 3.3.判断区间类型 /* 区间 1> 半开半闭区间 0~9 0..<10 2> 闭区间 0~9 0...9 错误写法 1~9 0<.<10 正确写法 1~9 1..9/1..<10 */ let score = 88 switch score { case 0..<60: print("不及格") case 60..<80: print("及格") case 80..<90: print("良好") case 90...100: print("优秀") default: print("不合理的分数") }
mit
cc6cc7730312c31a8a14b72c9f3624c0
11.196262
52
0.570115
2.39011
false
false
false
false
ashfurrow/FunctionalReactiveAwesome
Pods/RxSwift/RxSwift/RxSwift/Observables/Implementations/Sample.swift
2
3562
// // Sample.swift // RxSwift // // Created by Krunoslav Zaher on 5/1/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class SampleImpl_<O: ObserverType, ElementType, SampleType where O.Element == ElementType> : Observer<SampleType> { typealias Parent = Sample_<O, SampleType> let parent: Parent init(parent: Parent) { self.parent = parent } override func on(event: Event<Element>) { parent.lock.performLocked { switch event { case .Next: if let element = parent.sampleState.element { if self.parent.parent.onlyNew { parent.sampleState.element = nil } trySend(parent.observer, element) } if parent.sampleState.atEnd { trySendCompleted(parent.observer) parent.dispose() } case .Error(let e): trySendError(parent.observer, e) parent.dispose() case .Completed: if let element = parent.sampleState.element { parent.sampleState.element = nil trySend(parent.observer, element) } if parent.sampleState.atEnd { trySendCompleted(parent.observer) parent.dispose() } } } } } class Sample_<O: ObserverType, SampleType> : Sink<O>, ObserverType { typealias Element = O.Element typealias Parent = Sample<Element, SampleType> typealias SampleState = ( element: Event<Element>?, atEnd: Bool, sourceSubscription: SingleAssignmentDisposable ) let parent: Parent var lock = NSRecursiveLock() var sampleState: SampleState = ( element: nil, atEnd: false, sourceSubscription: SingleAssignmentDisposable() ) init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { sampleState.sourceSubscription.setDisposable(parent.source.subscribe(self)) let samplerSubscription = parent.sampler.subscribe(SampleImpl_(parent: self)) return CompositeDisposable(sampleState.sourceSubscription, samplerSubscription) } func on(event: Event<Element>) { self.lock.performLocked { switch event { case .Next: self.sampleState.element = event case .Error: trySend(observer, event) self.dispose() case .Completed: self.sampleState.atEnd = true self.sampleState.sourceSubscription.dispose() } } } } class Sample<Element, SampleType> : Producer<Element> { let source: Observable<Element> let sampler: Observable<SampleType> let onlyNew: Bool init(source: Observable<Element>, sampler: Observable<SampleType>, onlyNew: Bool) { self.source = source self.sampler = sampler self.onlyNew = onlyNew } override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = Sample_(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } }
mit
eb1a50082af5530dc1435db3f76b0c90
29.452991
145
0.567097
5.002809
false
false
false
false
hollance/swift-algorithm-club
Knuth-Morris-Pratt/KnuthMorrisPratt.swift
2
1720
/* Knuth-Morris-Pratt algorithm for pattern/string matching The code is based on the book: "Algorithms on String, Trees and Sequences: Computer Science and Computational Biology" by Dan Gusfield Cambridge University Press, 1997 */ import Foundation extension String { func indexesOf(ptnr: String) -> [Int]? { let text = Array(self) let pattern = Array(ptnr) let textLength: Int = text.count let patternLength: Int = pattern.count guard patternLength > 0 else { return nil } var suffixPrefix: [Int] = [Int](repeating: 0, count: patternLength) var textIndex: Int = 0 var patternIndex: Int = 0 var indexes: [Int] = [Int]() /* Pre-processing stage: computing the table for the shifts (through Z-Algorithm) */ let zeta = ZetaAlgorithm(ptnr: ptnr) for patternIndex in (1 ..< patternLength).reversed() { textIndex = patternIndex + zeta![patternIndex] - 1 suffixPrefix[textIndex] = zeta![patternIndex] } /* Search stage: scanning the text for pattern matching */ textIndex = 0 patternIndex = 0 while textIndex + (patternLength - patternIndex - 1) < textLength { while patternIndex < patternLength && text[textIndex] == pattern[patternIndex] { textIndex = textIndex + 1 patternIndex = patternIndex + 1 } if patternIndex == patternLength { indexes.append(textIndex - patternIndex) } if patternIndex == 0 { textIndex = textIndex + 1 } else { patternIndex = suffixPrefix[patternIndex - 1] } } guard !indexes.isEmpty else { return nil } return indexes } }
mit
388cd5fd70cba330c4f2db2838d95bcb
25.461538
88
0.625581
4.215686
false
false
false
false
DzinVision/GimVic-iOS
GimVic/SetupMalicaViewController.swift
2
1438
// // SetupMalicaViewController.swift // GimVic // // Created by Vid Drobnič on 9/21/16. // Copyright © 2016 Vid Drobnič. All rights reserved. // import UIKit import GimVicData class SetupMalicaViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var malicaPickerView: UIPickerView! func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return ChooserData.sharedInstance.snackTypes.count } func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { let title = ChooserData.sharedInstance.snackTypes[row] .replacingOccurrences(of: "_", with: " ") .capitalized return NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIColor.white]) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let identifier = segue.identifier { if identifier == "nextSegue" { let selected = ChooserData.sharedInstance.snackTypes[malicaPickerView.selectedRow(inComponent: 0)] UserDefaults().set(selected, forKey: UserSettings.snack.rawValue) } } } }
mit
c3ff85fa3a18123758f45879825561be
34
114
0.664808
5.017483
false
false
false
false
CodePath2017Group4/travel-app
RoadTripPlanner/BusinessBottomSheetViewController.swift
1
17660
// // BussinessBottomSheetViewController.swift // RoadTripPlanner // // Created by Deepthy on 10/24/17. // Copyright © 2017 Deepthy. All rights reserved. // import UIKit import YelpAPI import CDYelpFusionKit import MapKit import Parse class BusinessBottomSheetViewController: UIViewController { // holdView can be UIImageView instead @IBOutlet weak var holdView: UIView! //@IBOutlet weak var left: UIButton! @IBOutlet weak var right: UIButton! @IBOutlet weak var businessImage: UIImageView! @IBOutlet weak var businessNameLabel: UILabel! @IBOutlet weak var displayAddr1: UILabel! @IBOutlet weak var displayAddr2: UILabel! @IBOutlet weak var reviewImage: UIImageView! @IBOutlet weak var reviewCountLabel: UILabel! @IBOutlet weak var ratingsCountLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var ratingTotalLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var addPriceSymbolLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! let fullView: CGFloat = 100 @IBOutlet weak var phoneLabel: UILabel! @IBOutlet weak var openNowLabel: UILabel! var business: CDYelpBusiness! var businesses: [CDYelpBusiness]! override func viewDidLoad() { super.viewDidLoad() registerForNotifications() if business != nil { if business.name != nil { businessNameLabel.text = "\((business?.name)!)" } if let reviewCount = business?.reviewCount { if (reviewCount == 1) { reviewCountLabel.text = "\(reviewCount) \(Constants.BusinessLabels.reviewLabel)" } else { reviewCountLabel.text = "\(reviewCount) \(Constants.BusinessLabels.reviewsLabel)" } } self.right.addTarget(self, action: #selector(DetailViewController().onTripAdd), for: .touchDown) //self.right.addTarget(self, action: #selector(self.onSavePlace), for: .allTouchEvents) if let businessImageUrl = business.imageUrl { // imageView?.setImageWith(businessImageUrl) let backgroundImageView = UIImageView() let backgroundImage = UIImage() backgroundImageView.setImageWith(businessImageUrl) businessImage.image = backgroundImageView.image//setImageWith(businessImageUrl) businessImage.contentMode = .scaleAspectFill businessImage.clipsToBounds = true } if let bussinessAddr = business.location?.displayAddress { displayAddr1.text = bussinessAddr[0] displayAddr2.text = bussinessAddr[1] } if let bussinessAddr = business.location?.addressOne { print("bussinessAddr \(bussinessAddr)") print("bussinessAddr2 \(business.location?.addressTwo)") print("bussinessAddr3 \(business.location?.addressThree)") print("bussinessAddr \(business.location?.displayAddress?.count)") for da in (business.location?.displayAddress)! { print("da \(da)") } } if let phone = business.displayPhone { phoneLabel.text = "\(phone)" print("display phone \(business.displayPhone)") } if let price = business.price { var nDollar = price.count var missingDollar = 4-nDollar var labelDollar = "$" var mPrice = "" for i in 0..<missingDollar { mPrice += labelDollar } priceLabel.text = "\(price)" addPriceSymbolLabel.text = "\(mPrice)" } else { priceLabel.isHidden = true addPriceSymbolLabel.isHidden = true } //print("business.distance \(business.distance)") if let distance = business.distance { var distInMiles = Double.init(distance as! NSNumber) * 0.000621371 distanceLabel.text = String(format: "%.2f", distInMiles) } if let closed = business.isClosed { ///openNowLabel.textColor = closed ? UIColor.red : UIColor.green openNowLabel.text = closed ? "Closed" : "Open" if !closed { if let hours = business.hours { } } if let photos = business.photos { for p in photos { print("photos \(p)") } } if let hours = business.hours { let date = Date() let calendar = Calendar.current let dayOfWeek = calendar.component(.weekday, from: date) for hour in hours { let textLabel = UILabel() textLabel.textColor = hour.isOpenNow! ? UIColor.green : UIColor.red textLabel.text = hour.isOpenNow! ? "Open" : "Closed" let hourOpen = hour.open let textLabelExt = UILabel() textLabelExt.text = "" for day in hourOpen! { if (dayOfWeek-1) == day.day! { print("hours end \(day.end)") var timeString = day.end as! String timeString.insert(":", at: (timeString.index((timeString.startIndex), offsetBy: 2))) print("timeString \(timeString)") /* let dateAsString = timeString let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" let hourClose = dateFormatter.date(from: dateAsString) print("hourClose \(hourClose)") dateFormatter.dateFormat = "h:mm a" let date12 = dateFormatter.string(from: date) //let hourClose = day.end!*/ textLabelExt.text = hour.isOpenNow! ? " untill \(amAppend(str: timeString))" : "" } } openNowLabel.text = "\(textLabel.text!) \(textLabelExt.text!)" print("dayOfWeek\(dayOfWeek)") if hour.isOpenNow! { /// if let hours = business.hours { //} for h in hours { print("hours \(h.hoursType)") print("hours \(h.isOpenNow)") print("hours \(h.open)") for ho in h.open! { print("hours \(ho.day)") print("hours \(ho.end)") print("hours \(ho.isOvernight)") print("hours \(ho.toJSONString())") } } } } } if let ratingsCount = business.rating { if ratingsCount == 0 { reviewImage.image = UIImage(named: "0star") } else if ratingsCount > 0 && ratingsCount <= 1 { reviewImage.image = UIImage(named: "1star") } else if ratingsCount > 1 && ratingsCount <= 1.5 { reviewImage.image = UIImage(named: "1halfstar") } else if ratingsCount > 1.5 && ratingsCount <= 2 { reviewImage.image = UIImage(named: "2star") } else if ratingsCount > 2 && ratingsCount <= 2.5 { reviewImage.image = UIImage(named: "2halfstar") } else if ratingsCount > 2.5 && ratingsCount <= 3 { reviewImage.image = UIImage(named: "3star") } else if ratingsCount > 3 && ratingsCount <= 3.5 { reviewImage.image = UIImage(named: "3halfstar") } else if ratingsCount > 3.5 && ratingsCount <= 4 { reviewImage.image = UIImage(named: "4star") } else if ratingsCount > 4 && ratingsCount <= 4.5 { reviewImage.image = UIImage(named: "4halfstar") } else { reviewImage.image = UIImage(named: "5star") } if !(ratingsCount.isLess(than: 4.0)) { ratingsCountLabel.backgroundColor = UIColor(red: 39/255, green: 190/255, blue: 73/255, alpha: 1) ratingTotalLabel.backgroundColor = UIColor(red: 39/255, green: 190/255, blue: 73/255, alpha: 1) } else if !(ratingsCount.isLess(than: 3.0)) && (ratingsCount.isLess(than: 4.0)) { ratingsCountLabel.backgroundColor = UIColor.orange ratingTotalLabel.backgroundColor = UIColor.orange } else { ratingsCountLabel.backgroundColor = UIColor.yellow ratingTotalLabel.backgroundColor = UIColor.yellow } let labelString = UILabel() labelString.font = UIFont.boldSystemFont(ofSize: 5) labelString.text = "5" ratingsCountLabel.text = "\(business.rating!)" + " / " //+ labelString.text! } } } // roundViews() } func amAppend(str:String) -> String{ var temp = str var strArr = str.characters.split{$0 == ":"}.map(String.init) var hour = Int(strArr[0])! var min = Int(strArr[1])! if(hour > 12){ temp = temp + " PM" } else{ temp = temp + " AM" } return temp } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) prepareBackgroundView() self.loadViewIfNeeded() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIView.animate(withDuration: 0.6, animations: { [weak self] in let frame = self?.view.frame // let yComponent = self?.partialView // self?.view.frame = CGRect(x: 0, y: yComponent!, width: frame!.width, height: frame!.height) }) } func registerForNotifications() { // Register to receive Businesses NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "BussinessUpdate"), object: nil, queue: OperationQueue.main) { [weak self] (notification: Notification) in self?.business = notification.userInfo!["business"] as! CDYelpBusiness //self?.addAnnotationFor(businesses: (self?.businesses)!) print("self?.business id in nitofocation \(self?.business.id)") print("self?.business photod in nitofocation \(self?.business.photos?.count)") self?.view.setNeedsDisplay() //self?.tableView.reloadData() //self?.collectionView.reloadData() //self?.mapView.reloadInputViews() } } // @IBAction func onAddRemoveTrip(_ sender: Any) { print("onAddRemoveTrip") let storyboard = UIStoryboard(name: "Main", bundle: nil) print("businesses \(businesses)") if(businesses == nil) { let createTripViewController = storyboard.instantiateViewController(withIdentifier: "CreateTripViewController") as! CreateTripViewController createTripViewController.startTextField.text = "Current Location" createTripViewController.destinationTextField.text = (self.business.location?.displayAddress![0])! + " " + (self.business.location?.displayAddress![1])! navigationController?.pushViewController(createTripViewController, animated: true) } else { let routeMapViewController = storyboard.instantiateViewController(withIdentifier: "RouteMapView") as! RouteMapViewController let selectedLoc = self.business.coordinates let currentLocMapItem = MKMapItem.forCurrentLocation() var coord = CLLocationCoordinate2D.init(latitude: (selectedLoc?.latitude)!, longitude: (selectedLoc?.longitude)!) let selectedPlacemark = MKPlacemark(coordinate: coord, addressDictionary: nil) let selectedMapItem = MKMapItem(placemark: selectedPlacemark) let mapItems = [selectedMapItem, currentLocMapItem] var placemark = MKPlacemark(coordinate: coord) let addMapItem = MKMapItem(placemark: placemark) let intermediateLocation = CLLocation.init(latitude: placemark.coordinate.latitude, longitude: placemark.coordinate.longitude) let intermediateSegment = TripSegment(name: placemark.title!, address: "Temp Address", geoPoint: PFGeoPoint(location: intermediateLocation)) //self.trip?.addSegment(tripSegment: intermediateSegment) let selectedPlace = Places(cllocation: CLLocation.init(latitude: placemark.coordinate.latitude, longitude: placemark.coordinate.longitude) , distance: 0, coordinate: placemark.coordinate) //selectedPlace.calculateDistance(fromLocation: startPlace.cllocation) routeMapViewController.placestops.append(selectedPlace) routeMapViewController.placestops.sort(by: { ($0.distance?.isLess(than: $1.distance! ))! }) var stopIndex = 0 for i in 0...routeMapViewController.placestops.count-1 { // if placestops[i].coordinate.latitude == placemark.coordinate.latitude && placestops[i].coordinate.longitude == placemark.coordinate.longitude { stopIndex = i break //} } // locationArray.insert((textField: UITextField(), mapItem: addMapItem), at: stopIndex) //self.mapView.removeOverlays(self.mapView.overlays) // routeMapViewController.calculateSegmentDirections(index: 0, time: 0, routes: []) // routeMapViewController.locationArray = locationArray // routeMapViewController.trip = trip navigationController?.pushViewController(routeMapViewController, animated: true) } } @IBAction func onSavePlace(_ sender: Any) { print("onSavePlace") } func prepareBackgroundView(){ let blurEffect = UIBlurEffect.init(style: .dark) let visualEffect = UIVisualEffectView.init(effect: blurEffect) let bluredView = UIVisualEffectView.init(effect: blurEffect) bluredView.contentView.addSubview(visualEffect) visualEffect.frame = UIScreen.main.bounds bluredView.frame = UIScreen.main.bounds view.insertSubview(bluredView, at: 0) } }
mit
fd3f95cc1ca4dcf786f69093d5db8079
41.347722
164
0.479302
5.955818
false
false
false
false
irisapp/das-quadrat
Source/iOS/TouchAuthorizer.swift
1
2040
// // TouchAuthorizer.swift // Quadrat // // Created by Constantine Fry on 12/11/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation import UIKit class TouchAuthorizer: Authorizer { weak var presentingViewController: UIViewController? weak var delegate: SessionAuthorizationDelegate? var authorizationViewController: AuthorizationViewController? func authorize(viewController: UIViewController, delegate: SessionAuthorizationDelegate?, completionHandler: (String?, NSError?) -> Void) { self.authorizationViewController = AuthorizationViewController(authorizationURL: authorizationURL, redirectURL: redirectURL, delegate: self) self.authorizationViewController!.shouldControllNetworkActivityIndicator = shouldControllNetworkActivityIndicator let navigationController = AuthorizationNavigationController(rootViewController: authorizationViewController!) navigationController.modalPresentationStyle = .FormSheet delegate?.sessionWillPresentAuthorizationViewController?(authorizationViewController!) viewController.presentViewController(navigationController, animated: true, completion: nil) self.presentingViewController = viewController self.completionHandler = completionHandler self.delegate = delegate } override func finilizeAuthorization(accessToken: String?, error: NSError?) { if let authorizationViewController = self.authorizationViewController { self.delegate?.sessionWillDismissAuthorizationViewController?(authorizationViewController) } self.presentingViewController?.dismissViewControllerAnimated(true) { self.didDismissViewController(accessToken, error: error) self.authorizationViewController = nil } } func didDismissViewController(accessToken: String?, error: NSError?) { super.finilizeAuthorization(accessToken, error: error) } }
bsd-2-clause
b9b94d059f4707aa55775c2911941c83
40.632653
118
0.745098
6.415094
false
false
false
false
cburrows/swift-protobuf
Sources/SwiftProtobuf/SimpleExtensionMap.swift
1
3512
// Sources/SwiftProtobuf/SimpleExtensionMap.swift - Extension support // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// A default implementation of ExtensionMap. /// // ----------------------------------------------------------------------------- // Note: The generated code only relies on ExpressibleByArrayLiteral public struct SimpleExtensionMap: ExtensionMap, ExpressibleByArrayLiteral, CustomDebugStringConvertible { public typealias Element = AnyMessageExtension // Since type objects aren't Hashable, we can't do much better than this... internal var fields = [Int: Array<AnyMessageExtension>]() public init() {} public init(arrayLiteral: Element...) { insert(contentsOf: arrayLiteral) } public init(_ others: SimpleExtensionMap...) { for other in others { formUnion(other) } } public subscript(messageType: Message.Type, fieldNumber: Int) -> AnyMessageExtension? { get { if let l = fields[fieldNumber] { for e in l { if messageType == e.messageType { return e } } } return nil } } public func fieldNumberForProto(messageType: Message.Type, protoFieldName: String) -> Int? { // TODO: Make this faster... for (_, list) in fields { for e in list { if e.fieldName == protoFieldName && e.messageType == messageType { return e.fieldNumber } } } return nil } public mutating func insert(_ newValue: Element) { let fieldNumber = newValue.fieldNumber if let l = fields[fieldNumber] { let messageType = newValue.messageType var newL = l.filter { return $0.messageType != messageType } newL.append(newValue) fields[fieldNumber] = newL } else { fields[fieldNumber] = [newValue] } } public mutating func insert(contentsOf: [Element]) { for e in contentsOf { insert(e) } } public mutating func formUnion(_ other: SimpleExtensionMap) { for (fieldNumber, otherList) in other.fields { if let list = fields[fieldNumber] { var newList = list.filter { for o in otherList { if $0.messageType == o.messageType { return false } } return true } newList.append(contentsOf: otherList) fields[fieldNumber] = newList } else { fields[fieldNumber] = otherList } } } public func union(_ other: SimpleExtensionMap) -> SimpleExtensionMap { var out = self out.formUnion(other) return out } public var debugDescription: String { var names = [String]() for (_, list) in fields { for e in list { names.append("\(e.fieldName):(\(e.fieldNumber))") } } let d = names.joined(separator: ",") return "SimpleExtensionMap(\(d))" } }
apache-2.0
3207062cb0262b2ace9160c6d1ca3269
30.357143
105
0.531891
5.329287
false
false
false
false
kripple/bti-watson
ios-app/Carthage/Checkouts/ios-sdk/WatsonDeveloperCloud/AlchemyLanguage/AlchemyLanguageParametersProtocol.swift
1
1868
/** * Copyright IBM Corporation 2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation protocol AlchemyLanguageParameters {} extension AlchemyLanguageParameters { func asDictionary() -> [String : String] { var returnDictionary = [String : String]() let mirror = Mirror(reflecting: self) for property in mirror.children { if let label = property.label { let value = property.value let unwrappedValueAsString = "\(unwrap(value))" if unwrappedValueAsString != "" { returnDictionary.updateValue("\(unwrappedValueAsString)", forKey: label) } } } return returnDictionary } // Reference [1] func unwrap(any:Any) -> Any { let mi = Mirror(reflecting: any) if mi.displayStyle != .Optional { return any } if mi.children.count == 0 { return NSNull() } let (_, some) = mi.children.first! return some } } // REFERENCES // [1] http://stackoverflow.com/questions/27989094/how-to-unwrap-an-optional-value-from-any-type
mit
65ae65e10768ca67e472a7cabcb803c5
26.880597
96
0.567452
5.117808
false
false
false
false
riteshhgupta/RGListKit
Pods/ReactiveSwift/Sources/Flatten.swift
3
32976
// // Flatten.swift // ReactiveSwift // // Created by Neil Pankey on 11/30/15. // Copyright © 2015 GitHub. All rights reserved. // import enum Result.NoError /// Describes how a stream of inner streams should be flattened into a stream of values. public struct FlattenStrategy { fileprivate enum Kind { case concurrent(limit: UInt) case latest case race } fileprivate let kind: Kind private init(kind: Kind) { self.kind = kind } /// The stream of streams is merged, so that any value sent by any of the inner /// streams is forwarded immediately to the flattened stream of values. /// /// The flattened stream of values completes only when the stream of streams, and all /// the inner streams it sent, have completed. /// /// Any interruption of inner streams is treated as completion, and does not interrupt /// the flattened stream of values. /// /// Any failure from the inner streams is propagated immediately to the flattened /// stream of values. public static let merge = FlattenStrategy(kind: .concurrent(limit: .max)) /// The stream of streams is concatenated, so that only values from one inner stream /// are forwarded at a time, in the order the inner streams are received. /// /// In other words, if an inner stream is received when a previous inner stream has /// yet terminated, the received stream would be enqueued. /// /// The flattened stream of values completes only when the stream of streams, and all /// the inner streams it sent, have completed. /// /// Any interruption of inner streams is treated as completion, and does not interrupt /// the flattened stream of values. /// /// Any failure from the inner streams is propagated immediately to the flattened /// stream of values. public static let concat = FlattenStrategy(kind: .concurrent(limit: 1)) /// The stream of streams is merged with the given concurrency cap, so that any value /// sent by any of the inner streams on the fly is forwarded immediately to the /// flattened stream of values. /// /// In other words, if an inner stream is received when a previous inner stream has /// yet terminated, the received stream would be enqueued. /// /// The flattened stream of values completes only when the stream of streams, and all /// the inner streams it sent, have completed. /// /// Any interruption of inner streams is treated as completion, and does not interrupt /// the flattened stream of values. /// /// Any failure from the inner streams is propagated immediately to the flattened /// stream of values. /// /// - precondition: `limit > 0`. public static func concurrent(limit: UInt) -> FlattenStrategy { return FlattenStrategy(kind: .concurrent(limit: limit)) } /// Forward only values from the latest inner stream sent by the stream of streams. /// The active inner stream is disposed of as a new inner stream is received. /// /// The flattened stream of values completes only when the stream of streams, and all /// the inner streams it sent, have completed. /// /// Any interruption of inner streams is treated as completion, and does not interrupt /// the flattened stream of values. /// /// Any failure from the inner streams is propagated immediately to the flattened /// stream of values. public static let latest = FlattenStrategy(kind: .latest) /// Forward only events from the first inner stream that sends an event. Any other /// in-flight inner streams is disposed of when the winning inner stream is /// determined. /// /// The flattened stream of values completes only when the stream of streams, and the /// winning inner stream, have completed. /// /// Any interruption of inner streams is propagated immediately to the flattened /// stream of values. /// /// Any failure from the inner streams is propagated immediately to the flattened /// stream of values. public static let race = FlattenStrategy(kind: .race) } extension Signal where Value: SignalProducerConvertible, Error == Value.Error { /// Flattens the inner producers sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// - note: If `signal` or an active inner producer fails, the returned /// signal will forward that failure immediately. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> { switch strategy.kind { case .concurrent(let limit): return self.concurrent(limit: limit) case .latest: return self.switchToLatest() case .race: return self.race() } } } extension Signal where Value: SignalProducerConvertible, Error == NoError { /// Flattens the inner producers sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// - note: If `signal` or an active inner producer fails, the returned /// signal will forward that failure immediately. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> { return self .promoteError(Value.Error.self) .flatten(strategy) } } extension Signal where Value: SignalProducerConvertible, Error == NoError, Value.Error == NoError { /// Flattens the inner producers sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> { switch strategy.kind { case .concurrent(let limit): return self.concurrent(limit: limit) case .latest: return self.switchToLatest() case .race: return self.race() } } } extension Signal where Value: SignalProducerConvertible, Value.Error == NoError { /// Flattens the inner producers sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// - note: If `signal` fails, the returned signal will forward that failure /// immediately. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> { return self.flatMap(strategy) { $0.producer.promoteError(Error.self) } } } extension SignalProducer where Value: SignalProducerConvertible, Error == Value.Error { /// Flattens the inner producers sent upon `producer` (into a single /// producer of values), according to the semantics of the given strategy. /// /// - note: If `producer` or an active inner producer fails, the returned /// producer will forward that failure immediately. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> { switch strategy.kind { case .concurrent(let limit): return self.concurrent(limit: limit) case .latest: return self.switchToLatest() case .race: return self.race() } } } extension SignalProducer where Value: SignalProducerConvertible, Error == NoError { /// Flattens the inner producers sent upon `producer` (into a single /// producer of values), according to the semantics of the given strategy. /// /// - note: If an active inner producer fails, the returned producer will /// forward that failure immediately. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> { return self .promoteError(Value.Error.self) .flatten(strategy) } } extension SignalProducer where Value: SignalProducerConvertible, Error == NoError, Value.Error == NoError { /// Flattens the inner producers sent upon `producer` (into a single /// producer of values), according to the semantics of the given strategy. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> { switch strategy.kind { case .concurrent(let limit): return self.concurrent(limit: limit) case .latest: return self.switchToLatest() case .race: return self.race() } } } extension SignalProducer where Value: SignalProducerConvertible, Value.Error == NoError { /// Flattens the inner producers sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// - note: If `signal` fails, the returned signal will forward that failure /// immediately. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> { return self.flatMap(strategy) { $0.producer.promoteError(Error.self) } } } extension Signal where Value: Sequence { /// Flattens the `sequence` value sent by `signal`. public func flatten() -> Signal<Value.Iterator.Element, Error> { return self.flatMap(.merge, SignalProducer.init) } } extension SignalProducer where Value: Sequence { /// Flattens the `sequence` value sent by `signal`. public func flatten() -> SignalProducer<Value.Iterator.Element, Error> { return self.flatMap(.merge, SignalProducer<Value.Iterator.Element, NoError>.init) } } extension Signal where Value: SignalProducerConvertible, Error == Value.Error { fileprivate func concurrent(limit: UInt) -> Signal<Value.Value, Error> { precondition(limit > 0, "The concurrent limit must be greater than zero.") return Signal<Value.Value, Error> { relayObserver, lifetime in lifetime += self.observeConcurrent(relayObserver, limit, lifetime) } } fileprivate func observeConcurrent(_ observer: Signal<Value.Value, Error>.Observer, _ limit: UInt, _ lifetime: Lifetime) -> Disposable? { let state = Atomic(ConcurrentFlattenState<Value.Value, Error>(limit: limit)) func startNextIfNeeded() { while let producer = state.modify({ $0.dequeue() }) { let producerState = UnsafeAtomicState<ProducerState>(.starting) let deinitializer = ScopedDisposable(AnyDisposable(producerState.deinitialize)) producer.startWithSignal { signal, inner in let handle = lifetime.observeEnded(inner.dispose) signal.observe { event in switch event { case .completed, .interrupted: handle?.dispose() let shouldComplete: Bool = state.modify { state in state.activeCount -= 1 return state.shouldComplete } withExtendedLifetime(deinitializer) { if shouldComplete { observer.sendCompleted() } else if producerState.is(.started) { startNextIfNeeded() } } case .value, .failed: observer.send(event) } } } withExtendedLifetime(deinitializer) { producerState.setStarted() } } } return observe { event in switch event { case let .value(value): state.modify { $0.queue.append(value.producer) } startNextIfNeeded() case let .failed(error): observer.send(error: error) case .completed: let shouldComplete: Bool = state.modify { state in state.isOuterCompleted = true return state.shouldComplete } if shouldComplete { observer.sendCompleted() } case .interrupted: observer.sendInterrupted() } } } } extension SignalProducer where Value: SignalProducerConvertible, Error == Value.Error { fileprivate func concurrent(limit: UInt) -> SignalProducer<Value.Value, Error> { precondition(limit > 0, "The concurrent limit must be greater than zero.") return SignalProducer<Value.Value, Error> { relayObserver, lifetime in self.startWithSignal { signal, interruptHandle in lifetime.observeEnded(interruptHandle.dispose) _ = signal.observeConcurrent(relayObserver, limit, lifetime) } } } } extension SignalProducer { /// `concat`s `next` onto `self`. /// /// - parameters: /// - next: A follow-up producer to concat `self` with. /// /// - returns: A producer that will start `self` and then on completion of /// `self` - will start `next`. public func concat(_ next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> { return SignalProducer<SignalProducer<Value, Error>, Error>([ self.producer, next ]).flatten(.concat) } /// `concat`s `value` onto `self`. /// /// - parameters: /// - value: A value to concat onto `self`. /// /// - returns: A producer that, when started, will emit own values and on /// completion will emit a `value`. public func concat(value: Value) -> SignalProducer<Value, Error> { return self.concat(SignalProducer(value: value)) } /// `concat`s `self` onto initial `previous`. /// /// - parameters: /// - previous: A producer to start before `self`. /// /// - returns: A signal producer that, when started, first emits values from /// `previous` producer and then from `self`. public func prefix(_ previous: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> { return previous.concat(self) } /// `concat`s `self` onto initial `value`. /// /// - parameters: /// - value: A first value to emit. /// /// - returns: A producer that, when started, first emits `value`, then all /// values emited by `self`. public func prefix(value: Value) -> SignalProducer<Value, Error> { return self.prefix(SignalProducer(value: value)) } } private final class ConcurrentFlattenState<Value, Error: Swift.Error> { typealias Producer = ReactiveSwift.SignalProducer<Value, Error> /// The limit of active producers. let limit: UInt /// The number of active producers. var activeCount: UInt = 0 /// The producers waiting to be started. var queue: [Producer] = [] /// Whether the outer producer has completed. var isOuterCompleted = false /// Whether the flattened signal should complete. var shouldComplete: Bool { return isOuterCompleted && activeCount == 0 && queue.isEmpty } init(limit: UInt) { self.limit = limit } /// Dequeue the next producer if one should be started. /// /// - returns: The `Producer` to start or `nil` if no producer should be /// started. func dequeue() -> Producer? { if activeCount < limit, !queue.isEmpty { activeCount += 1 return queue.removeFirst() } else { return nil } } } private enum ProducerState: Int32 { case starting case started } extension UnsafeAtomicState where State == ProducerState { fileprivate func setStarted() { precondition(tryTransition(from: .starting, to: .started), "The transition is not supposed to fail.") } } extension Signal { /// Merges the given signals into a single `Signal` that will emit all /// values from each of them, and complete when all of them have completed. /// /// - parameters: /// - signals: A sequence of signals to merge. public static func merge<Seq: Sequence>(_ signals: Seq) -> Signal<Value, Error> where Seq.Iterator.Element == Signal<Value, Error> { return SignalProducer<Signal<Value, Error>, Error>(signals) .flatten(.merge) .startAndRetrieveSignal() } /// Merges the given signals into a single `Signal` that will emit all /// values from each of them, and complete when all of them have completed. /// /// - parameters: /// - signals: A list of signals to merge. public static func merge(_ signals: Signal<Value, Error>...) -> Signal<Value, Error> { return Signal.merge(signals) } } extension SignalProducer { /// Merges the given producers into a single `SignalProducer` that will emit /// all values from each of them, and complete when all of them have /// completed. /// /// - parameters: /// - producers: A sequence of producers to merge. public static func merge<Seq: Sequence>(_ producers: Seq) -> SignalProducer<Value, Error> where Seq.Iterator.Element == SignalProducer<Value, Error> { return SignalProducer<Seq.Iterator.Element, NoError>(producers).flatten(.merge) } /// Merges the given producers into a single `SignalProducer` that will emit /// all values from each of them, and complete when all of them have /// completed. /// /// - parameters: /// - producers: A sequence of producers to merge. public static func merge(_ producers: SignalProducer<Value, Error>...) -> SignalProducer<Value, Error> { return SignalProducer.merge(producers) } } extension Signal where Value: SignalProducerConvertible, Error == Value.Error { /// Returns a signal that forwards values from the latest signal sent on /// `signal`, ignoring values sent on previous inner signal. /// /// - warning: An error sent on `signal` or the latest inner signal will be /// sent on the returned signal. /// /// - note: The returned signal completes when `signal` and the latest inner /// signal have both completed. fileprivate func switchToLatest() -> Signal<Value.Value, Error> { return Signal<Value.Value, Error> { observer, lifetime in let serial = SerialDisposable() lifetime += serial lifetime += self.observeSwitchToLatest(observer, serial) } } fileprivate func observeSwitchToLatest(_ observer: Signal<Value.Value, Error>.Observer, _ latestInnerDisposable: SerialDisposable) -> Disposable? { let state = Atomic(LatestState<Value, Error>()) return self.observe { event in switch event { case let .value(p): p.producer.startWithSignal { innerSignal, innerDisposable in state.modify { // When we replace the disposable below, this prevents // the generated Interrupted event from doing any work. $0.replacingInnerSignal = true } latestInnerDisposable.inner = innerDisposable state.modify { $0.replacingInnerSignal = false $0.innerSignalComplete = false } innerSignal.observe { event in switch event { case .interrupted: // If interruption occurred as a result of a new // producer arriving, we don't want to notify our // observer. let shouldComplete: Bool = state.modify { state in if !state.replacingInnerSignal { state.innerSignalComplete = true } return !state.replacingInnerSignal && state.outerSignalComplete } if shouldComplete { observer.sendCompleted() } case .completed: let shouldComplete: Bool = state.modify { $0.innerSignalComplete = true return $0.outerSignalComplete } if shouldComplete { observer.sendCompleted() } case .value, .failed: observer.send(event) } } } case let .failed(error): observer.send(error: error) case .completed: let shouldComplete: Bool = state.modify { $0.outerSignalComplete = true return $0.innerSignalComplete } if shouldComplete { observer.sendCompleted() } case .interrupted: observer.sendInterrupted() } } } } extension SignalProducer where Value: SignalProducerConvertible, Error == Value.Error { /// - warning: An error sent on `signal` or the latest inner signal will be /// sent on the returned signal. /// /// - note: The returned signal completes when `signal` and the latest inner /// signal have both completed. /// /// - returns: A signal that forwards values from the latest signal sent on /// `signal`, ignoring values sent on previous inner signal. fileprivate func switchToLatest() -> SignalProducer<Value.Value, Error> { return SignalProducer<Value.Value, Error> { observer, lifetime in let latestInnerDisposable = SerialDisposable() lifetime.observeEnded(latestInnerDisposable.dispose) self.startWithSignal { signal, signalDisposable in lifetime.observeEnded(signalDisposable.dispose) if let disposable = signal.observeSwitchToLatest(observer, latestInnerDisposable) { lifetime.observeEnded(disposable.dispose) } } } } } private struct LatestState<Value, Error: Swift.Error> { var outerSignalComplete: Bool = false var innerSignalComplete: Bool = true var replacingInnerSignal: Bool = false } extension Signal where Value: SignalProducerConvertible, Error == Value.Error { /// Returns a signal that forwards values from the "first input signal to send an event" /// (winning signal) that is sent on `self`, ignoring values sent from other inner signals. /// /// An error sent on `self` or the winning inner signal will be sent on the /// returned signal. /// /// The returned signal completes when `self` and the winning inner signal have both completed. fileprivate func race() -> Signal<Value.Value, Error> { return Signal<Value.Value, Error> { observer, lifetime in let relayDisposable = CompositeDisposable() lifetime += relayDisposable lifetime += self.observeRace(observer, relayDisposable) } } fileprivate func observeRace(_ observer: Signal<Value.Value, Error>.Observer, _ relayDisposable: CompositeDisposable) -> Disposable? { let state = Atomic(RaceState()) return self.observe { event in switch event { case let .value(innerProducer): // Ignore consecutive `innerProducer`s if any `innerSignal` already sent an event. guard !relayDisposable.isDisposed else { return } innerProducer.producer.startWithSignal { innerSignal, innerDisposable in state.modify { $0.innerSignalComplete = false } let disposableHandle = relayDisposable.add(innerDisposable) var isWinningSignal = false innerSignal.observe { event in if !isWinningSignal { isWinningSignal = state.modify { state in guard !state.isActivated else { return false } state.isActivated = true return true } // Ignore non-winning signals. guard isWinningSignal else { return } // The disposals would be run exactly once immediately after // the winning signal flips `state.isActivated`. disposableHandle?.dispose() relayDisposable.dispose() } switch event { case .completed: let shouldComplete: Bool = state.modify { state in state.innerSignalComplete = true return state.outerSignalComplete } if shouldComplete { observer.sendCompleted() } case .value, .failed, .interrupted: observer.send(event) } } } case let .failed(error): observer.send(error: error) case .completed: let shouldComplete: Bool = state.modify { state in state.outerSignalComplete = true return state.innerSignalComplete } if shouldComplete { observer.sendCompleted() } case .interrupted: observer.sendInterrupted() } } } } extension SignalProducer where Value: SignalProducerConvertible, Error == Value.Error { /// Returns a producer that forwards values from the "first input producer to send an event" /// (winning producer) that is sent on `self`, ignoring values sent from other inner producers. /// /// An error sent on `self` or the winning inner producer will be sent on the /// returned producer. /// /// The returned producer completes when `self` and the winning inner producer have both completed. fileprivate func race() -> SignalProducer<Value.Value, Error> { return SignalProducer<Value.Value, Error> { observer, lifetime in let relayDisposable = CompositeDisposable() lifetime.observeEnded(relayDisposable.dispose) self.startWithSignal { signal, signalDisposable in lifetime.observeEnded(signalDisposable.dispose) if let disposable = signal.observeRace(observer, relayDisposable) { lifetime.observeEnded(disposable.dispose) } } } } } private struct RaceState { var outerSignalComplete = false var innerSignalComplete = true var isActivated = false } extension Signal { /// Maps each event from `signal` to a new signal, then flattens the /// resulting producers (into a signal of values), according to the /// semantics of the given strategy. /// /// - warning: If `signal` or any of the created producers fail, the /// returned signal will forward that failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> Signal<Inner.Value, Error> where Inner.Error == Error { return map(transform).flatten(strategy) } /// Maps each event from `signal` to a new signal, then flattens the /// resulting producers (into a signal of values), according to the /// semantics of the given strategy. /// /// - warning: If `signal` fails, the returned signal will forward that /// failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> Signal<Inner.Value, Error> where Inner.Error == NoError { return map(transform).flatten(strategy) } } extension Signal where Error == NoError { /// Maps each event from `signal` to a new signal, then flattens the /// resulting signals (into a signal of values), according to the /// semantics of the given strategy. /// /// - warning: If any of the created signals emit an error, the returned /// signal will forward that error immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> Signal<Inner.Value, Inner.Error> { return map(transform).flatten(strategy) } /// Maps each event from `signal` to a new signal, then flattens the /// resulting signals (into a signal of values), according to the /// semantics of the given strategy. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> Signal<Inner.Value, NoError> where Inner.Error == NoError { return map(transform).flatten(strategy) } } extension SignalProducer { /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// - warning: If `self` or any of the created producers fail, the returned /// producer will forward that failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> SignalProducer<Inner.Value, Error> where Inner.Error == Error { return map(transform).flatten(strategy) } /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// - warning: If `self` fails, the returned producer will forward that /// failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> SignalProducer<Inner.Value, Error> where Inner.Error == NoError { return map(transform).flatten(strategy) } } extension SignalProducer where Error == NoError { /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> SignalProducer<Inner.Value, Error> where Inner.Error == Error { return map(transform).flatten(strategy) } /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// - warning: If any of the created producers fail, the returned producer /// will forward that failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> SignalProducer<Inner.Value, Inner.Error> { return map(transform).flatten(strategy) } } extension Signal { /// Catches any failure that may occur on the input signal, mapping to a new /// producer that starts in its place. /// /// - parameters: /// - transform: A closure that accepts emitted error and returns a signal /// producer with a different type of error. public func flatMapError<F>(_ transform: @escaping (Error) -> SignalProducer<Value, F>) -> Signal<Value, F> { return Signal<Value, F> { observer, lifetime in lifetime += self.observeFlatMapError(transform, observer, SerialDisposable()) } } fileprivate func observeFlatMapError<F>(_ handler: @escaping (Error) -> SignalProducer<Value, F>, _ observer: Signal<Value, F>.Observer, _ serialDisposable: SerialDisposable) -> Disposable? { return self.observe { event in switch event { case let .value(value): observer.send(value: value) case let .failed(error): handler(error).startWithSignal { signal, disposable in serialDisposable.inner = disposable signal.observe(observer) } case .completed: observer.sendCompleted() case .interrupted: observer.sendInterrupted() } } } } extension SignalProducer { /// Catches any failure that may occur on the input producer, mapping to a /// new producer that starts in its place. /// /// - parameters: /// - transform: A closure that accepts emitted error and returns a signal /// producer with a different type of error. public func flatMapError<F>(_ transform: @escaping (Error) -> SignalProducer<Value, F>) -> SignalProducer<Value, F> { return SignalProducer<Value, F> { observer, lifetime in let serialDisposable = SerialDisposable() lifetime.observeEnded(serialDisposable.dispose) self.startWithSignal { signal, signalDisposable in serialDisposable.inner = signalDisposable _ = signal.observeFlatMapError(transform, observer, serialDisposable) } } } }
mit
1d0d263deafb5cbd07f4ee724bc100e1
34.26738
193
0.695709
4.117243
false
false
false
false
atl009/WordPress-iOS
WordPress/Classes/Extensions/WPStyleGuide+Aztec.swift
1
1178
import UIKit import Gridicons import WordPressShared extension WPStyleGuide { static let aztecFormatBarInactiveColor: UIColor = UIColor(hexString: "7B9AB1") static let aztecFormatBarActiveColor: UIColor = UIColor(hexString: "11181D") static let aztecFormatBarDisabledColor = WPStyleGuide.greyLighten20() static let aztecFormatBarDividerColor = WPStyleGuide.greyLighten30() static let aztecFormatBarBackgroundColor = UIColor.white static var aztecFormatPickerSelectedCellBackgroundColor: UIColor { get { return (UIDevice.isPad()) ? WPStyleGuide.lightGrey() : WPStyleGuide.greyLighten30() } } static var aztecFormatPickerBackgroundColor: UIColor { get { return (UIDevice.isPad()) ? .white : WPStyleGuide.lightGrey() } } static func configureBetaButton(_ button: UIButton) { let helpImage = Gridicon.iconOfType(.helpOutline) button.setImage(helpImage, for: .normal) button.tintColor = WPStyleGuide.greyLighten10() let edgeInsets = UIEdgeInsets(top: 2.0, left: 2.0, bottom: 2.0, right: 2.0) button.contentEdgeInsets = edgeInsets } }
gpl-2.0
fc65e5cb3e4844b0600495ce6822e899
31.722222
95
0.705433
4.92887
false
false
false
false
takaiwai/CGExtensions
Example/Tests/Tests.swift
1
2431
// https://github.com/Quick/Quick import Quick import Nimble import CGExtensions class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } describe("Geometry and trigonomitry refreshers") { it("checks cos()") { let c1 = cos(0.0) let c2 = cos(.pi / 2.0) let c3 = cos(CGFloat.pi) let c4 = cos(.pi * 1.5) let c5 = cos(.pi * 2.0) expect(c1) ≈ 1.0 expect(c2) ≈ 0.0 expect(c3) ≈ -1.0 expect(c4) ≈ 0.0 expect(c5) ≈ 1.0 } it("checks sin()") { let s1 = sin(0.0) let s2 = sin(.pi / 2.0) let s3 = sin(CGFloat.pi) let s4 = sin(.pi * 1.5) let s5 = sin(.pi * 2.0) expect(s1) ≈ 0.0 expect(s2) ≈ 1.0 expect(s3) ≈ 0.0 expect(s4) ≈ -1.0 expect(s5) ≈ 0.0 } it("checkes atan2()") { let a1 = atan2(0.0, 1.0) let a2 = atan2(1.0, 0.0) let a3 = atan2(0.0, -1.0) let a4 = atan2(-1.0, 0.0) let a5 = atan2(1.0, 1.0) let a6 = atan2(100.0, 100.0) expect(a1) ≈ 0.0 expect(a2) ≈ CGFloat.pi / 2.0 expect(a3) ≈ CGFloat.pi expect(a4) ≈ -CGFloat.pi / 2.0 expect(a5) ≈ CGFloat.pi / 4.0 expect(a6) ≈ CGFloat.pi / 4.0 } } } }
mit
489078e2035307efa89115810177bb75
27.488095
58
0.330547
4.104631
false
false
false
false
naithar/Kitura
Sources/Kitura/Headers.swift
1
5820
/* * Copyright IBM Corporation 2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import KituraNet /// The struct containing the HTTP headers and implements the headers APIs for the /// `RouterRequest` and `RouterResponse` classes. public struct Headers { /// The header storage internal var headers: HeadersContainer /// Initialize a `Headers` instance /// /// - Parameter headers: The container for the headers init(headers: HeadersContainer) { self.headers = headers } /// Append values to the header /// /// - Parameter key: The key of the header to append a value to. /// - Parameter value: The value to be appended to the specified header. public mutating func append(_ key: String, value: String) { headers.append(key, value: value) } } /// Conformance to the `Collection` protocol extension Headers: Collection { /// The starting index of the `Headers` collection public var startIndex: HeadersIndex { return headers.startIndex } /// The ending index of the `Headers` collection public var endIndex: HeadersIndex { return headers.endIndex } /// The type of an Index of the `Headers` collection. public typealias HeadersIndex = HeadersContainer.Index /// Get the value of a HTTP header /// /// - Parameter key: The HTTP header key whose value is to be retrieved /// /// - Returns: The value of the specified HTTP header, or nil, if it doesn't exist. public subscript(key: String) -> String? { get { return headers[key]?.first } set(newValue) { if let newValue = newValue { headers[key] = [newValue] } else { headers[key] = nil } } } /// Get a (key value) tuple from the `Headers` collection at the specified position. /// /// - Parameter position: The position in the `Headers` collection of the (key, value) /// tuple to return. /// /// - Returns: A (key, value) tuple. public subscript(position: HeadersIndex) -> (String, String?) { get { let (key, value) = headers[position] return (key, value.first) } } /// Get the next Index in the `Headers` collection after the one specified. /// /// - Parameter after: The Index whose successor is to be returned. /// /// - Returns: The Index in the `Headers` collection after the one specified. // swiftlint:disable variable_name public func index(after i: HeadersIndex) -> HeadersIndex { return headers.index(after: i) } // swiftlint:enable variable_name } /// Various convenience methods for setting various HTTP headers extension Headers { /// Sets the Location HTTP header /// /// - Parameter path: the path to set into the header or the special reserved word "back". public mutating func setLocation(_ path: String) { var p = path if p == "back" { if let referrer = self["referrer"] { p = referrer } else { p = "/" } } self["Location"] = p } /// Sets the Content-Type HTTP header /// /// - Parameter type: The type to set in the Content-Type header /// - Parameter charset: The charset to specify in the Content-Type header. public mutating func setType(_ type: String, charset: String? = nil) { if let contentType = ContentType.sharedInstance.getContentType(forExtension: type) { var contentCharset = "" if let charset = charset { contentCharset = "; charset=\(charset)" } self["Content-Type"] = contentType + contentCharset } } /// Sets the HTTP header Content-Disposition to "attachment", optionally /// adding the filename parameter. If a file is specified the HTTP header /// Content-Type will be set based on the extension of the specified file. /// /// - Parameter for: The file to set the filename to public mutating func addAttachment(for filePath: String? = nil) { guard let filePath = filePath else { self["Content-Disposition"] = "attachment" return } let filePaths = filePath.characters.split {$0 == "/"}.map(String.init) guard let fileName = filePaths.last else { return } self["Content-Disposition"] = "attachment; fileName = \"\(fileName)\"" let contentType = ContentType.sharedInstance.getContentType(forFileName: fileName) if let contentType = contentType { self["Content-Type"] = contentType } } /// Adds a link with specified parameters to Link HTTP header /// /// - Parameter link: link value /// - Parameter linkParameters: The link parameters (according to RFC 5988) with their values public mutating func addLink(_ link: String, linkParameters: [LinkParameter: String]) { var headerValue = "<\(link)>" for (linkParamer, value) in linkParameters { headerValue += "; \(linkParamer.rawValue)=\"\(value)\"" } self.append("Link", value: headerValue) } }
apache-2.0
c029cce811959bb2cac40e2f8fabe8b2
33.035088
97
0.62079
4.670947
false
false
false
false
emericspiroux/Open42
correct42/UIColor+Theme.swift
1
1408
// // UIColor+Theme.swift // Open42 // // Created by larry on 27/07/2016. // Copyright © 2016 42. All rights reserved. // import UIKit import Foundation enum Theme { case primary case secondary case accent case darkText case lightText case background case alert var color:UIColor{ switch self { case .primary: return UIColor.fromRGB(0x00897B) case .secondary: return UIColor.fromRGB(0x4DB6AC) case .accent: return UIColor.fromRGB(0xD5AD0B) case .darkText: return UIColor.fromRGB(0x152C18) case .lightText: return UIColor.fromRGB(0xFDFFFD) case .background: return UIColor.fromRGB(0xFDFFFD) case .alert: return UIColor.fromRGB(0xDF4F4F) } } static func getColoredText(text:String, color:UIColor) -> NSMutableAttributedString{ let string:NSMutableAttributedString = NSMutableAttributedString(string: text) let words:[String] = text.componentsSeparatedByString(" ") for var word in words { if (word.hasPrefix("{|") && word.hasSuffix("|}")) { let range:NSRange = (string.string as NSString).rangeOfString(word) string.addAttribute(NSForegroundColorAttributeName, value: color, range: range) word = word.stringByReplacingOccurrencesOfString("{|", withString: "") word = word.stringByReplacingOccurrencesOfString("|}", withString: "") string.replaceCharactersInRange(range, withString: word) } } return string } }
apache-2.0
402e2080c1071aec12a1b740bc8e310e
24.6
85
0.725657
3.626289
false
false
false
false
Wakup/Wakup-iOS-SDK
Wakup/SavedCouponsViewController.swift
1
10568
// // SavedCouponsViewController.swift // Wuakup // // Created by Guillermo Gutiérrez on 17/02/15. // Copyright (c) 2015 Yellow Pineapple. All rights reserved. // import Foundation import CoreLocation import DZNEmptyDataSet import CHTCollectionViewWaterfallLayout class SavedCouponsViewController: LoadingPresenterViewController, CHTCollectionViewDelegateWaterfallLayout, UICollectionViewDataSource, UICollectionViewDelegate, CLLocationManagerDelegate, ZoomTransitionOrigin, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource { var couponCollectionHandler: CouponCollectionHandler? let layout = CHTCollectionViewWaterfallLayout() let showDetailsSegueId = "showDetails" var selectedRow: Int = 0 let offersService = OffersService.sharedInstance let locationManager = CLLocationManager() var location: CLLocation? { didSet { couponCollectionHandler?.userLocation = location } } var coordinate: CLLocationCoordinate2D? { get { return location?.coordinate } } var locationTimestamp: Date? var locationExpirationTime: TimeInterval = 5 * 60 var locationExpired: Bool { get { if let timestamp = locationTimestamp { let elapsedTime = -timestamp.timeIntervalSinceNow return elapsedTime > locationExpirationTime } return true } } let persistenceService = PersistenceService.sharedInstance @IBOutlet var collectionView: UICollectionView? func reload() { couponCollectionHandler?.reloadCoupons() } func fetchLocation() { locationManager.delegate = self if #available(iOS 8.0, *) { locationManager.requestWhenInUseAuthorization() } locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters locationManager.startUpdatingLocation() } deinit { collectionView?.emptyDataSetDelegate = nil collectionView?.emptyDataSetSource = nil } // MARK: View lifecycle methods override func viewDidLoad() { super.viewDidLoad() collectionView?.collectionViewLayout = layout // Initialize CouponCollectionHandler with the load coupon method couponCollectionHandler = CouponCollectionHandler(collectionView: collectionView, loadCouponMethod: { (page, perPage, onComplete) -> Void in let savedOfferIds = self.persistenceService.getSavedOfferIds(true) if savedOfferIds.count > 0 { guard let location = self.location else { return } self.offersService.getOfferDetails(savedOfferIds, location: location.coordinate, sensor: location.horizontalAccuracy > 0, completion: onComplete) } else { self.couponCollectionHandler?.cancel() Async.main { // Reload in the next main thread cycle to allow the view hierarchy to compose self.collectionView?.reloadEmptyDataSet() } } }) couponCollectionHandler!.showFooterWhenReloading = false couponCollectionHandler!.enablePagination = false couponCollectionHandler!.onLoadingChanged = { loading in if loading { self.showLoadingView() } else { self.dismissLoadingView() } } couponCollectionHandler!.shouldLoadCoupons = { page in if (page == 0 && self.locationExpired) { self.fetchLocation() return false } return true } couponCollectionHandler!.onContextActionSelected = { action, coupon in switch action { case .Save: NSLog("WARNING: This shouldn't happen: 'Save' action in a saved offer") case .Remove: self.persistenceService.removeOfferId(coupon.id) self.couponCollectionHandler?.removeCoupon(coupon, animated: true) case .ShowMap: self.showMap(forOffer: coupon) case .Share: self.shareCoupon(coupon) } } couponCollectionHandler!.onErrorReceived = { error in // Reload empty data set to show error view self.collectionView?.reloadEmptyDataSet() } couponCollectionHandler!.userLocation = location self.view.backgroundColor = collectionView?.backgroundColor // Setup DZNEmptyDataSet collectionView?.emptyDataSetDelegate = self collectionView?.emptyDataSetSource = self reload() // // Setup Shy NavBar // shyNavBarManager.scrollView = self.collectionView // shyNavBarManager.expansionResistance = 20 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) couponCollectionHandler?.refreshControl.endRefreshing() // iOS 9 UIRefreshControl issue } // MARK: Collection View methods func collectionView (_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return couponCollectionHandler!.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return couponCollectionHandler!.collectionView(collectionView, numberOfItemsInSection: section) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return couponCollectionHandler!.collectionView(collectionView, cellForItemAt: indexPath) } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { couponCollectionHandler?.collectionView(collectionView, willDisplay: cell, forItemAt: indexPath) } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { return couponCollectionHandler!.collectionView(collectionView, viewForSupplementaryElementOfKind: kind, at: indexPath) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { couponCollectionHandler?.collectionView(collectionView, didSelectItemAt: indexPath) selectedRow = (indexPath as NSIndexPath).row performSegue(withIdentifier: showDetailsSegueId, sender: self) } // MARK: CLLocationManagerDelegate methods func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { NSLog("AuthorizationStatusChanged: %d", status.rawValue) switch status { case .authorizedAlways where locationExpired, .authorizedWhenInUse where locationExpired: reload() default: break } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { NSLog("Error obtaining location: %@", error.localizedDescription) couponCollectionHandler?.cancel() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let newLocation = locations.last else { return } NSLog("Received location update %@", newLocation) self.location = newLocation self.locationTimestamp = Date() self.locationManager.stopUpdatingLocation() self.locationManager.delegate = nil reload() } // MARK: Transition methods override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == showDetailsSegueId) { let vc = segue.destination as! CouponDetailsViewController vc.userLocation = location vc.coupons = couponCollectionHandler!.coupons vc.selectedIndex = selectedRow vc.onSelectionChanged = { coupon, row in self.selectedRow = row } } } func zoomTransitionOriginView() -> UIView { let indexPath = IndexPath(row: selectedRow, section: 0) let cell = self.collectionView?.scrollToAndGetCell(atIndexPath: indexPath) as! CouponCollectionViewCell return cell.couponImageView } // MARK: DZNEmptyDataSetDelegate and DZNEmptyDataSetSource var lastRequestFailed: Bool { get { return couponCollectionHandler?.lastRequestFailed ?? false } } let emptyViewColor = UIColor(fromHexString: "#908E90") func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { let attributes = [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18), NSAttributedString.Key.foregroundColor: emptyViewColor ] let title = lastRequestFailed ? "ConnectionErrorViewTitle".i18n() : "EmptyMyOffersTitle".i18n() return NSAttributedString(string: title, attributes: attributes) } func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! { if lastRequestFailed { return CodeIcon(iconIdentifier: "cloud-alert").getImage(CGRect(x: 0, y: 0, width: 150, height: 100)) } else { return CodeIcon(iconIdentifier: "save").getImage(CGRect(x: 0, y: 0, width: 90, height: 90)) } } func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { let attributes = [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: emptyViewColor ] let description = lastRequestFailed ? "ConnectionErrorViewMsg".i18n() : "EmptyMyOffersDescription".i18n() return NSAttributedString(string: description, attributes: attributes) } func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool { return lastRequestFailed || !(couponCollectionHandler?.loading ?? false) } func emptyDataSetDidTap(_ scrollView: UIScrollView!) { if lastRequestFailed { reload() } } func offset(forEmptyDataSet scrollView: UIScrollView!) -> CGPoint { // Minor tweak to center the view in the screen, not the Scroll view return CGPoint(x: 0, y: -scrollView.contentInset.top / 2) } }
mit
f9704946a1f77072789caec211211103
40.766798
259
0.671808
5.831678
false
false
false
false
yemuhong/HundredsOfThink
HundredsOfThink/HundredsOfThink/Classes/Tools/UIView-Extension.swift
1
1474
// // UIView-Extension.swift // HundredsOfThink // // Created by 顾宏钟 on 17/2/24. // Copyright © 2017年 hongzhong. All rights reserved. // import Foundation import UIKit extension UIView { var hg_x : CGFloat { get { return frame.origin.x } set(newVale) { var tempFrame : CGRect = frame // 空的frame = 系统原来的frame tempFrame.origin.x = newVale // 系统原来的frame = 新的frame frame = tempFrame // 系统原来的frame = 新的frame } } // y var hg_y : CGFloat { get { return self.frame.origin.y } set(newValue) { var tempFrame : CGRect = frame tempFrame.origin.y = newValue frame = tempFrame } } // width var hg_width : CGFloat { get { return frame.size.width } set(newValue) { var tempFrame : CGRect = frame tempFrame.size.width = newValue frame = tempFrame } } // height var hg_height : CGFloat { get { return self.frame.size.height } set(newValue) { var tempFrame = frame tempFrame.size.height = newValue frame = tempFrame } } }
apache-2.0
97bd2fc65ce5e3216bd2fe9b34ab9486
18.763889
67
0.45116
4.711921
false
false
false
false
PiXeL16/BudgetShare
BudgetShare/UI/Login/LoginViewController.swift
1
2314
// // LoginViewController.swift // BudgetShare // // Created by Chris Jimenez on 3/5/17. // Copyright © 2017 Chris Jimenez. All rights reserved. // import UIKit class LoginViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var signUpButton: UIButton! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var loginFieldsView: UIView! var presenter: LoginModule! deinit { presenter = nil } override func viewDidLoad() { super.viewDidLoad() self.setupView() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func loginTapped(_ sender: Any) { self.didTapLogin() } @IBAction func signUpTapped(_ sender: Any) { self.didTapSignUp() } func setupView() { self.loginFieldsView.layer.cornerRadius = Constants.cornerRadius self.loginButton.layer.cornerRadius = Constants.cornerRadius self.signUpButton.layer.cornerRadius = Constants.cornerRadius let backgroundGradient = Gradients(self.view.bounds).orangeBackgroundGradient self.view.layer.insertSublayer(backgroundGradient, at: 0) } override var prefersStatusBarHidden: Bool { return true } } extension LoginViewController: LoginView { weak internal var controller: UIViewController? { return self } func didTapLogin() { guard let email = emailTextField.text, let password = passwordTextField.text, !email.isEmpty, !password.isEmpty else { self.loginFieldsView.shake() return } //TODO: Show activity indicator //Dismiss keyboard self.view.endEditing(true) presenter.login(email: email, password: password) } func didTapSignUp() { presenter.presentSignUp() } func didReceiveError(message: String) { presenter.presentError(message: message) } func loginSuccesful() { } }
mit
b13b8db3007b8e286f6d9cda0d9c80c3
21.456311
85
0.633377
5.094714
false
false
false
false
aschwaighofer/swift
test/AutoDiff/validation-test/control_flow.swift
2
20206
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: SR12741 import _Differentiation import StdlibUnittest var ControlFlowTests = TestSuite("ControlFlow") ControlFlowTests.test("Conditionals") { func cond1(_ x: Float) -> Float { if x > 0 { return x * x } return x + x } expectEqual(8, gradient(at: 4, in: cond1)) expectEqual(2, gradient(at: -10, in: cond1)) func cond2(_ x: Float) -> Float { let y: Float if x > 0 { y = x * x } else if x == -1337 { y = 0 } else { y = x + x } return y } expectEqual(8, gradient(at: 4, in: cond2)) expectEqual(2, gradient(at: -10, in: cond2)) expectEqual(0, gradient(at: -1337, in: cond2)) func cond2_var(_ x: Float) -> Float { var y: Float = x if x > 0 { y = y * x } else if x == -1337 { y = x // Dummy assignment; shouldn't affect computation. y = x // Dummy assignment; shouldn't affect computation. y = 0 } else { y = x + y } return y } expectEqual(8, gradient(at: 4, in: cond2_var)) expectEqual(2, gradient(at: -10, in: cond2_var)) expectEqual(0, gradient(at: -1337, in: cond2_var)) func cond3(_ x: Float, _ y: Float) -> Float { if x > 0 { return x * y } return y - x } expectEqual((5, 4), gradient(at: 4, 5, in: cond3)) expectEqual((-1, 1), gradient(at: -3, -2, in: cond3)) func cond4_var(_ x: Float) -> Float { var outer = x outerIf: if true { var inner = outer inner = inner * x if false { break outerIf } outer = inner } return outer } expectEqual((9, 6), valueWithGradient(at: 3, in: cond4_var)) func cond_tuple(_ x: Float) -> Float { // Convoluted function returning `x + x`. let y: (Float, Float) = (x, x) if x > 0 { return y.0 + y.1 } return y.0 + y.0 - y.1 + y.0 } expectEqual((8, 2), valueWithGradient(at: 4, in: cond_tuple)) expectEqual((-20, 2), valueWithGradient(at: -10, in: cond_tuple)) expectEqual((-2674, 2), valueWithGradient(at: -1337, in: cond_tuple)) func cond_tuple2(_ x: Float) -> Float { // Convoluted function returning `x + x`. let y: (Float, Float) = (x, x) let y0 = y.0 if x > 0 { let y1 = y.1 return y0 + y1 } let y0_double = y0 + y.0 let y1 = y.1 return y0_double - y1 + y.0 } expectEqual((8, 2), valueWithGradient(at: 4, in: cond_tuple2)) expectEqual((-20, 2), valueWithGradient(at: -10, in: cond_tuple2)) expectEqual((-2674, 2), valueWithGradient(at: -1337, in: cond_tuple2)) func cond_tuple_var(_ x: Float) -> Float { // Convoluted function returning `x + x`. var y: (Float, Float) = (x, x) var z: (Float, Float) = (x + x, x - x) if x > 0 { var w = (x, x) y.0 = w.1 y.1 = w.0 z.0 = z.0 - y.0 z.1 = z.1 + y.0 } else { z = (x, x) } return y.0 + y.1 - z.0 + z.1 } expectEqual((8, 2), valueWithGradient(at: 4, in: cond_tuple_var)) expectEqual((-20, 2), valueWithGradient(at: -10, in: cond_tuple_var)) expectEqual((-2674, 2), valueWithGradient(at: -1337, in: cond_tuple_var)) func cond_nestedtuple_var(_ x: Float) -> Float { // Convoluted function returning `x + x`. var y: (Float, Float) = (x + x, x - x) var z: ((Float, Float), Float) = (y, x) if x > 0 { var w = (x, x) y.0 = w.1 y.1 = w.0 z.0.0 = z.0.0 - y.0 z.0.1 = z.0.1 + y.0 } else { z = ((y.0 - x, y.1 + x), x) } return y.0 + y.1 - z.0.0 + z.0.1 } expectEqual((8, 2), valueWithGradient(at: 4, in: cond_nestedtuple_var)) expectEqual((-20, 2), valueWithGradient(at: -10, in: cond_nestedtuple_var)) expectEqual((-2674, 2), valueWithGradient(at: -1337, in: cond_nestedtuple_var)) struct FloatPair : Differentiable { var first, second: Float init(_ first: Float, _ second: Float) { self.first = first self.second = second } } struct Pair<T : Differentiable, U : Differentiable> : Differentiable { var first: T var second: U init(_ first: T, _ second: U) { self.first = first self.second = second } } func cond_struct(_ x: Float) -> Float { // Convoluted function returning `x + x`. let y = FloatPair(x, x) if x > 0 { return y.first + y.second } return y.first + y.first - y.second + y.first } expectEqual((8, 2), valueWithGradient(at: 4, in: cond_struct)) expectEqual((-20, 2), valueWithGradient(at: -10, in: cond_struct)) expectEqual((-2674, 2), valueWithGradient(at: -1337, in: cond_struct)) func cond_struct2(_ x: Float) -> Float { // Convoluted function returning `x + x`. let y = FloatPair(x, x) let y0 = y.first if x > 0 { let y1 = y.second return y0 + y1 } let y0_double = y0 + y.first let y1 = y.second return y0_double - y1 + y.first } expectEqual((8, 2), valueWithGradient(at: 4, in: cond_struct2)) expectEqual((-20, 2), valueWithGradient(at: -10, in: cond_struct2)) expectEqual((-2674, 2), valueWithGradient(at: -1337, in: cond_struct2)) func cond_struct_var(_ x: Float) -> Float { // Convoluted function returning `x + x`. var y = FloatPair(x, x) var z = FloatPair(x + x, x - x) if x > 0 { var w = y y.first = w.second y.second = w.first z.first = z.first - y.first z.second = z.second + y.first } else { z = FloatPair(x, x) } return y.first + y.second - z.first + z.second } expectEqual((8, 2), valueWithGradient(at: 4, in: cond_struct_var)) expectEqual((-20, 2), valueWithGradient(at: -10, in: cond_struct_var)) expectEqual((-2674, 2), valueWithGradient(at: -1337, in: cond_struct_var)) func cond_nestedstruct_var(_ x: Float) -> Float { // Convoluted function returning `x + x`. var y = FloatPair(x + x, x - x) var z = Pair(y, x) if x > 0 { var w = FloatPair(x, x) y.first = w.second y.second = w.first z.first.first = z.first.first - y.first z.first.second = z.first.second + y.first } else { z = Pair(FloatPair(y.first - x, y.second + x), x) } return y.first + y.second - z.first.first + z.first.second } expectEqual((8, 2), valueWithGradient(at: 4, in: cond_nestedstruct_var)) expectEqual((-20, 2), valueWithGradient(at: -10, in: cond_nestedstruct_var)) expectEqual((-2674, 2), valueWithGradient(at: -1337, in: cond_nestedstruct_var)) func guard1(_ x: Float, _ y: Float) -> Float { guard x > 0 else { return x * x } return y * y } expectEqual((0, 10), gradient(at: 4, 5, in: guard1)) expectEqual((-6, 0), gradient(at: -3, -2, in: guard1)) func guard2(_ x: Float, _ y: Float) -> Float { guard x > 0 else { if y > 0 { return x * y } else if x == -1337 { return x * x } return 0 } return y * y } expectEqual((0, 10), gradient(at: 4, 5, in: guard2)) expectEqual((5, -1337), gradient(at: -1337, 5, in: guard2)) expectEqual((-2674, 0), gradient(at: -1337, -5, in: guard2)) expectEqual((2, -3), gradient(at: -3, 2, in: guard2)) func guard2_var(_ x: Float, _ y: Float) -> Float { var z = y guard x > 0 else { if y > 0 { z = z * x } else if x == -1337 { z = x z = z * z } else { z = 0 } return z } return z * y } expectEqual((0, 10), gradient(at: 4, 5, in: guard2_var)) expectEqual((5, -1337), gradient(at: -1337, 5, in: guard2_var)) expectEqual((-2674, 0), gradient(at: -1337, -5, in: guard2_var)) expectEqual((2, -3), gradient(at: -3, 2, in: guard2_var)) func guard3(_ x: Float, _ y: Float) -> Float { guard x > 0 else { fatalError() } return y * y } expectEqual((0, 10), gradient(at: 4, 5, in: guard3)) expectCrash { _ = gradient(at: -3, -2, in: guard3) } func cond_empty(_ x: Float) -> Float { if x > 0 { // Create empty trampoline blocks. } return x * x } expectEqual(4, gradient(at: 2, in: cond_empty)) expectEqual(-6, gradient(at: -3, in: cond_empty)) func cond_generic<T : Differentiable & FloatingPoint>( _ x: T, _ y: T ) -> T { if x > 0 { return x } return y } expectEqual((1, 0), gradient(at: 4, 5, in: { x, y in cond_generic(x, y) })) expectEqual((0, 1), gradient(at: -4, 5, in: { x, y in cond_generic(x, y) })) } ControlFlowTests.test("NestedConditionals") { func nested1(_ x: Float) -> Float { if x > 0 { if x > 10 { return x * x + x } else { return x * x } } return x * -x } expectEqual(23, gradient(at: 11, in: nested1)) expectEqual(8, gradient(at: 4, in: nested1)) expectEqual(20, gradient(at: -10, in: nested1)) func nested2(_ x: Float, _ y: Float) -> Float { if x > 0 { if y > 10 { return x * y } else { return x + y } } return -y } expectEqual((20, 4), gradient(at: 4, 20, in: nested2)) expectEqual((1, 1), gradient(at: 4, 5, in: nested2)) expectEqual((0, -1), gradient(at: -3, -2, in: nested2)) func nested3(_ x: Float, _ y: Float) -> Float { if x > 0 { if y > 10 { let z = x * y if z > 100 { return x + z } else if y == 20 { return z + z } } else { return x + y } } return -y } expectEqual((40, 8), gradient(at: 4, 20, in: nested3)) expectEqual((0, -1), gradient(at: 4, 21, in: nested3)) expectEqual((1, 1), gradient(at: 4, 5, in: nested3)) expectEqual((0, -1), gradient(at: -3, -2, in: nested3)) func nested3_var(_ x: Float, _ y: Float) -> Float { var w = y if x > 0 { if y > 10 { var z = x * w if z > 100 { z = x + z return z } else if y == 20 { z = z + z return z } } else { w = x + w return w } } w = -w return w } expectEqual((40, 8), gradient(at: 4, 20, in: nested3)) expectEqual((0, -1), gradient(at: 4, 21, in: nested3)) expectEqual((1, 1), gradient(at: 4, 5, in: nested3)) expectEqual((0, -1), gradient(at: -3, -2, in: nested3)) // TF-781: nested if derivative correctness. do { struct TF_781: Differentiable { var w: Float = 3 @differentiable(wrt: self) // wrt only self is important func callAsFunction(_ input: Float) -> Float { var x = input if true { if true { // Function application below should make `self` have non-zero // derivative. x = x * w } } return x } } let x: Float = 10 expectEqual(TF_781.TangentVector(w: x), gradient(at: TF_781()) { $0(x) }) } // Non-method version of TF-781. do { @differentiable(wrt: x) func TF_781(_ x: Float, _ y: Float) -> Float { var result = y if true { if true { result = result * x } } return result } let x: Float = 10 expectEqual(x, gradient(at: 3) { TF_781($0, x) }) } } ControlFlowTests.test("Recursion") { func factorial(_ x: Float) -> Float { if x == 1 { return 1 } return x * factorial(x - 1) } expectEqual(0, gradient(at: 1, in: factorial)) expectEqual(1, gradient(at: 2, in: factorial)) expectEqual(5, gradient(at: 3, in: factorial)) expectEqual(26, gradient(at: 4, in: factorial)) expectEqual(154, gradient(at: 5, in: factorial)) func factorial_var1(_ x: Float) -> Float { var y: Float = x if x == 1 { y = 1 } else { y = x y = y * factorial_var1(y - 1) } return y } expectEqual(0, gradient(at: 1, in: factorial_var1)) expectEqual(1, gradient(at: 2, in: factorial_var1)) expectEqual(5, gradient(at: 3, in: factorial_var1)) expectEqual(26, gradient(at: 4, in: factorial_var1)) expectEqual(154, gradient(at: 5, in: factorial_var1)) func factorial_var2(_ x: Float) -> Float { // Next line is the only difference with `factorial_var1`. var y: Float = 1 if x == 1 { y = 1 } else { y = x y = y * factorial_var2(y - 1) } return y } expectEqual(0, gradient(at: 1, in: factorial_var2)) expectEqual(1, gradient(at: 2, in: factorial_var2)) expectEqual(5, gradient(at: 3, in: factorial_var2)) expectEqual(26, gradient(at: 4, in: factorial_var2)) expectEqual(154, gradient(at: 5, in: factorial_var2)) func product(_ x: Float, count: Int) -> Float { precondition(count > 0) if count == 1 { return x } return x * product(x, count: count - 1) } expectEqual(300, gradient(at: 10, in: { x in product(x, count: 3) })) expectEqual(-20, gradient(at: -10, in: { x in product(x, count: 2) })) expectEqual(1, gradient(at: 100, in: { x in product(x, count: 1) })) } ControlFlowTests.test("Enums") { enum Enum { case a(Float) case b(Float, Float) func enum_notactive1(_ x: Float) -> Float { switch self { case let .a(a): return x * a case let .b(b1, b2): return x * b1 * b2 } } } func enum_notactive1(_ e: Enum, _ x: Float) -> Float { switch e { case let .a(a): return x * a case let .b(b1, b2): return x * b1 * b2 } } expectEqual(10, gradient(at: 2, in: { x in enum_notactive1(.a(10), x) })) expectEqual(10, gradient(at: 2, in: { x in Enum.a(10).enum_notactive1(x) })) expectEqual(20, gradient(at: 2, in: { x in enum_notactive1(.b(4, 5), x) })) expectEqual(20, gradient(at: 2, in: { x in Enum.b(4, 5).enum_notactive1(x) })) func enum_notactive2(_ e: Enum, _ x: Float) -> Float { var y = x if x > 0 { var z = y + y switch e { case .a: z = z - y case .b: y = y + x } var w = y if case .a = e { w = w + z } return w } else if case .b = e { return y + y } return x + y } expectEqual((8, 2), valueWithGradient(at: 4, in: { x in enum_notactive2(.a(10), x) })) expectEqual((20, 2), valueWithGradient(at: 10, in: { x in enum_notactive2(.b(4, 5), x) })) expectEqual((-20, 2), valueWithGradient(at: -10, in: { x in enum_notactive2(.a(10), x) })) expectEqual((-2674, 2), valueWithGradient(at: -1337, in: { x in enum_notactive2(.b(4, 5), x) })) func optional_notactive1(_ optional: Float?, _ x: Float) -> Float { if let y = optional { return x * y } return x + x } expectEqual(2, gradient(at: 2, in: { x in optional_notactive1(nil, x) })) expectEqual(10, gradient(at: 2, in: { x in optional_notactive1(10, x) })) struct Dense : Differentiable { var w1: Float @noDerivative var w2: Float? @differentiable func callAsFunction(_ input: Float) -> Float { if let w2 = w2 { return input * w1 * w2 } return input * w1 } } expectEqual((Dense.TangentVector(w1: 10), 20), gradient(at: Dense(w1: 4, w2: 5), 2) { dense, x in dense(x) }) expectEqual((Dense.TangentVector(w1: 2), 4), gradient(at: Dense(w1: 4, w2: nil), 2) { dense, x in dense(x) }) indirect enum Indirect { case e(Float, Enum) case indirect(Indirect) } func enum_indirect_notactive1(_ indirect: Indirect, _ x: Float) -> Float { switch indirect { case let .e(f, e): switch e { case .a: return x * f * enum_notactive1(e, x) case .b: return x * f * enum_notactive1(e, x) } case let .indirect(ind): return enum_indirect_notactive1(ind, x) } } do { let ind: Indirect = .e(10, .a(3)) expectEqual(120, gradient(at: 2, in: { x in enum_indirect_notactive1(ind, x) })) expectEqual(120, gradient(at: 2, in: { x in enum_indirect_notactive1(.indirect(ind), x) })) } } ControlFlowTests.test("Loops") { func for_loop(_ x: Float) -> Float { var result = x for _ in 0..<2 { result = result * x } return result } expectEqual((8, 12), valueWithGradient(at: 2, in: for_loop)) expectEqual((27, 27), valueWithGradient(at: 3, in: for_loop)) func for_loop_nonactive_initial_value(_ x: Float) -> Float { var result: Float = 1 for _ in 0..<2 { result = result * x } return result } expectEqual((4, 4), valueWithGradient(at: 2, in: for_loop_nonactive_initial_value)) expectEqual((9, 6), valueWithGradient(at: 3, in: for_loop_nonactive_initial_value)) func while_loop(_ x: Float) -> Float { var result = x var i = 0 while i < 2 { result = result * x i += 1 } return result } expectEqual((8, 12), valueWithGradient(at: 2, in: while_loop)) expectEqual((27, 27), valueWithGradient(at: 3, in: while_loop)) func while_loop_nonactive_initial_value(_ x: Float) -> Float { var result: Float = 1 var i = 0 while i < 2 { result = result * x i += 1 } return result } expectEqual((4, 4), valueWithGradient(at: 2, in: while_loop_nonactive_initial_value)) expectEqual((9, 6), valueWithGradient(at: 3, in: while_loop_nonactive_initial_value)) func repeat_while_loop(_ x: Float) -> Float { var result = x var i = 0 repeat { result = result * x i += 1 } while i < 2 return result } // FIXME(TF-584): Investigate incorrect (too big) gradient values for // repeat-while loops. // expectEqual((8, 12), valueWithGradient(at: 2, in: repeat_while_loop)) // expectEqual((27, 27), valueWithGradient(at: 3, in: repeat_while_loop)) expectEqual((8, 18), valueWithGradient(at: 2, in: repeat_while_loop)) expectEqual((27, 36), valueWithGradient(at: 3, in: repeat_while_loop)) func repeat_while_loop_nonactive_initial_value(_ x: Float) -> Float { var result: Float = 1 var i = 0 repeat { result = result * x i += 1 } while i < 2 return result } // FIXME(TF-584): Investigate incorrect (too big) gradient values for // repeat-while loops. // expectEqual((4, 4), valueWithGradient(at: 2, in: repeat_while_loop_nonactive_initial_value)) // expectEqual((9, 6), valueWithGradient(at: 3, in: repeat_while_loop_nonactive_initial_value)) expectEqual((4, 5), valueWithGradient(at: 2, in: repeat_while_loop_nonactive_initial_value)) expectEqual((9, 7), valueWithGradient(at: 3, in: repeat_while_loop_nonactive_initial_value)) func loop_continue(_ x: Float) -> Float { var result = x for i in 1..<10 { if i.isMultiple(of: 2) { continue } result = result * x } return result } expectEqual((64, 192), valueWithGradient(at: 2, in: loop_continue)) expectEqual((729, 1458), valueWithGradient(at: 3, in: loop_continue)) func loop_break(_ x: Float) -> Float { var result = x for i in 1..<10 { if i.isMultiple(of: 2) { continue } result = result * x } return result } expectEqual((64, 192), valueWithGradient(at: 2, in: loop_break)) expectEqual((729, 1458), valueWithGradient(at: 3, in: loop_break)) func nested_loop1(_ x: Float) -> Float { var outer = x for _ in 0..<2 { outer = outer * x var inner = outer var i = 0 while i < 2 { inner = inner + x i += 1 } outer = inner } return outer } expectEqual((20, 22), valueWithGradient(at: 2, in: nested_loop1)) expectEqual((104, 66), valueWithGradient(at: 4, in: nested_loop1)) func nested_loop2(_ x: Float, count: Int) -> Float { var outer = x outerLoop: for _ in 0..<count { outer = outer * x var inner = outer var i = 0 while i < count { inner = inner + x i += 1 switch Int(inner.truncatingRemainder(dividingBy: 7)) { case 0: break outerLoop case 1: break default: continue } } outer = inner } return outer } expectEqual((6, 5), valueWithGradient(at: 2, in: { x in nested_loop2(x, count: 1) })) expectEqual((20, 22), valueWithGradient(at: 2, in: { x in nested_loop2(x, count: 2) })) expectEqual((52, 80), valueWithGradient(at: 2, in: { x in nested_loop2(x, count: 3) })) expectEqual((24, 28), valueWithGradient(at: 2, in: { x in nested_loop2(x, count: 4) })) } runAllTests()
apache-2.0
ba5527846395c61983d9190cf01a3d5e
27.22067
98
0.560378
3.181546
false
false
false
false
jfosterdavis/Charles
Charles/GameWinnerViewController.swift
1
9088
// // GameWinnerViewController.swift // Charles // // Created by Jacob Foster Davis on 6/4/17. // Copyright © 2017 Zero Mu, LLC. All rights reserved. // import Foundation import UIKit /******************************************************/ /*******************///MARK: Shown to the user when the win the game // Here give the user the chance to go back to level 10 with + 1M in cash /******************************************************/ class GameWinnerViewController: MapCollectionViewController { //@IBOutlet weak var dismissButton: UIButton! @IBOutlet weak var performanceMosaicPerformanceView: PerformanceMosaicView! //var initialLevelToScrollTo = 11 var timer = Timer() var userLevel: Int! var parentVC: DataViewController! var option1Level = 1 var option2Level = 1 var option3Level = 1 @IBOutlet weak var option1Button: UIButton! @IBOutlet weak var option2Button: UIButton! @IBOutlet weak var option3Button: UIButton! //@IBOutlet weak var shareButton: UIButton! override func viewDidLoad() { //super.viewDidLoad() //setupCoreData FRCs _ = setupFetchedResultsController(frcKey: keyXP, entityName: "XP", sortDescriptors: [], predicate: nil) dismissButton.roundCorners(with: 5) shareButton.roundCorners(with: 5) includeDollarSignWhenSharing = true graphicImageView.isHidden = false //always show the icon in this screen graphicImageView.alpha = 0 dismissButton.alpha = 0 option1Button.alpha = 0 option2Button.alpha = 0 option3Button.alpha = 0 shareButton.alpha = 0 disableAllButtons() //based on user level, give player options for option 2 and 3. Option 1 sould stay at 0 option2Level = Int(userLevel / 2) //option 2 goes back halfway //option2Button.setTitle(String(describing: option2Level), for: UIControlState.normal) option3Level = Utilities.random(range: 1...(userLevel - 1)) //option 3 is a random level //option3Button.setTitle(String(describing: option3Level), for: UIControlState.normal) //load the mosaic initialLevelToScrollTo = userLevel playerHasFinishedInitialLevelToScrollTo = true performanceMosaicPerformanceView.tileData = getMosaicData() performanceMosaicPerformanceView.setNeedsDisplay() } override func viewDidLayoutSubviews() { dismissButton.roundCorners() shareButton.roundCorners() option1Button.roundCorners() option2Button.roundCorners() option3Button.roundCorners() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) graphicImageView.fade(.inOrOut, resultAlpha: 0.70, withDuration: 10, delay: 1, completion: {(finished:Bool) in //let the graphic receive taps for fun let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(tapGestureRecognizer:))) self.graphicImageView.isUserInteractionEnabled = true self.graphicImageView.addGestureRecognizer(tapGestureRecognizer) }) //start the timer timer = Timer.scheduledTimer(timeInterval: 12, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) //slowly fade each button in and enable option1Button.fade(.in, withDuration: 5, delay: 20, completion: {(finished:Bool) in self.option1Button.isEnabled = true}) option2Button.fade(.in, withDuration: 5, delay: 23, completion: {(finished:Bool) in self.option2Button.isEnabled = true}) option3Button.fade(.in, withDuration: 5, delay: 26, completion: {(finished:Bool) in self.option3Button.isEnabled = true}) dismissButton.fade(.in, withDuration: 8, delay: 35, completion: {(finished:Bool) in self.dismissButton.isEnabled = true}) shareButton.fade(.in, withDuration: 8, delay: 38, completion: {(finished:Bool) in self.shareButton.isEnabled = true}) } override func viewDidDisappear(_ animated: Bool) { //stop the timer to avoide stacking penalties timer.invalidate() } @objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer) { let tappedImage = tapGestureRecognizer.view as! UIImageView timer.invalidate() //start the timer timer = Timer.scheduledTimer(timeInterval: 12, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) pulse(view: tappedImage) } func disableAllButtons() { dismissButton.isEnabled = false shareButton.isEnabled = false option1Button.isEnabled = false option2Button.isEnabled = false option3Button.isEnabled = false } @IBAction func choiceButtonPressed(_ sender: UIButton) { disableAllButtons() //the choice is made! //determine level to go to var destinationLevel = 1 var bonusCash = 0 switch sender { case let x where x == option1Button: destinationLevel = option1Level case let x where x == option2Button: destinationLevel = option2Level case let x where x == option3Button: destinationLevel = option3Level //give bonus cash for being adventurous bonusCash = 500000 default: destinationLevel = option1Level } //determine cash to give player //player would get 30M for going to level 1 let cashPrize = (30000000 / destinationLevel) + bonusCash //give player this new cash let currentScore = parentVC.getCurrentScore() let resultScore = currentScore + cashPrize parentVC.setCurrentScore(newScore: resultScore) //set the user to the new level parentVC.reducePlayerLevel(to: destinationLevel) fadeAwayAndDismiss() } @IBAction override func dismissButtonPressed(_ sender: Any) { disableAllButtons() //the choice is made. fadeAwayAndDismiss() } // @IBAction func shareButtonPressed(_ sender: Any) { // let imageToShare = getSharabaleMosaicImage() // // let objectsToShare = [imageToShare] as [Any] // // let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) // // //Excluded Activities // activityVC.excludedActivityTypes = [.addToReadingList, .openInIBooks, .postToVimeo, .postToWeibo, .postToTencentWeibo] // // // //activityVC.popoverPresentationController?.sourceView = self as? UIView // self.present(activityVC, animated: true, completion: nil) // // } func fadeAwayAndDismiss() { //slowly fade each button in and enable option1Button.fade(.out, withDuration: 2, delay: 1.5, completion: {(finished:Bool) in self.dismiss(animated: true, completion: nil)}) option2Button.fade(.out, withDuration: 2, delay: 1, completion: nil) option3Button.fade(.out, withDuration: 2, delay: 0.5, completion: nil) shareButton.fade(.out, withDuration: 2, delay: 0, completion: nil) dismissButton.fade(.out, withDuration: 2, delay: 0, completion: nil) } @objc func updateTimer() { pulse(view: graphicImageView) } func pulse(view: UIView) { view.fade(.inOrOut, resultAlpha: 1, withDuration: 1) view.fade(.inOrOut, resultAlpha: 0.70, withDuration: 2, delay: 0.1) } }
apache-2.0
d60a7906c9347a4e6857191e87d9c590
34.357977
155
0.547485
5.396081
false
false
false
false
ReactKit/ReactKitCatalog
ReactKitCatalog-iOS/AppDelegate.swift
2
2358
// // AppDelegate.swift // ReactKitCatalog-iOS // // Created by Yasuhiro Inami on 2014/10/06. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // import UIKit import Alamofire //import BigBrother @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func _setupAppearance() { let font = UIFont(name: "AvenirNext-Medium", size: 16)! UINavigationBar.appearance().titleTextAttributes = [ NSFontAttributeName : font ] UIBarButtonItem.appearance().setTitleTextAttributes([ NSFontAttributeName : font ], forState: .Normal) // UIButton.appearance().titleLabel?.font = font // UILabel.appearance().font = font // UITextField.appearance().font = font // UITextView.appearance().font = font } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // 2015/07/18 comment-out: BigBrother not working in Swift 2 (Xcode7-beta3) // setup BigBrother (networkActivityIndicator) // BigBrother.addToSharedSession() // BigBrother.addToSessionConfiguration(Alamofire.Manager.sharedInstance.session.configuration) self._setupAppearance() let splitVC = self.window!.rootViewController as! UISplitViewController splitVC.delegate = self let mainNavC = splitVC.viewControllers[0] as! UINavigationController // let detailNavC = splitVC.viewControllers[1] as UINavigationController let mainVC = mainNavC.topViewController as! MasterViewController // NOTE: use dispatch_after to check `splitVC.collapsed` after delegation is complete (for iPad) // FIXME: look for better solution dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1_000_000), dispatch_get_main_queue()) { if !splitVC.collapsed { mainVC.showDetailViewControllerAtIndex(0) } } return true } func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { return true } }
mit
43c01288eef018e73212386c406d6b25
36.396825
220
0.686757
5.258929
false
false
false
false
wfilleman/ArraysPlayground
Arrays.playground/Sources/SupportCode.swift
1
885
import Foundation // Open Weather Map API Key public let openWeatherAPIKey = "" // City IDs for Weather API // Scottsdale, AZ = 5313457 // Gilbert, AZ = 5295903 // Flagstaff, AZ = 5294810 // New York, NY = 5128638 public let cityID = "5313457" // Functions // - Convert Kelvin to Fahrenheit public func KtoF(kelvin:NSNumber) -> NSNumber { return NSNumber (integer:Int((kelvin.doubleValue - 273.15) * 1.8 + 32.00)) } // - Convert meters to miles public func metersToMilesPerHour(meters:NSNumber) -> NSNumber { return NSNumber(double: (meters.doubleValue * 0.00062137) * 60 * 60) } // Double Extension to limit the returned number of decimal places extension Double { /// Rounds the double to decimal places value public func roundToPlaces(places:Int) -> Double { let divisor = pow(10.0, Double(places)) return round(self * divisor) / divisor } }
apache-2.0
f23b476a7dcaaf5afc3298e4f27d4eb3
27.580645
78
0.696045
3.627049
false
false
false
false
avtr/bluejay
Bluejay/Bluejay/ReadResult.swift
1
1236
// // ReadResult.swift // Bluejay // // Created by Jeremy Chiang on 2017-01-03. // Copyright © 2017 Steamclock Software. All rights reserved. // import Foundation /// Indicates a successful, cancelled, or failed read attempt, where the success case contains the value read. public enum ReadResult<R> { /// The read is successful and the value read is captured in the associated value. case success(R) /// The read is cancelled for a reason. case cancelled /// The read has failed unexpectedly with an error. case failure(Error) } extension ReadResult where R: Receivable { /// Create a typed read result from raw data. init(dataResult: ReadResult<Data?>) { switch dataResult { case .success(let data): if let data = data { do { self = .success(try R(bluetoothData: data)) } catch { self = .failure(error) } } else { self = .failure(BluejayError.missingData) } case .cancelled: self = .cancelled case .failure(let error): self = .failure(error) } } }
mit
38e22a84d5349c1d085d736268e45e80
26.444444
110
0.561943
4.490909
false
false
false
false
pkrawat1/TravelApp-ios
TravelApp/View/UserProfile/UserMenuBar.swift
1
5642
// // UserMenuBar.swift // TravelApp // // Created by Nitesh on 16/02/17. // Copyright © 2017 Pankaj Rawat. All rights reserved. // import UIKit class UserMenuBar: UIView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate { let cell = "cellID" let profileTabs = ["Trips", "Followers", "Following", "Media"] lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.translatesAutoresizingMaskIntoConstraints = false cv.dataSource = self cv.delegate = self return cv }() var userProfileCell: UserProfileCell! override init(frame: CGRect) { super.init(frame: frame) // SharedData.sharedInstance.homeController?.navigationController?.hidesBarsOnSwipe = true collectionView.register(UserMenuCell.self, forCellWithReuseIdentifier: cell) setupCollectionView() let selectedIndexPath = NSIndexPath(item: 0, section: 0) as IndexPath collectionView.selectItem(at: selectedIndexPath, animated: false, scrollPosition: []) setupHorizontalBar() } func setupCollectionView() { addSubview(collectionView) addConstraintsWithFormat(format: "H:|[v0]|", views: collectionView) addConstraintsWithFormat(format: "V:|[v0]|", views: collectionView) } var horizontalBarLeftAnchor: NSLayoutConstraint? func setupHorizontalBar() { let horizontalBarView = UIView() horizontalBarView.backgroundColor = UIColor.appCallToActionColor() horizontalBarView.translatesAutoresizingMaskIntoConstraints = false addSubview(horizontalBarView) horizontalBarLeftAnchor = horizontalBarView.leftAnchor.constraint(equalTo: self.leftAnchor) horizontalBarLeftAnchor?.isActive = true horizontalBarView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true horizontalBarView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1/4).isActive = true horizontalBarView.heightAnchor.constraint(equalToConstant: 3).isActive = true } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print(indexPath.item) // let x = CGFloat(indexPath.item) * frame.width / 4 // horizontalBarLeftAnchor?.constant = x // // UIView.animate(withDuration: 0.75, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { // self.layoutIfNeeded() // }, completion: nil) // // UIView.animate(withDuration: 0.75) { // self.layoutIfNeeded() // } userProfileCell.scrollToMenuIndex(menuIndex: indexPath) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 4 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cell, for: indexPath) as! UserMenuCell cell.labelView.text = profileTabs[indexPath.item].capitalized return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: frame.width / 4, height: frame.height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class UserMenuCell: BaseCell { let labelView: UILabel = { let labelView = UILabel() labelView.textColor = UIColor.white labelView.font = labelView.font.withSize(12) labelView.text = "Hello" labelView.textAlignment = .center labelView.translatesAutoresizingMaskIntoConstraints = false return labelView }() override var isHighlighted: Bool { didSet { updateViewOnSelectedAndHighlight(status: isHighlighted) } } override var isSelected: Bool { didSet { updateViewOnSelectedAndHighlight(status: isSelected) } } func updateViewOnSelectedAndHighlight(status: Bool) { UIView.animate(withDuration: 0.75, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { if status { self.backgroundColor = UIColor(white: 0.5, alpha: 0.2) } else { self.backgroundColor = UIColor.appBaseColor() } }, completion: nil) } override func setupViews() { super.setupViews() backgroundColor = UIColor.appBaseColor() alpha = 0.7 addSubview(labelView) labelView.heightAnchor.constraint(equalToConstant: 30).isActive = true labelView.widthAnchor.constraint(equalTo: widthAnchor, constant: 2).isActive = true labelView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true labelView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true } }
mit
4ec6fbe673feb8806604cc1ea75bbe17
32.981928
175
0.665662
5.418828
false
false
false
false
oarrabi/Guaka-Generator
Sources/GuakaClILib/GeneratorParts.swift
1
3631
// // generatorStuff.swift // guaka-cli // // Created by Omar Abdelhafith on 12/11/2016. // // import StringScanner import FileUtils public enum GeneratorParts { public static let comamndAddingPlaceholder = " // Command adding placeholder, edit this line" public static let importGuaka = "import Guaka" public static let importPackageDescription = "import PackageDescription" public static let guakaURL = "https://github.com/oarrabi/Guaka.git" public static let guakaVersion = "0" public static let generatedComment = "// Generated, dont update" public static func setupFileContent() -> String { return [ importGuaka, "", generatedComment, "func setupCommands() {", comamndAddingPlaceholder, "}", "" ].joined(separator: "\n") } public static func mainSwiftFileContent() -> String { return [ importGuaka, "", "setupCommands()", "", "rootCommand.execute()", "" ].joined(separator: "\n") } public static func commandFile(forVarName varName: String, commandName: String) -> String { return [ importGuaka, "" , "var \(varName)Command = Command(", " usage: \"\(commandName)\", configuration: configuration, run: execute)", "", "", "private func configuration(command: Command) {", "" , " command.add(flags: [", " // Add your flags here", " ]", " )", "" , " // Other configurations", "}", "", "private func execute(flags: Flags, args: [String]) {", " // Execute code here", " print(\"\(commandName) called\")", "}", "" ].joined(separator: "\n") } public static func packageFile(forCommandName name: String) -> String { return [ importPackageDescription, "let package = Package(", " name: \"\(name)\",", " dependencies: [", " .Package(url: \"\(guakaURL)\", majorVersion: \(guakaVersion)),", " ]", ")", "" ].joined(separator: "\n") } public static func updateSetupFile(withContent content: String, byAddingCommand command: String, withParent parent: String? = nil) throws -> String { guard let indexFound = content.find(string: comamndAddingPlaceholder) else { throw GuakaError.setupFileAltered } var line = "" if let parent = parent { line = " \(parent)Command.add(subCommand: \(command))" } else { line = " rootCommand.add(subCommand: \(command))" } let end = content.index(indexFound, offsetBy: comamndAddingPlaceholder.characters.count) let part1 = content[content.startIndex..<indexFound] let part2 = content[end..<content.endIndex] return part1 + line + "\n\(comamndAddingPlaceholder)" + part2 } public static func commandName(forPassedArgs args: [String]) throws -> String { guard let name = args.first else { throw GuakaError.missingCommandName } guard args.count == 1 else { throw GuakaError.tooManyArgsPassed } if name.characters.contains(" ") { throw GuakaError.wrongCommandNameFormat(name) } return name } public static func projectName(forPassedArgs args: [String]) throws -> String? { switch args.count { case 0: return nil case 1: let name = args.first! if name.characters.contains(" ") { throw GuakaError.wrongCommandNameFormat(name) } return name default: throw GuakaError.tooManyArgsPassed } } }
mit
743f90b68c9dbc919dbd091c8e7aaff3
24.391608
96
0.59653
4.159221
false
false
false
false
ra1028/VueFlux
VueFlux/Internal/DispatcherContext.swift
1
922
/// Shared instance provider for Dispatcher. struct DispatcherContext { static let shared = DispatcherContext() private let dispatchers = AtomicReference([ObjectIdentifier: Any]()) private init() {} /// Provide a shared instance of Dispatcher. /// /// - Parameters: /// - stateType: State protocol conformed type for Dispatcher. /// /// - Returns: An shared instance of Dispatcher. func dispatcher<State: VueFlux.State>(for stateType: State.Type) -> Dispatcher<State> { return dispatchers.modify { dispatchers in let identifier = ObjectIdentifier(stateType) if let dispatcher = dispatchers[identifier] as? Dispatcher<State> { return dispatcher } let dispatcher = Dispatcher<State>() dispatchers[identifier] = dispatcher return dispatcher } } }
mit
497352f8e8fe20a6308a1ca756df1e3f
33.148148
91
0.616052
5.32948
false
false
false
false
FranDepascuali/ProyectoAlimentar
ProyectoAlimentar/Resources/ColorPalette.swift
1
867
// // ColorPalette.swift // ProyectoAlimentar // // Created by Francisco Depascuali on 9/2/16. // Copyright © 2016 Alimentar. All rights reserved. // import UIKit import Core public protocol ColorPaletteType { static var primaryColor: UIColor { get } static var activatedColor: UIColor { get } } private extension UIColor { static let lightOrange = UIColor(hex: "FDB949")! static let darkOrange = UIColor(hex: "F39700")! static let lightGrey = UIColor(hex: "F2F2F2")! } public struct ColorPalette: ColorPaletteType { public static var primaryColor = UIColor.lightOrange public static var activatedColor = UIColor.darkOrange public static var primaryTextColor = UIColor.black public static var secondaryTextColor = UIColor(hex: "9b9b9b")! public static var clearBackgroundColor = UIColor.lightGrey }
apache-2.0
c664cf2abbdfccb180d77890a351c8bd
20.65
66
0.720554
4.084906
false
false
false
false
SheffieldKevin/CustomControlDemo
CustomControlDemo/ViewController.swift
1
1746
// // ViewController.swift // CustomControlDemo // // Created by Kevin Meaney on 06/11/2014. // Copyright (c) 2014 Kevin Meaney. All rights reserved. // import UIKit class ViewController: UIViewController { let jsonRenderer = CustomDial(frame: CGRectZero) var sliderControl:UISlider = UISlider(frame: CGRectZero) override func viewDidLoad() { super.viewDidLoad() view.addSubview(jsonRenderer) view.addSubview(sliderControl) sliderControl.addTarget(self, action: "controlValueChanged:", forControlEvents: .ValueChanged) jsonRenderer.addTarget(self, action: "controlValueChanged:", forControlEvents: .ValueChanged) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func controlValueChanged(control: UIControl) { if let slider = control as? UISlider { // println("Range slider value changed: \(slider.value)") jsonRenderer.currentValue = CGFloat(slider.value) jsonRenderer.drawTrack() } else if let customDial = control as? CustomDial { // println("Custom dial value changed: \(customDial.currentValue)") sliderControl.value = Float(customDial.currentValue) jsonRenderer.drawTrack() } } override func viewDidLayoutSubviews() { self.jsonRenderer.frame = CGRect(x: 20, y: 20, width: 200, height: 200) self.sliderControl.frame = CGRect(x: 20, y: 240, width: 200, height: 20) jsonRenderer.currentValue = CGFloat(self.sliderControl.value) jsonRenderer.drawTrack() } }
mit
eba9b71d86722144e32160ab25d1738d
33.92
80
0.644903
4.731707
false
false
false
false
benlangmuir/swift
test/Constraints/diagnostics.swift
1
72078
// RUN: %target-typecheck-verify-swift protocol P { associatedtype SomeType } protocol P2 { func wonka() } extension Int : P { typealias SomeType = Int } extension Double : P { typealias SomeType = Double } func f0(_ x: Int, _ y: Float) { } func f1(_: @escaping (Int, Float) -> Int) { } func f2(_: (_: (Int) -> Int)) -> Int {} func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {} func f4(_ x: Int) -> Int { } func f5<T : P2>(_ : T) { } // expected-note@-1 {{required by global function 'f5' where 'T' = '(Int) -> Int'}} // expected-note@-2 {{required by global function 'f5' where 'T' = '(Int, String)'}} // expected-note@-3 {{required by global function 'f5' where 'T' = 'Int.Type'}} // expected-note@-4 {{where 'T' = 'Int'}} func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {} var i : Int var d : Double // Check the various forms of diagnostics the type checker can emit. // Tuple size mismatch. f1( f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}} ) // Tuple element unused. f0(i, i, // expected-error@:7 {{cannot convert value of type 'Int' to expected argument type 'Float'}} i) // expected-error{{extra argument in call}} // Cannot conform to protocols. f5(f4) // expected-error {{type '(Int) -> Int' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} f5((1, "hello")) // expected-error {{type '(Int, String)' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} f5(Int.self) // expected-error {{type 'Int.Type' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} // Tuple element not convertible. f0(i, d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}} ) // Function result not a subtype. f1( f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}} ) f3( f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}} ) f4(i, d) // expected-error {{extra argument in call}} // Missing member. i.missingMember() // expected-error{{value of type 'Int' has no member 'missingMember'}} // Generic member does not conform. extension Int { func wibble<T: P2>(_ x: T, _ y: T) -> T { return x } // expected-note {{where 'T' = 'Int'}} func wubble<T>(_ x: (Int) -> T) -> T { return x(self) } } i.wibble(3, 4) // expected-error {{instance method 'wibble' requires that 'Int' conform to 'P2'}} // Generic member args correct, but return type doesn't match. struct A : P2 { func wonka() {} } let a = A() for j in i.wibble(a, a) { // expected-error {{for-in loop requires 'A' to conform to 'Sequence'}} } // Generic as part of function/tuple types func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}} return (c: 0, i: g(())) } func f7() -> (c: Int, v: A) { let g: (Void) -> A = { _ in return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}} return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}} } func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{where 'T' = 'Int'}} // expected-note@-1 {{required by global function 'f8' where 'T' = '(Int, Double)'}} f8(3, f4) // expected-error {{global function 'f8' requires that 'Int' conform to 'P2'}} typealias Tup = (Int, Double) func f9(_ x: Tup) -> Tup { return x } f8((1,2.0), f9) // expected-error {{type '(Int, Double)' cannot conform to 'P2'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} // <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals 1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}} [1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}} "awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}} // Does not conform to protocol. f5(i) // expected-error {{global function 'f5' requires that 'Int' conform to 'P2'}} // Make sure we don't leave open existentials when diagnosing. // <rdar://problem/20598568> func pancakes(_ p: P2) { f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}} f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}} } protocol Shoes { static func select(_ subject: Shoes) -> Self } // Here the opaque value has type (metatype_type (archetype_type ... )) func f(_ x: Shoes, asType t: Shoes.Type) { return t.select(x) // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } precedencegroup Starry { associativity: left higherThan: MultiplicationPrecedence } infix operator **** : Starry func ****(_: Int, _: String) { } i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} infix operator ***~ : Starry func ***~(_: Int, _: String) { } i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} @available(*, unavailable, message: "call the 'map()' method on the sequence") public func myMap<C : Collection, T>( // expected-note {{'myMap' has been explicitly marked unavailable here}} _ source: C, _ transform: (C.Iterator.Element) -> T ) -> [T] { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "call the 'map()' method on the optional value") public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? { fatalError("unavailable function can't be called") } // <rdar://problem/20142523> func rdar20142523() { _ = myMap(0..<10, { x in // expected-error {{'myMap' is unavailable: call the 'map()' method on the sequence}} () return x }) } // <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral func rdar21080030() { var s = "Hello" // https://github.com/apple/swift/issues/50141 // This should be 'cannot_call_non_function_value'. if s.count() == 0 {} // expected-error{{cannot call value of non-function type 'Int'}} {{13-15=}} } // <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136()'}} r21248136() // expected-error {{generic parameter 'T' could not be inferred}} let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}} // <rdar://problem/17080659> Error Message QOI - wrong return type in an overload func recArea(_ h: Int, w : Int) { return h * w // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong func r17224804(_ monthNumber : Int) { // expected-error@+1:49 {{cannot convert value of type 'Int' to expected argument type 'String'}} let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber) } // <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?' func r17020197(_ x : Int?, y : Int) { if x! { } // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} // <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible if y {} // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} } // <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different func validateSaveButton(_ text: String) { return (text.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}} expected-note {{did you mean to add a return type?}} } // <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype class r20201968C { func blah() { r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}} } } // <rdar://problem/21459429> QoI: Poor compilation error calling assert func r21459429(_ a : Int) { assert(a != nil, "ASSERT COMPILATION ERROR") // expected-warning @-1 {{comparing non-optional value of type 'Int' to 'nil' always returns true}} } // <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an argument of type 'Int' struct StructWithOptionalArray { var array: [Int]? } func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int { return foo.array[0] // expected-error {{value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'}} // expected-note@-1{{chain the optional using '?' to access member 'subscript' only for non-'nil' base values}}{{19-19=?}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{19-19=!}} } // <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}} // <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf String().asdf // expected-error {{value of type 'String' has no member 'asdf'}} // <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment protocol r21553065Protocol {} class r21553065Class<T : AnyObject> {} // expected-note{{requirement specified as 'T' : 'AnyObject'}} _ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Class' requires that 'any r21553065Protocol' be a class type}} // Type variables not getting erased with nested closures struct Toe { let toenail: Nail // expected-error {{cannot find type 'Nail' in scope}} func clip() { toenail.inspect { x in toenail.inspect { y in } } } } // <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic class r21447318 { var x = 42 func doThing() -> r21447318 { return self } } func test21447318(_ a : r21447318, b : () -> r21447318) { a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}} b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}} } // <rdar://problem/20409366> Diagnostics for init calls should print the class name class r20409366C { init(a : Int) {} init?(a : r20409366C) { let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}} } } // <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match func r18800223(_ i : Int) { // 20099385 _ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}} // 19648528 _ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}} var buttonTextColor: String? _ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{result values in '? :' expression have mismatching types 'Int' and '(_) -> _'}} } // <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back _ = { $0 } // expected-error {{unable to infer type of a closure parameter '$0' in the current context}} _ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}} _ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}} // <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure. func rdar21784170() { let initial = (1.0 as Double, 2.0 as Double) (Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}} } // Diagnose passing an array in lieu of variadic parameters func variadic(_ x: Int...) {} func variadicArrays(_ x: [Int]...) {} func variadicAny(_ x: Any...) {} struct HasVariadicSubscript { subscript(_ x: Int...) -> Int { get { 0 } } } let foo = HasVariadicSubscript() let array = [1,2,3] let arrayWithOtherEltType = ["hello", "world"] variadic(array) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} variadic([1,2,3]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{10-11=}} {{16-17=}} variadic([1,2,3,]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{10-11=}} {{16-17=}} {{17-18=}} variadic(0, array, 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} variadic(0, [1,2,3], 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{13-14=}} {{19-20=}} variadic(0, [1,2,3,], 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{13-14=}} {{19-20=}} {{20-21=}} variadic(arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type 'Int'}} variadic(1, arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type 'Int'}} // FIXME: https://github.com/apple/swift/issues/53499 variadic(["hello", "world"]) // expected-error 2 {{cannot convert value of type 'String' to expected element type 'Int'}} // expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-2 {{remove brackets to pass array elements directly}} variadic([1] + [2] as [Int]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} foo[array] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} foo[[1,2,3]] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{5-6=}} {{11-12=}} foo[0, [1,2,3], 4] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-1 {{remove brackets to pass array elements directly}} {{8-9=}} {{14-15=}} variadicAny(array) variadicAny([1,2,3]) variadicArrays(array) variadicArrays([1,2,3]) variadicArrays(arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type '[Int]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} variadicArrays(1,2,3) // expected-error 3 {{cannot convert value of type 'Int' to expected argument type '[Int]'}} protocol Proto {} func f<T: Proto>(x: [T]) {} func f(x: Int...) {} f(x: [1,2,3]) // TODO(diagnostics): Diagnose both the missing conformance and the disallowed array splat to cover both overloads. // expected-error@-2 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}} // expected-note@-3 {{remove brackets to pass array elements directly}} // <rdar://problem/21829141> BOGUS: unexpected trailing closure func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } } func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } } let expectType1 = expect(Optional(3))(Optional<Int>.self) let expectType1Check: Int = expectType1 // <rdar://problem/19804707> Swift Enum Scoping Oddity func rdar19804707() { enum Op { case BinaryOperator((Double, Double) -> Double) } var knownOps : Op knownOps = Op.BinaryOperator({$1 - $0}) knownOps = Op.BinaryOperator(){$1 - $0} knownOps = Op.BinaryOperator{$1 - $0} knownOps = .BinaryOperator({$1 - $0}) // rdar://19804707 - trailing closures for contextual member references. knownOps = .BinaryOperator(){$1 - $0} knownOps = .BinaryOperator{$1 - $0} _ = knownOps } // <rdar://problem/20491794> Error message does not tell me what the problem is enum Color { case Red case Unknown(description: String) static func rainbow() -> Color {} static func overload(a : Int) -> Color {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(a:)')}} // expected-note@-1 {{candidate expects value of type 'Int' for parameter #1 (got 'Double')}} static func overload(b : Int) -> Color {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(b:)')}} // expected-note@-1 {{candidate expects value of type 'Int' for parameter #1 (got 'Double')}} static func frob(_ a : Int, b : inout Int) -> Color {} static var svar: Color { return .Red } } let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error@-1 {{cannot convert value of type 'Array<(Int, _)>' to specified type '(Int, Color)'}} // expected-error@-2 {{cannot infer contextual base in reference to member 'Unknown'}} let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }} let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }} let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }} let _: Color = .Unknown // expected-error {{member 'Unknown(description:)' expects argument of type 'String'}} let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}} // expected-error@-1 {{cannot convert value of type 'Int' to expected argument type 'String'}} let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}} let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type '(Double, Float)' to specified type '(Int, Float)'}} let _ : Color = .rainbow // expected-error {{member 'rainbow()' is a function that produces expected type 'Color'; did you mean to call it?}} {{25-25=()}} let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .overload(1.0) // expected-error {{no exact matches in call to static method 'overload'}} let _: Color = .overload(1) // expected-error {{no exact matches in call to static method 'overload'}} let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}} // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}} // expected-error@-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{28-28=&}} let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}} // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'?}} someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'?}} someColor = .svar() // expected-error {{cannot call value of non-function type 'Color'}} someColor = .svar(1) // expected-error {{cannot call value of non-function type 'Color'}} func testTypeSugar(_ a : Int) { typealias Stride = Int let x = Stride(a) x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } // <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr func r21974772(_ y : Int) { let x = &(1.0 + y) // expected-error {{'&' may only be used to pass an argument to inout parameter}} } // <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc protocol r22020088P {} func r22020088Foo<T>(_ t: T) {} func r22020088bar(_ p: r22020088P?) { r22020088Foo(p.fdafs) // expected-error {{value of type '(any r22020088P)?' has no member 'fdafs'}} } // <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type func f(_ arguments: [String]) -> [ArraySlice<String>] { return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" }) } struct AOpts : OptionSet { let rawValue : Int } class B { func function(_ x : Int8, a : AOpts) {} func f2(_ a : AOpts) {} static func f1(_ a : AOpts) {} } class GenClass<T> {} struct GenStruct<T> {} enum GenEnum<T> {} func test(_ a : B) { B.f1(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}} a.function(42, a: nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}} a.function(42, nil) // expected-error {{missing argument label 'a:' in call}} // expected-error@-1 {{'nil' is not compatible with expected argument type 'AOpts'}} a.f2(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}} func foo1(_ arg: Bool) -> Int {return nil} func foo2<T>(_ arg: T) -> GenClass<T> {return nil} func foo3<T>(_ arg: T) -> GenStruct<T> {return nil} func foo4<T>(_ arg: T) -> GenEnum<T> {return nil} // expected-error@-4 {{'nil' is incompatible with return type 'Int'}} // expected-error@-4 {{'nil' is incompatible with return type 'GenClass<T>'}} // expected-error@-4 {{'nil' is incompatible with return type 'GenStruct<T>'}} // expected-error@-4 {{'nil' is incompatible with return type 'GenEnum<T>'}} let clsr1: () -> Int = {return nil} let clsr2: () -> GenClass<Bool> = {return nil} let clsr3: () -> GenStruct<String> = {return nil} let clsr4: () -> GenEnum<Double?> = {return nil} // expected-error@-4 {{'nil' is not compatible with closure result type 'Int'}} // expected-error@-4 {{'nil' is not compatible with closure result type 'GenClass<Bool>'}} // expected-error@-4 {{'nil' is not compatible with closure result type 'GenStruct<String>'}} // expected-error@-4 {{'nil' is not compatible with closure result type 'GenEnum<Double?>'}} var number = 0 var genClassBool = GenClass<Bool>() var funcFoo1 = foo1 number = nil genClassBool = nil funcFoo1 = nil // expected-error@-3 {{'nil' cannot be assigned to type 'Int'}} // expected-error@-3 {{'nil' cannot be assigned to type 'GenClass<Bool>'}} // expected-error@-3 {{'nil' cannot be assigned to type '(Bool) -> Int'}} } // <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure typealias MyClosure = ([Int]) -> Bool func r21684487() { var closures = Array<MyClosure>() let testClosure = {(list: [Int]) -> Bool in return true} let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions;}} } // <rdar://problem/18397777> QoI: special case comparisons with nil func r18397777(_ d : r21447318?) { let c = r21447318() if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to 'nil' always returns true}} } if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}} } if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{8-8= == nil)}} } if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{18-18= == nil)}} } } // <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list func r22255907_1<T>(_ a : T, b : Int) {} func r22255907_2<T>(_ x : Int, a : T, b: Int) {} func reachabilityForInternetConnection() { var variable: Int = 42 r22255907_1(&variable, b: 2) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}} r22255907_2(1, a: &variable, b: 2)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}} } // <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}} _ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}} // <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init func r22263468(_ a : String?) { typealias MyTuple = (Int, String) // TODO(diagnostics): This is a regression from diagnosing missing optional unwrap for `a`, we have to // re-think the way errors in tuple elements are detected because it's currently impossible to detect // exactly what went wrong here and aggregate fixes for different elements at the same time. _ = MyTuple(42, a) // expected-error {{tuple type '(Int, String?)' is not convertible to tuple type 'MyTuple' (aka '(Int, String)')}} } func testTupleConstructionInOutArg() { typealias II = (Int, Int) var i = 0 _ = (Int, Int)(&i, 0) // expected-error {{'&' may only be used to pass an argument to inout parameter}} _ = II(&i, 0) // expected-error {{'&' may only be used to pass an argument to inout parameter}} _ = II(&i, &i) // expected-error 2{{'&' may only be used to pass an argument to inout parameter}} } // rdar://71829040 - "ambiguous without more context" error for tuple type mismatch. func r71829040() { func object(forKey: String) -> Any? { nil } let flags: [String: String] // expected-error@+1 {{tuple type '(String, Bool)' is not convertible to tuple type '(String, String)'}} flags = Dictionary(uniqueKeysWithValues: ["keyA", "keyB"].map { ($0, object(forKey: $0) as? Bool ?? false) }) } // rdar://22470302 - Crash with parenthesized call result. class r22470302Class { func f() {} } func r22470302(_ c: r22470302Class) { print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}} } // <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile extension String { @available(*, unavailable, message: "calling this is unwise") func unavail<T : Sequence> // expected-note {{'unavail' has been explicitly marked unavailable here}} (_ a : T) -> String where T.Iterator.Element == String {} } extension Array { func g() -> String { return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}} } func h() -> String { return "foo".unavail([0]) // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}} } } // <rdar://problem/22519983> QoI: Weird error when failing to infer archetype func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {} // expected-note @-1 {{in call to function 'safeAssign'}} let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure struct Radar21692808<Element> { init(count: Int, value: Element) {} // expected-note {{'init(count:value:)' declared here}} } func radar21692808() -> Radar21692808<Int> { return Radar21692808<Int>(count: 1) { // expected-error {{trailing closure passed to parameter of type 'Int' that does not accept a closure}} return 1 } } // <rdar://problem/17557899> - This shouldn't suggest calling with (). func someOtherFunction() {} func someFunction() -> () { // Producing an error suggesting that this return someOtherFunction // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic func r23560128() { var a : (Int,Int)? a.0 = 42 // expected-error{{value of optional type '(Int, Int)?' must be unwrapped to refer to member '0' of wrapped base type '(Int, Int)'}} // expected-note@-1{{chain the optional }} } // <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping struct ExampleStruct21890157 { var property = "property" } var example21890157: ExampleStruct21890157? example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' must be unwrapped to refer to member 'property' of wrapped base type 'ExampleStruct21890157'}} // expected-note@-1{{chain the optional }} struct UnaryOp {} _ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}} // expected-note@-1 {{overloads for '-' exist with these partially matching parameter lists: (Double), (Float)}} // <rdar://problem/23433271> Swift compiler segfault in failure diagnosis func f23433271(_ x : UnsafePointer<Int>) {} func segfault23433271(_ a : UnsafeMutableRawPointer) { f23433271(a[0]) // expected-error {{value of type 'UnsafeMutableRawPointer' has no subscripts}} } // <rdar://problem/23272739> Poor diagnostic due to contextual constraint func r23272739(_ contentType: String) { let actualAcceptableContentTypes: Set<String> = [] return actualAcceptableContentTypes.contains(contentType) // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets func r23641896() { var g = "Hello World" g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<String.Index>'}} _ = g[12] // expected-error {{'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.}} } // <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note func test17875634() { var match: [(Int, Int)] = [] var row = 1 var col = 2 match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}} } // <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values enum AssocTest { case one(Int) } // FIXME(rdar://problem/65688291) - on iOS simulator this diagnostic is flaky, // either `referencing operator function '==' on 'Equatable'` or `operator function '==' requires` if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{requires that 'AssocTest' conform to 'Equatable'}} // expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}} // <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types func r24251022() { var a = 1 var b: UInt32 = 2 _ = a + b // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UInt32, UInt32)}} a += a + b // expected-error {{cannot convert value of type 'UInt32' to expected argument type 'Int'}} a += b // expected-error@:8 {{cannot convert value of type 'UInt32' to expected argument type 'Int'}} } func overloadSetResultType(_ a : Int, b : Int) -> Int { // https://twitter.com/_jlfischer/status/712337382175952896 // TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}} } postfix operator +++ postfix func +++ <T>(_: inout T) -> T { fatalError() } // <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) { let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}} _ = bytes[i+++] // expected-error {{cannot pass immutable value to mutating operator: 'i' is a 'let' constant}} } // https://github.com/apple/swift/issues/44203 // Wrong error description when using '===' on non-class types class C_44203 { func f(bytes : UnsafeMutablePointer<Int>, _ i : Int?) { _ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}} _ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}} _ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}} _ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}} _ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}} _ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}} } } func nilComparison(i: Int, o: AnyObject) { _ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}} _ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}} _ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}} _ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}} // FIXME(integers): uncomment these tests once the < is no longer ambiguous // _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}} // _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}} _ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}} _ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}} } // <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion func testImplConversion(a : Float?) -> Bool {} func testImplConversion(a : Int?) -> Bool { let someInt = 42 let a : Int = testImplConversion(someInt) // expected-error {{missing argument label 'a:' in call}} {{36-36=a: }} // expected-error@-1 {{cannot convert value of type 'Bool' to specified type 'Int'}} } // <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands class Foo23752537 { var title: String? var message: String? } extension Foo23752537 { func isEquivalent(other: Foo23752537) { // TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" // expected-error@+1 {{unexpected non-void return value in void function}} return (self.title != other.title && self.message != other.message) // expected-note {{did you mean to add a return type?}} } } // <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands" func rdar27391581(_ a : Int, b : Int) -> Int { return a == b && b != 0 // expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}} } // <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {} func read<T : BinaryInteger>() -> T? { var buffer : T let n = withUnsafeMutablePointer(to: &buffer) { (p) in read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<T>' to expected argument type 'UnsafeMutableRawPointer'}} } } func f23213302() { var s = Set<Int>() s.subtract(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}} } // <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context func rdar24202058(a : Int) { return a <= 480 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // https://github.com/apple/swift/issues/44361 // Warning about unused result with ternary operator do { struct S { func foo() {} } let x: S? // Don't generate a warning about unused result since 'foo' returns 'Void'. true ? nil : x?.foo() } // Make sure RawRepresentable fix-its don't crash in the presence of type variables class NSCache<K, V> { func object(forKey: K) -> V? {} } class CacheValue { func value(x: Int) -> Int {} // expected-note {{found candidate with type '(Int) -> Int'}} func value(y: String) -> String {} // expected-note {{found candidate with type '(String) -> String'}} } func valueForKey<K>(_ key: K) -> CacheValue? { let cache = NSCache<K, CacheValue>() return cache.object(forKey: key)?.value // expected-error {{no exact matches in reference to instance method 'value'}} } // https://github.com/apple/swift/issues/43863 do { func f1() { return true || false // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } func f2() -> Int { return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}} } // Diagnostic message for initialization with binary operations as right side. let _: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} let _: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}} let _: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}} let _: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}} } // https://github.com/apple/swift/issues/44815 do { struct S { func bar(value: UInt) {} } let foo = S() let a: Int = 1 let b: Int = 2 let result = a / b foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} foo.bar(value: UInt(result)) // Ok } // https://github.com/apple/swift/issues/44772 // Erroneous diagnostic when unable to infer generic type do { struct S<A, B> { // expected-note 4 {{'B' declared as parameter to type 'S'}} expected-note 2 {{'A' declared as parameter to type 'S'}} expected-note * {{generic type 'S' declared here}} init(a: A) {} init(b: B) {} init(c: Int) {} init(_ d: A) {} init(e: A?) {} } struct S_Array<A, B> { // expected-note {{'B' declared as parameter to type 'S_Array'}} expected-note * {{generic type 'S_Array' declared here}} init(_ a: [A]) {} } struct S_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'S_Dict'}} expected-note * {{generic type 'S_Dict' declared here}} init(a: [A: Double]) {} } S(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} S(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} S(c: 2) // expected-error@-1 {{generic parameter 'A' could not be inferred}} // expected-error@-2 {{generic parameter 'B' could not be inferred}} // expected-note@-3 {{explicitly specify the generic arguments to fix this issue}} {{4-4=<Any, Any>}} S(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} S_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} S(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} S_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} S<Int>(a: 0) // expected-error {{generic type 'S' specialized with too few type parameters (got 1, but expected 2)}} S<Int>(b: 1) // expected-error {{generic type 'S' specialized with too few type parameters (got 1, but expected 2)}} let _ = S<Int, Bool>(a: 0) // Ok let _ = S<Int, Bool>(b: true) // Ok S<Int, Bool, Float>(a: 0) // expected-error {{generic type 'S' specialized with too many type parameters (got 3, but expected 2)}} S<Int, Bool, Float>(b: 0) // expected-error {{generic type 'S' specialized with too many type parameters (got 3, but expected 2)}} } // <rdar://problem/29850459> Swift compiler misreports type error in ternary expression let r29850459_flag = true let r29850459_a: Int = 0 let r29850459_b: Int = 1 func r29850459() -> Bool { return false } let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} // https://github.com/apple/swift/issues/48822 // Tailored diagnostics with fixits for numerical conversions do { enum Foo: Int { case bar } // expected-error@+1 {{cannot convert value of type 'Float' to expected argument type 'Int'}} {{35-35=Int(}} {{43-43=)}} let _: Int = Foo.bar.rawValue * Float(0) // expected-error@+1 {{cannot convert value of type 'Int' to expected argument type 'Float'}} {{18-18=Float(}} {{34-34=)}} let _: Float = Foo.bar.rawValue * Float(0) // expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{none}} // expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}} Foo.bar.rawValue * Float(0) } do { let lhs = Float(3) let rhs = Int(0) // expected-error@+1 {{cannot convert value of type 'Int' to expected argument type 'Float'}} {{24-24=Float(}} {{27-27=)}} let _: Float = lhs * rhs // expected-error@+1 {{cannot convert value of type 'Float' to expected argument type 'Int'}} {{16-16=Int(}} {{19-19=)}} let _: Int = lhs * rhs // expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{none}} // expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}} lhs * rhs } do { // expected-error@+1 {{cannot convert value of type 'String' to expected argument type 'Int'}} {{none}} Int(3) * "0" struct S {} // expected-error@+1 {{cannot convert value of type 'S' to expected argument type 'Int'}} {{none}} Int(10) * S() } // FIXME: Operator lookup does not reach local types, so this must be a // top-level struct (https://github.com/apple/swift/issues/51378). struct S_48822: ExpressibleByIntegerLiteral { typealias IntegerLiteralType = Int init(integerLiteral: Int) {} static func +(lhs: S_48822, rhs: Int) -> Float { return 42.0 } } do { let x: Float = 1.0 // expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'S_48822' and 'Float'}} {{none}} // expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (S_48822, Int)}} let _: Float = S_48822(integerLiteral: 42) + x // expected-error@+1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} {{48-48=Int(}} {{52-52=)}} let _: Float = S_48822(integerLiteral: 42) + 42.0 // expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'S_48822' and 'Float'}} {{none}} // expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (S_48822, Int)}} let _: Float = S_48822(integerLiteral: 42) + x + 1.0 } // Ambiguous overload inside a trailing closure func ambiguousCall() -> Int {} // expected-note {{found this candidate}} func ambiguousCall() -> Float {} // expected-note {{found this candidate}} func takesClosure(fn: () -> ()) {} takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}} // https://github.com/apple/swift/issues/47269 // Useless diagnostics calling non-static method class C1_47269 { private static func foo(x: Int, y: Bool) { self.bar(x: x) // expected-error@-1 {{instance member 'bar' cannot be used on type 'C1_47269'}} } private func bar(x: Int) { } } class C2_47269 { static func a() { self.f(x: 3, y: true) // expected-error@-1 {{instance member 'f' cannot be used on type 'C2_47269'}} } private func f(a: Int, b: Bool, c: String) { self.f(x: a, y: b) } private func f(x: Int, y: Bool) { } } // rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful struct R32101765 { let prop32101765 = 0 } let _: KeyPath<R32101765, Float> = \.prop32101765 // expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}} let _: KeyPath<R32101765, Float> = \R32101765.prop32101765 // expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}} let _: KeyPath<R32101765, Float> = \.prop32101765.unknown // expected-error@-1 {{type 'Int' has no member 'unknown'}} let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown // expected-error@-1 {{type 'Int' has no member 'unknown'}} // rdar://problem/32390726 - Bad Diagnostic: Don't suggest `var` to `let` when binding inside for-statement for var i in 0..<10 { // expected-warning {{variable 'i' was never mutated; consider removing 'var' to make it constant}} {{5-9=}} _ = i + 1 } // https://github.com/apple/swift/issues/47621 // Attempting to return result of 'reduce(_:_:)' in a method with no return // produces ambiguous error func f_47621() { let doubles: [Double] = [1, 2, 3] return doubles.reduce(0, +) // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} } // rdar://problem/32934129 - QoI: misleading diagnostic class L_32934129<T : Comparable> { init(_ value: T) { self.value = value } init(_ value: T, _ next: L_32934129<T>?) { self.value = value self.next = next } var value: T var next: L_32934129<T>? = nil func length() -> Int { func inner(_ list: L_32934129<T>?, _ count: Int) { guard let list = list else { return count } // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}} return inner(list.next, count + 1) } return inner(self, 0) // expected-error {{cannot convert return expression of type '()' to return type 'Int'}} } } // rdar://problem/31671195 - QoI: erroneous diagnostic - cannot call value of non-function type class C_31671195 { var name: Int { fatalError() } func name(_: Int) { fatalError() } } C_31671195().name(UInt(0)) // expected-error@-1 {{cannot convert value of type 'UInt' to expected argument type 'Int'}} // rdar://problem/28456467 - QoI: erroneous diagnostic - cannot call value of non-function type class AST_28456467 { var hasStateDef: Bool { return false } } protocol Expr_28456467 {} class ListExpr_28456467 : AST_28456467, Expr_28456467 { let elems: [Expr_28456467] init(_ elems:[Expr_28456467] ) { self.elems = elems } override var hasStateDef: Bool { return elems.first(where: { $0.hasStateDef }) != nil // expected-error@-1 {{value of type 'any Expr_28456467' has no member 'hasStateDef'}} } } // https://github.com/apple/swift/issues/47657 do { var a = ["1", "2", "3", "4", "5"] var b = [String]() b = a[2...4] // expected-error {{cannot assign value of type 'ArraySlice<String>' to type '[String]'}} } // TODO(diagnostics):Figure out what to do when expressions are complex and completely broken func rdar17170728() { var i: Int? = 1 var j: Int? var k: Int? = 2 let _ = [i, j, k].reduce(0 as Int?) { $0 && $1 ? $0! + $1! : ($0 ? $0! : ($1 ? $1! : nil)) // expected-error@-1 4 {{optional type 'Int?' cannot be used as a boolean; test for '!= nil' instead}} } let _ = [i, j, k].reduce(0 as Int?) { // expected-error {{missing argument label 'into:' in call}} // expected-error@-1 {{cannot convert value of type 'Int?' to expected argument type '(inout @escaping (Bool, Bool) -> Bool?, Int?) throws -> ()'}} $0 && $1 ? $0 + $1 : ($0 ? $0 : ($1 ? $1 : nil)) // expected-error@-1 {{binary operator '+' cannot be applied to two 'Bool' operands}} } } // https://github.com/apple/swift/issues/48493 // Failure to emit diagnostic for bad generic constraints func elephant<T, U>(_: T) where T : Collection, T.Element == U, T.Element : Hashable {} // expected-note {{where 'U' = 'T'}} func platypus<T>(a: [T]) { _ = elephant(a) // expected-error {{global function 'elephant' requires that 'T' conform to 'Hashable'}} } // Another case of the above. func badTypes() { let sequence:AnySequence<[Int]> = AnySequence() { AnyIterator() { [3] }} // Notes, attached to declarations, explain that there is a difference between Array.init(_:) and // RangeReplaceableCollection.init(_:) which are both applicable in this case. let array = [Int](sequence) // expected-error@-1 {{no exact matches in call to initializer}} } // rdar://34357545 func unresolvedTypeExistential() -> Bool { return (Int.self==_{}) // expected-error@-1 {{could not infer type for placeholder}} // expected-error@-2 {{type placeholder not allowed here}} } do { struct Array {} let foo: Swift.Array = Array() // expected-error {{cannot convert value of type 'Array' to specified type 'Array<Element>'}} // expected-error@-1 {{generic parameter 'Element' could not be inferred}} struct Error {} let bar: Swift.Error = Error() //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz: (Swift.Error) = Error() //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz2: Swift.Error = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz3: (Swift.Error) = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} let baz4: ((Swift.Error)) = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}} } // SyntaxSugarTypes with unresolved types func takesGenericArray<T>(_ x: [T]) {} takesGenericArray(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}} func takesNestedGenericArray<T>(_ x: [[T]]) {} takesNestedGenericArray(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[[Int]]'}} func takesSetOfGenericArrays<T>(_ x: Set<[T]>) {} takesSetOfGenericArrays(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<[Int]>'}} func takesArrayOfSetOfGenericArrays<T>(_ x: [Set<[T]>]) {} takesArrayOfSetOfGenericArrays(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Set<[Int]>]'}} func takesArrayOfGenericOptionals<T>(_ x: [T?]) {} takesArrayOfGenericOptionals(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int?]'}} func takesGenericDictionary<T, U>(_ x: [T : U]) {} // expected-note {{in call to function 'takesGenericDictionary'}} takesGenericDictionary(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '[T : U]'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} // expected-error@-2 {{generic parameter 'U' could not be inferred}} typealias Z = Int func takesGenericDictionaryWithTypealias<T>(_ x: [T : Z]) {} // expected-note {{in call to function 'takesGenericDictionaryWithTypealias'}} takesGenericDictionaryWithTypealias(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '[T : Z]'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} func takesGenericFunction<T>(_ x: ([T]) -> Void) {} // expected-note {{in call to function 'takesGenericFunction'}} takesGenericFunction(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '([T]) -> Void'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} func takesTuple<T>(_ x: ([T], [T])) {} // expected-note {{in call to function 'takesTuple'}} takesTuple(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '([T], [T])'}} // expected-error@-1 {{generic parameter 'T' could not be inferred}} // Void function returns non-void result fix-it func voidFunc() { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{16-16= -> <#Return Type#>}} } func voidFuncWithArgs(arg1: Int) { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{33-33= -> <#Return Type#>}} } func voidFuncWithCondFlow() { if Bool.random() { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{28-28= -> <#Return Type#>}} } else { return 2 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{28-28= -> <#Return Type#>}} } } func voidFuncWithNestedVoidFunc() { func nestedVoidFunc() { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{24-24= -> <#Return Type#>}} } } func voidFuncWithEffects1() throws { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{35-35= -> <#Return Type#>}} } @available(SwiftStdlib 5.5, *) func voidFuncWithEffects2() async throws { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{41-41= -> <#Return Type#>}} } @available(SwiftStdlib 5.5, *) // expected-error@+1 {{'async' must precede 'throws'}} func voidFuncWithEffects3() throws async { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{41-41= -> <#Return Type#>}} } @available(SwiftStdlib 5.5, *) func voidFuncWithEffects4() async { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{34-34= -> <#Return Type#>}} } func voidFuncWithEffects5(_ closure: () throws -> Void) rethrows { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{65-65= -> <#Return Type#>}} } @available(SwiftStdlib 5.5, *) func voidGenericFuncWithEffects<T>(arg: T) async where T: CustomStringConvertible { return 1 // expected-error@-1 {{unexpected non-void return value in void function}} // expected-note@-2 {{did you mean to add a return type?}}{{49-49= -> <#Return Type#>}} } // Special cases: These should not offer a note + fix-it func voidFuncExplicitType() -> Void { return 1 // expected-error {{unexpected non-void return value in void function}} } class ClassWithDeinit { deinit { return 0 // expected-error {{unexpected non-void return value in void function}} } } class ClassWithVoidProp { var propertyWithVoidType: () { return 5 } // expected-error {{unexpected non-void return value in void function}} } class ClassWithPropContainingSetter { var propWithSetter: Int { get { return 0 } set { return 1 } // expected-error {{unexpected non-void return value in void function}} } } // https://github.com/apple/swift/issues/54389 struct Rect { let width: Int let height: Int } struct Frame { func rect(width: Int, height: Int) -> Rect { Rect(width: width, height: height) } let rect: Rect } func foo(frame: Frame) { frame.rect.width + 10.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}} } // Make sure we prefer the conformance failure. func f11(_ n: Int) {} func f11<T : P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{where 'T' = 'Int'}} f11(3, f4) // expected-error {{global function 'f11' requires that 'Int' conform to 'P2'}} let f12: (Int) -> Void = { _ in } func f12<T : P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{where 'T' = 'Int'}} f12(3, f4)// expected-error {{global function 'f12' requires that 'Int' conform to 'P2'}} /// https://github.com/apple/swift/issues/57615 /// Bad diagnostic for `var` + `func` overload with mismatched call // FIXME: Diagnostic still bad in local scope. func f_57615(x: Int, y: Int) {} var f_57615: Any = 0 f_57615(0, x: 0) // expected-error {{incorrect argument labels in call (have '_:x:', expected 'x:y:')}} // https://github.com/apple/swift/issues/54669 struct S1_54669<Value> {} struct S2_54669 {} protocol P_54669 {} func f_54669() -> S1_54669<[S2_54669]> {} func genericFunc<S2_54669: P_54669>(_ completion: @escaping (S1_54669<[S2_54669]>) -> Void) { let t = f_54669() completion(t) // expected-error {{cannot convert value of type 'diagnostics.S1_54669<[diagnostics.S2_54669]>' to expected argument type 'diagnostics.S1_54669<[S2_54669]>'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('diagnostics.S2_54669' and 'S2_54669') are expected to be equal}} } func assignGenericMismatch() { var a: [Int]? var b: [String] a = b // expected-error {{cannot assign value of type '[String]' to type '[Int]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} b = a // expected-error {{cannot assign value of type '[Int]' to type '[String]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}} // expected-error@-2 {{value of optional type '[Int]?' must be unwrapped to a value of type '[Int]'}} // expected-note@-3 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-4 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } // [Int] to [String]? argument to param conversion let value: [Int] = [] func gericArgToParamOptional(_ param: [String]?) {} gericArgToParamOptional(value) // expected-error {{convert value of type '[Int]' to expected argument type '[String]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}} // Inout Expr conversions func gericArgToParamInout1(_ x: inout [[Int]]) {} func gericArgToParamInout2(_ x: inout [[String]]) { gericArgToParamInout1(&x) // expected-error {{cannot convert value of type '[[String]]' to expected argument type '[[Int]]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} } func gericArgToParamInoutOptional(_ x: inout [[String]]?) { gericArgToParamInout1(&x) // expected-error {{cannot convert value of type '[[String]]?' to expected argument type '[[Int]]'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}} // expected-error@-2 {{value of optional type '[[String]]?' must be unwrapped to a value of type '[[String]]'}} // expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } func gericArgToParamInout(_ x: inout [[Int]]) { // expected-note {{change variable type to '[[String]]?' if it doesn't need to be declared as '[[Int]]'}} gericArgToParamInoutOptional(&x) // expected-error {{cannot convert value of type '[[Int]]' to expected argument type '[[String]]?'}} // expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}} // expected-error@-2 {{inout argument could be set to a value with a type other than '[[Int]]'; use a value declared as type '[[String]]?' instead}} } // https://github.com/apple/swift/issues/55169 do { struct S<E> {} // expected-note {{arguments to generic parameter 'E' ('Int' and 'Double') are expected to be equal}} func generic<T>(_ value: inout T, _ closure: (S<T>) -> Void) {} let arg: Int generic(&arg) { (g: S<Double>) -> Void in } // expected-error {{cannot convert value of type '(S<Double>) -> Void' to expected argument type '(S<Int>) -> Void'}} } // rdar://problem/62428353 - bad error message for passing `T` where `inout T` was expected func rdar62428353<T>(_ t: inout T) { let v = t // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} rdar62428353(v) // expected-error {{cannot pass immutable value as inout argument: 'v' is a 'let' constant}} } func rdar62989214() { struct Flag { var isTrue: Bool } @propertyWrapper @dynamicMemberLookup struct Wrapper<Value> { var wrappedValue: Value subscript<Subject>( dynamicMember keyPath: WritableKeyPath<Value, Subject> ) -> Wrapper<Subject> { get { fatalError() } } } func test(arr: Wrapper<[Flag]>, flag: Flag) { arr[flag].isTrue // expected-error {{cannot convert value of type 'Flag' to expected argument type 'Int'}} } } // https://github.com/apple/swift/issues/48258 do { func f1() -> String? {} f1!.count // expected-error {{function 'f1' was used as a property; add () to call it}} {{5-5=()}} func f2() -> Int? { 0 } let _: Int = f2! // expected-error {{function 'f2' was used as a property; add () to call it}} {{18-18=()}} } // rdar://74696023 - Fallback error when passing incorrect optional type to `==` operator func rdar74696023() { struct MyError { var code: Int = 0 } func test(error: MyError?, code: Int32) { guard error?.code == code else { fatalError() } // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } } extension Int { static var optionalIntMember: Int? { 0 } static var optionalThrowsMember: Int? { get throws { 0 } } } func testUnwrapFixIts(x: Int?) throws { let _ = x + 2 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{11-11=(}} {{12-12= ?? <#default value#>)}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{12-12=!}} let _ = (x ?? 0) + 2 let _ = 2 + x // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{15-15=(}} {{16-16= ?? <#default value#>)}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{16-16=!}} let _ = 2 + (x ?? 0) func foo(y: Int) {} foo(y: x) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{11-11= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{11-11=!}} foo(y: x ?? 0) let _ = x < 2 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{12-12= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{12-12=!}} let _ = x ?? 0 < 2 let _ = 2 < x // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{16-16= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{16-16=!}} let _ = 2 < x ?? 0 let _: Int = (.optionalIntMember) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{35-35= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{35-35=!}} let _: Int = (.optionalIntMember ?? 0) let _ = 1 + .optionalIntMember // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{15-15=(}} {{33-33= ?? <#default value#>)}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{33-33=!}} let _ = 1 + (.optionalIntMember ?? 0) let _ = try .optionalThrowsMember + 1 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{15-15=(}} {{36-36= ?? <#default value#>)}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{36-36=!}} let _ = try (.optionalThrowsMember ?? 0) + 1 let _ = .optionalIntMember?.bitWidth > 0 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{39-39= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{11-11=(}} {{39-39=)!}} let _ = (.optionalIntMember?.bitWidth)! > 0 let _ = .optionalIntMember?.bitWidth ?? 0 > 0 let _ = .random() ? .optionalIntMember : 0 // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{41-41= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{41-41=!}} let _ = .random() ? .optionalIntMember ?? 0 : 0 let _: Int = try try try .optionalThrowsMember // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{49-49= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{49-49=!}} let _: Int = try try try .optionalThrowsMember ?? 0 let _: Int = try! .optionalThrowsMember // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{42-42= ?? <#default value#>}} // expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{42-42=!}} let _: Int = try! .optionalThrowsMember ?? 0 } func rdar86611718(list: [Int]) { String(list.count()) // expected-error@-1 {{cannot call value of non-function type 'Int'}} }
apache-2.0
f2a1b142aae11e0fdb54d29a96862be9
46.171466
228
0.668581
3.648411
false
false
false
false
wang-chuanhui/CHSDK
Source/CHUI/ShapeMask.swift
1
2053
// // ShapeMask.swift // CHSDK // // Created by 王传辉 on 2017/8/4. // Copyright © 2017年 王传辉. All rights reserved. // import Foundation public protocol ShapeMask: class { func createShapeMaskMake() -> ShapeMaskMake } private var shapeMaskMakeKey = "shapeMaskMake" extension ShapeMask where Self: UIView { var shapeMaskMake: ShapeMaskMake { get { if let result = objc_getAssociatedObject(self, &shapeMaskMakeKey) as? ShapeMaskMake { return result } let result = createShapeMaskMake() objc_setAssociatedObject(self, &shapeMaskMakeKey, result, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return result } set { objc_setAssociatedObject(self, &shapeMaskMakeKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public func createShapeMaskMake() -> ShapeMaskMake { return ShapeMaskMake() } public func refreshShapeMask() { makeShapeMask { (shapeMaskMake) in } } public func makeShapeMask<T: ShapeMaskMake>(_ closure: ((T) -> ())) { if let shapeMaskMake = shapeMaskMake as? T { closure(shapeMaskMake) } shapeMask() } public func remakeShapeMask<T: ShapeMaskMake>(_ closure: ((T) -> ())) { removeShapeMask() shapeMaskMake = createShapeMaskMake() if let shapeMaskMake = shapeMaskMake as? T { closure(shapeMaskMake) } shapeMask() } func shapeMask() { shapeMaskMake.view = self shapeMaskMake.makeShapeLayer() layer.mask = shapeMaskMake.mask if shapeMaskMake.addSublayer { layer.addSublayer(shapeMaskMake.sublayer) }else { shapeMaskMake.sublayer.removeFromSuperlayer() } } public func removeShapeMask() { layer.mask = nil shapeMaskMake.sublayer.removeFromSuperlayer() } }
mit
ece01c8a9cdebe115fe45585c720a40f
25.128205
129
0.606477
4.364026
false
false
false
false
modocache/swift
test/ClangModules/objc_id_as_any.swift
4
751
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify %s // REQUIRES: objc_interop import Foundation func assertTypeIsAny(_: Any.Protocol) {} func staticType<T>(_: T) -> T.Type { return T.self } let idLover = NSIdLover() let t1 = staticType(idLover.makesId()) assertTypeIsAny(t1) struct ArbitraryThing {} idLover.takesId(ArbitraryThing()) var x: AnyObject = NSObject() idLover.takesArray(ofId: &x) var xAsAny = x as Any idLover.takesArray(ofId: &xAsAny) // expected-error{{argument type 'Any' does not conform to expected type 'AnyObject'}} var y: Any = NSObject() idLover.takesArray(ofId: &y) // expected-error{{argument type 'Any' does not conform to expected type 'AnyObject'}} idLover.takesId(x) idLover.takesId(y)
apache-2.0
5ad3c2b608236775da69faff4e57aafc
27.884615
121
0.731025
2.933594
false
false
false
false
XDislikeCode/Yepic
Yepic/Application/Support/TextFieldEffects/MadokaTextField.swift
4
6424
// // MadokaTextField.swift // TextFieldEffects // // Created by Raúl Riera on 05/02/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit /** A MadokaTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable visual effect around the edges of the control. */ @IBDesignable open class MadokaTextField: TextFieldEffects { /** The color of the placeholder text. This property applies a color to the complete placeholder string. The default value for this property is a black color. */ @IBInspectable dynamic open var placeholderColor: UIColor = .black { didSet { updatePlaceholder() } } /** The color of the border. This property applies a color to the lower edge of the control. The default value for this property is a clear color. */ @IBInspectable dynamic open var borderColor: UIColor? { didSet { updateBorder() } } /** The scale of the placeholder font. This property determines the size of the placeholder label relative to the font size of the text field. */ @IBInspectable dynamic open var placeholderFontScale: CGFloat = 0.65 { didSet { updatePlaceholder() } } override open var placeholder: String? { didSet { updatePlaceholder() } } override open var bounds: CGRect { didSet { updateBorder() updatePlaceholder() } } private let borderThickness: CGFloat = 1 private let placeholderInsets = CGPoint(x: 6, y: 6) private let textFieldInsets = CGPoint(x: 6, y: 6) private let borderLayer = CAShapeLayer() private var backgroundLayerColor: UIColor? // MARK: - TextFieldEffects override open func drawViewsForRect(_ rect: CGRect) { let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: rect.size.width, height: rect.size.height)) placeholderLabel.frame = frame.insetBy(dx: placeholderInsets.x, dy: placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(font!) updateBorder() updatePlaceholder() layer.addSublayer(borderLayer) addSubview(placeholderLabel) } override open func animateViewsForTextEntry() { borderLayer.strokeEnd = 1 UIView.animate(withDuration: 0.3, animations: { let translate = CGAffineTransform(translationX: -self.placeholderInsets.x, y: self.placeholderLabel.bounds.height + (self.placeholderInsets.y * 2)) let scale = CGAffineTransform(scaleX: 0.9, y: 0.9) self.placeholderLabel.transform = translate.concatenating(scale) }) { _ in self.animationCompletionHandler?(.textEntry) } } override open func animateViewsForTextDisplay() { if text!.isEmpty { borderLayer.strokeEnd = percentageForBottomBorder() UIView.animate(withDuration: 0.3, animations: { self.placeholderLabel.transform = CGAffineTransform.identity }) { _ in self.animationCompletionHandler?(.textDisplay) } } } // MARK: - Private private func updateBorder() { let rect = rectForBorder(bounds) let path = UIBezierPath() path.move(to: CGPoint(x: rect.origin.x + borderThickness, y: rect.height - borderThickness)) path.addLine(to: CGPoint(x: rect.width - borderThickness, y: rect.height - borderThickness)) path.addLine(to: CGPoint(x: rect.width - borderThickness, y: rect.origin.y + borderThickness)) path.addLine(to: CGPoint(x: rect.origin.x + borderThickness, y: rect.origin.y + borderThickness)) path.close() borderLayer.path = path.cgPath borderLayer.lineCap = kCALineCapSquare borderLayer.lineWidth = borderThickness borderLayer.fillColor = nil borderLayer.strokeColor = borderColor?.cgColor borderLayer.strokeEnd = percentageForBottomBorder() } private func percentageForBottomBorder() -> CGFloat { let borderRect = rectForBorder(bounds) let sumOfSides = (borderRect.width * 2) + (borderRect.height * 2) return (borderRect.width * 100 / sumOfSides) / 100 } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder || text!.isNotEmpty { animateViewsForTextEntry() } } private func placeholderFontFromFont(_ font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * placeholderFontScale) return smallerFont } private func rectForBorder(_ bounds: CGRect) -> CGRect { let newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y) return newRect } private func layoutPlaceholderInTextRect() { placeholderLabel.transform = CGAffineTransform.identity let textRect = self.textRect(forBounds: bounds) var originX = textRect.origin.x switch textAlignment { case .center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: textRect.height - placeholderLabel.bounds.height - placeholderInsets.y, width: placeholderLabel.bounds.width, height: placeholderLabel.bounds.height) } // MARK: - Overrides override open func editingRect(forBounds bounds: CGRect) -> CGRect { let newBounds = rectForBorder(bounds) return newBounds.insetBy(dx: textFieldInsets.x, dy: 0) } override open func textRect(forBounds bounds: CGRect) -> CGRect { let newBounds = rectForBorder(bounds) return newBounds.insetBy(dx: textFieldInsets.x, dy: 0) } }
mit
a27bf31a32009a3f7753a81398f369d0
33.718919
173
0.633349
5.184019
false
false
false
false
natecook1000/swift
test/Profiler/pgo_checked_cast.swift
1
3399
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_checked_cast -o %t/main // This unusual use of 'sh' allows the path of the profraw file to be // substituted by %target-run. // RUN: %target-run sh -c 'env LLVM_PROFILE_FILE=$1 $2' -- %t/default.profraw %t/main // RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata // RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-sorted-sil -emit-sil -module-name pgo_checked_cast -o - | %FileCheck %s --check-prefix=SIL // need to lower checked_cast_addr_br(addr) into IR for this // %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-ir -module-name pgo_checked_cast -o - | %FileCheck %s --check-prefix=IR // RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-sorted-sil -emit-sil -module-name pgo_checked_cast -o - | %FileCheck %s --check-prefix=SIL-OPT // need to lower checked_cast_addr_br(addr) into IR for this // %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-ir -module-name pgo_checked_cast -o - | %FileCheck %s --check-prefix=IR-OPT // REQUIRES: profile_runtime // REQUIRES: executable_test // REQUIRES: OS=macosx // SIL-LABEL: // pgo_checked_cast.check1<A>(Any, A) -> A // SIL-LABEL: sil @$S16pgo_checked_cast6check1yxyp_xtlF : $@convention(thin) <T> (@in_guaranteed Any, @in_guaranteed T) -> @out T !function_entry_count(5001) { // IR-LABEL: define swiftcc i32 @$S6pgo_checked_cast6guess1s5Int32VAD1x_tF // IR-OPT-LABEL: define swiftcc i32 @$S6pgo_checked_cast6guess1s5Int32VAD1x_tF public func check1<T>(_ a : Any, _ t : T) -> T { // SIL: checked_cast_addr_br take_always Any in {{.*}} : $*Any to T in {{.*}} : $*T, {{.*}}, {{.*}} !true_count(5000) !false_count(1) // SIL-OPT: checked_cast_addr_br take_always Any in {{.*}} : $*Any to T in {{.*}} : $*T, {{.*}}, {{.*}} !true_count(5000) !false_count(1) if let x = a as? T { return x } else { return t } } public class B {} public class C : B {} public class D : C {} // SIL-LABEL: // pgo_checked_cast.check2(pgo_checked_cast.B) -> Swift.Int32 // SIL-LABEL: sil @$S16pgo_checked_cast6check2ys5Int32VAA1BCF : $@convention(thin) (@guaranteed B) -> Int32 !function_entry_count(5003) { // IR-LABEL: define swiftcc i32 @$S6pgo_checked_cast6guess1s5Int32VAD1x_tF // IR-OPT-LABEL: define swiftcc i32 @$S6pgo_checked_cast6guess1s5Int32VAD1x_tF public func check2(_ a : B) -> Int32 { // SIL: checked_cast_br %0 : $B to $D, {{.*}}, {{.*}} !true_count(5000) // SIL: checked_cast_br %0 : $B to $C, {{.*}}, {{.*}} !true_count(2) // SIL-OPT: checked_cast_br %0 : $B to $D, {{.*}}, {{.*}} !true_count(5000) // SIL-OPT: checked_cast_br %0 : $B to $C, {{.*}}, {{.*}} !true_count(2) switch a { case is D: return 42 case is C: return 23 default: return 13 } } func main() { let answer : Int32 = 42 var sum : Int32 = 0 sum += check1("The answer to the life, the universe, and everything", answer) sum += check2(B()) sum += check2(C()) sum += check2(C()) for i : Int32 in 1...5000 { sum += check1(i, answer) sum += check2(D()) } } main() // IR: !{!"branch_weights", i32 5001, i32 2} // IR-OPT: !{!"branch_weights", i32 5001, i32 2}
apache-2.0
9476d2b02400515bfdc3657f05542208
43.142857
196
0.64313
2.825436
false
false
false
false
cuappdev/tcat-ios
TCAT/Cells/ServiceAlertTableViewCell.swift
1
9186
// // ServiceAlertTableViewCell.swift // TCAT // // Created by Omar Rasheed on 12/7/18. // Copyright © 2018 cuappdev. All rights reserved. // import SnapKit import UIKit class ServiceAlertTableViewCell: UITableViewCell { static let identifier: String = "serviceAlertCell" private var affectedRoutesLabel: UILabel? private var affectedRoutesStackView: UIStackView? private var descriptionLabel = UILabel() private var timeSpanLabel = UILabel() private var topSeparator: UIView? private let busIconHorizontalSpacing: CGFloat = 10 private let borderInset: CGFloat = 16 private var maxIconsPerRow: Int { let iconWidth = BusIconType.directionSmall.width let screenWidth = UIScreen.main.bounds.width let totalConstraintInset = borderInset * 2 return Int((screenWidth - totalConstraintInset + busIconHorizontalSpacing) / (iconWidth + busIconHorizontalSpacing)) } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupTimeSpanLabel() setupDescriptionLabel() } func configure(for alert: ServiceAlert, isNotFirstRow: Bool) { timeSpanLabel.text = formatTimeString(alert.fromDate, toDate: alert.toDate) descriptionLabel.text = alert.message if !alert.routes.isEmpty { setupAffectedRoutesStackView(alert: alert) setupaffectedRoutesLabel() } if isNotFirstRow { setupTopSeparator() } } private func setupTimeSpanLabel() { timeSpanLabel.numberOfLines = 0 timeSpanLabel.font = .getFont(.semibold, size: 18) timeSpanLabel.textColor = Colors.primaryText contentView.addSubview(timeSpanLabel) } private func setupDescriptionLabel() { descriptionLabel = UILabel() descriptionLabel.numberOfLines = 0 descriptionLabel.font = .getFont(.regular, size: 14) descriptionLabel.textColor = Colors.primaryText contentView.addSubview(descriptionLabel) } private func setupaffectedRoutesLabel() { let affectedRoutesLabel = UILabel() affectedRoutesLabel.font = .getFont(.semibold, size: 18) affectedRoutesLabel.textColor = Colors.primaryText affectedRoutesLabel.text = Constants.General.affectedRoutes self.affectedRoutesLabel = affectedRoutesLabel contentView.addSubview(affectedRoutesLabel) } private func setupAffectedRoutesStackView(alert: ServiceAlert) { let busIconVerticalSpacing: CGFloat = 10 affectedRoutesStackView = UIStackView() var routesCopy = alert.routes for _ in 0..<rowCount(alert: alert) { var subviews = [BusIcon]() for _ in 0..<maxIconsPerRow where !routesCopy.isEmpty { let route = routesCopy.removeFirst() subviews.append(BusIcon(type: .directionSmall, number: route)) } let rowStackView = UIStackView(arrangedSubviews: subviews) rowStackView.axis = .horizontal rowStackView.spacing = busIconHorizontalSpacing rowStackView.alignment = .top affectedRoutesStackView?.addArrangedSubview(rowStackView) } guard let stackView = affectedRoutesStackView else { return } stackView.axis = .vertical stackView.alignment = .leading stackView.spacing = busIconVerticalSpacing contentView.addSubview(stackView) } private func setupTopSeparator() { topSeparator = UIView() topSeparator?.backgroundColor = Colors.backgroundWash contentView.addSubview(topSeparator!) } private func descriptionLabelConstraints(topConstraint: UIView) { descriptionLabel.snp.remakeConstraints { (make) in if topConstraint == contentView { make.top.equalToSuperview().inset(borderInset) } else { make.top.equalTo(topConstraint.snp.bottom).offset(12) } make.leading.trailing.equalToSuperview().inset(borderInset) if let text = descriptionLabel.text { let width = contentView.frame.width - (CGFloat)(2 * borderInset) let heightValue = ceil(text.heightWithConstrainedWidth(width: width, font: descriptionLabel.font)) make.height.equalTo(ceil(heightValue)) } else { make.height.equalTo(descriptionLabel.intrinsicContentSize.height) } } } private func timeSpanLabelConstraints(topConstraint: UIView) { timeSpanLabel.snp.remakeConstraints { (make) in if topConstraint == contentView { make.top.equalToSuperview().inset(borderInset) } else { make.top.equalTo(topConstraint.snp.bottom).offset(12) } make.leading.trailing.equalToSuperview().inset(borderInset) make.height.equalTo(timeSpanLabel.intrinsicContentSize.height) } } private func topSeparatorConstraints() { let topSeparatorHeight = 8 if let topSeparator = topSeparator { topSeparator.snp.remakeConstraints { (make) in make.top.leading.trailing.equalToSuperview() make.height.equalTo(topSeparatorHeight) } } } override func updateConstraints() { let stackViewTopOffset = 24 if let topSeparator = topSeparator, timeSpanLabel.isDescendant(of: contentView) { // Both topSeparator and timeSpanLabel exist topSeparatorConstraints() timeSpanLabelConstraints(topConstraint: topSeparator) descriptionLabelConstraints(topConstraint: timeSpanLabel) } else if timeSpanLabel.isDescendant(of: contentView) { // Only timeSpanLabel, no topSeparator timeSpanLabelConstraints(topConstraint: contentView) descriptionLabelConstraints(topConstraint: timeSpanLabel) } else if let topSeparator = topSeparator { // Only topSeparator, no timeSpanLabel topSeparatorConstraints() descriptionLabelConstraints(topConstraint: topSeparator) } else { // Neither descriptionLabelConstraints(topConstraint: contentView) } if let stackView = affectedRoutesStackView, let affectedRoutesLabel = affectedRoutesLabel { // When both a separator view and stackView are required affectedRoutesLabel.snp.remakeConstraints { (make) in make.leading.equalTo(descriptionLabel) make.top.equalTo(descriptionLabel.snp.bottom).offset(stackViewTopOffset) make.size.equalTo(affectedRoutesLabel.intrinsicContentSize) } stackView.snp.remakeConstraints { (make) in make.top.equalTo(affectedRoutesLabel.snp.bottom).offset(8) make.leading.equalTo(descriptionLabel) make.bottom.equalToSuperview().inset(borderInset) } } else { descriptionLabel.snp.makeConstraints { (make) in make.bottom.equalToSuperview().inset(borderInset) } } super.updateConstraints() } private func formatTimeString(_ fromDate: String, toDate: String) -> String { let newformatter = DateFormatter() newformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.sZZZZ" newformatter.locale = Locale(identifier: "en_US_POSIX") let fromDate = newformatter.date(from: fromDate) let toDate = newformatter.date(from: toDate) let formatter = DateFormatter() formatter.dateFormat = "EEEE M/d" if let unWrappedFromDate = fromDate, let unWrappedToDate = toDate { let formattedFromDate = formatter.string(from: unWrappedFromDate) let formattedToDate = formatter.string(from: unWrappedToDate) return "\(formattedFromDate) - \(formattedToDate)" } timeSpanLabel.removeFromSuperview() return "Time: Unknown" } private func rowCount(alert: ServiceAlert) -> Int { if alert.routes.count > maxIconsPerRow { let addExtra = alert.routes.count % maxIconsPerRow > 0 ? 1 : 0 let rowCount = alert.routes.count / maxIconsPerRow return rowCount + addExtra } else { return 1 } } private func getDayOfWeek(_ today: Date) -> Int? { let myCalendar = Calendar(identifier: .gregorian) let weekDay = myCalendar.component(.weekday, from: today) return weekDay } override func prepareForReuse() { if let stackView = affectedRoutesStackView { stackView.removeFromSuperview() affectedRoutesStackView = nil } if let routesLabel = affectedRoutesLabel { routesLabel.removeFromSuperview() affectedRoutesLabel = nil } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
26ee2d64445a6e1f81443a9be9218ed8
35.448413
124
0.650082
5.300058
false
false
false
false
tjw/swift
test/decl/init/constructor-kind.swift
5
2922
// RUN: %target-typecheck-verify-swift // Test various orderings of constructor calls and assignments to make // sure we figure out the constructor kind in various situations. struct Measurement { let val: Int } class Superclass { init() {} init(name: String) {} } class SomeClass : Superclass { let width: Measurement // expected-note * {{declared here}} let height: Measurement // expected-note * {{declared here}} // super.init() call gives us a chaining initializer, where we can // assign let properties override init() { self.width = Measurement.self.init(val: 10) self.height = Measurement.self.init(val: 20) super.init(name: "shape") } // Another case init(width: Int, height: Int) { super.init(name: "shape") self.width = Measurement.self.init(val: width) self.height = Measurement.self.init(val: height) } // Delegating initializer -- let properties are immutable convenience init(width: Int) { self.init(width: width, height: 20) self.height = Measurement(val: 20) // expected-error {{'let' property 'height' may not be initialized directly; use "self.init(...)" or "self = ..." instead}} } // Another case convenience init(height: Int) { self.width = Measurement(val: 20) // expected-error {{'let' property 'width' may not be initialized directly; use "self.init(...)" or "self = ..." instead}} self.init(width: 10, height: height) } } struct SomeStruct { let width: Measurement // expected-note * {{declared here}} let height: Measurement // expected-note * {{declared here}} // Delegating initializer init() { self.init() self.width = Measurement.self.init(val: width) // expected-error {{'let' property 'width' may not be initialized directly; use "self.init(...)" or "self = ..." instead}} self.height = Measurement.self.init(val: height) // expected-error {{'let' property 'height' may not be initialized directly; use "self.init(...)" or "self = ..." instead}} } // Designated initializer init(width: Int, height: Int, meta: Measurement.Type) { self.width = meta.init(val: width) self.height = meta.init(val: height) } // Delegating initializer init(width: Int) { self.init() self.width = width // expected-error {{'let' property 'width' may not be initialized directly; use "self.init(...)" or "self = ..." instead}} self.height = Measurement(val: 20) // expected-error {{'let' property 'height' may not be initialized directly; use "self.init(...)" or "self = ..." instead}} } // Designated initializer init(height: Int) { self.width = Measurement(val: 10) // expected-error {{'let' property 'width' may not be initialized directly; use "self.init(...)" or "self = ..." instead}} self.height = height // expected-error {{'let' property 'height' may not be initialized directly; use "self.init(...)" or "self = ..." instead}} self.init() } }
apache-2.0
57c15a54438551381fd4656063229f25
36.948052
176
0.663244
3.854881
false
false
false
false
hamilyjing/JJSwiftStudy
Playground/Overloading.playground/section-1.swift
1
3406
import UIKit // +是已经存在操作符,不需要声明 func +(left: [Int], right: [Int]) -> [Int] { var sum = [Int]() assert(left.count == right.count, "Array of same length only") for (key, _) in left.enumerated() { sum.append(left[key] + right[key]) } return sum; } var sumArray = [1, 2] + [1, 2] // [2,4] // 这里有三个步骤去定义一个自定义操作符: /* 1.命名你的运算符 [现在你必须选择一个字符作为你的运算符。自定义运算符可以以/、=、-、+、!、*、%、<、>、&、|、^、~或者Unicode字符开始。这个给了你一个很大的范围去选择你的运算符。但是别太高兴,选择的时候你还必须考虑重复输入的时候更少的键盘键入次数。] 2.选择一种类型 [在Swift中你能定义一元、二元和三元的操作符。他们表明了运算符操作的数字的数目。 一元操作符与一个操作数相关,比如后置++(i++)或者前置++(++i),他们依赖于运算符与操作数出现的位置。 二元操作符是插入的,因为它出现在两个操作符中间,比如1 + 1。 三元操作符有三个操作数。在Swift中,?:条件操作符是唯一一个三目运算符,比如a?b:c。 你应该基于你的运算符的操作数的个数选择合适得类型。你想要实现两个数组相加,那就定义二元运算符。] 3.设置它的优先级和结合性 [结合性(associativity)的值可取的值有left,right和none。左结合运算符跟其他优先级相同的左结合运算符写在一起时,会跟左边的操作数结合。同理,右结合运算符会跟右边的操作数结合。而非结合运算符不能跟其他相同优先级的运算符写在一起。 结合性(associativity)的值默认为none,优先级(precedence)默认为100。 加法结合性和优先级(left和140) 这个是十分棘手的,所以有一个比较好的方法,在Swift language reference中找到一个类似的标准的运算符,然后使用相同的语义。例如,在定义向量加的时候,可以使用与+运算符相同的优先级和结合性。] */ // 定义新操作符 /* 新运算符可以声明为前置prefix,中置infix或后置postfix */ // 一元前置操作符 prefix operator +++ // 声明新操作符 prefix func +++( value: inout Int) -> Int { value += 2; return value; } var value: Int = 1 +++value // 二元中置操作符 infix operator ⊕ { associativity left precedence 140 } func ⊕(left: [Int], right: [Int]) -> [Int] //只有中置操作符不用在func前加infix关键字 { assert(left.count == right.count, "should same count") var sum = [Int](repeating: 0, count: left.count); for (key, _) in left.enumerated() { sum[key] = left[key] + right[key]; } return sum; } var sumArray1 = [1, 2] ⊕ [1, 2] // [2, 4] // 一元后置操作符 postfix operator --- postfix func ---( value: inout Int) -> Int { value -= 2; return value; } var value2 = 3 value2--- // 使用泛型定义新操作符 protocol Number { // 1 static func +(l: Self, r: Self) -> Self // 2 } extension Double : Number {} // 3 extension Float : Number {} extension Int : Number {} infix operator ⊕⊕ { associativity left precedence 140 } func ⊕⊕<T: Number>(left: T, right: T) -> T { return left + right; } var value5 = 1 ⊕⊕ 2
mit
22ec57360f3a317e92415e2c212a5469
20.816327
126
0.663237
2.365044
false
false
false
false
bvic23/VinceRP
VinceRP/Common/Timer.swift
1
773
// // Created by Viktor Belenyesi on 10/18/15. // Copyright (c) 2015 Viktor Belenyesi. All rights reserved. // public class Timer { private var timer: NSTimer? private var tick: (() -> ())? @objc private func timerHandler() { self.tick!() } public func cancel() { guard let t = self.timer else { return } t.invalidate() self.timer = nil } class func timer(interval: NSTimeInterval, tick: () ->()) -> Timer { let result = Timer() let t = NSTimer.scheduledTimerWithTimeInterval(interval, target: result, selector: #selector(Timer.timerHandler), userInfo: nil, repeats: true) result.tick = tick result.timer = t return result } }
mit
b8fb83318d8b3b741fad9b447ccaa083
23.935484
151
0.575679
4.417143
false
false
false
false
iOSWizards/AwesomeData
AwesomeData/Classes/Fetcher/AwesomeRequester.swift
1
8017
// // AwesomeFetcher.swift // AwesomeData // // Created by Evandro Harrison Hoffmann on 6/2/16. // Copyright © 2016 It's Day Off. All rights reserved. // import UIKit public enum URLMethod: String { case GET = "GET" case POST = "POST" case DELETE = "DELETE" case PUT = "PUT" } open class AwesomeRequester: NSObject { // MARK:- Where the magic happens /* * Fetch data from URL with NSUrlSession * @param urlString: Url to fetch data form * @param method: URL method to fetch data using URLMethod enum * @param headerValues: Any header values to complete the request * @param shouldCache: Cache fetched data, if on, it will check first for data in cache, then fetch if not found * @param completion: Returns fetched NSData in a block */ open static func performRequest(_ urlString: String?, method: URLMethod? = .GET, bodyData: Data? = nil, headerValues: [[String]]? = nil, shouldCache: Bool = false, completion:@escaping (_ data: Data?) -> Void, timeoutAfter timeout: TimeInterval = 0, onTimeout: (()->Void)? = nil) -> URLSessionDataTask?{ guard let urlString = urlString else { completion(nil) return nil } if urlString == "Optional(<null>)" { completion(nil) return nil } guard let url = URL(string: urlString) else{ completion(nil) return nil } let urlRequest = NSMutableURLRequest(url: url) //urlRequest.cachePolicy = .ReturnCacheDataElseLoad // check if file been cached already if shouldCache { if let data = AwesomeCacheManager.getCachedObject(urlRequest as URLRequest) { completion(data) return nil } } // Continue to URL request if let method = method { urlRequest.httpMethod = method.rawValue } if let bodyData = bodyData { urlRequest.httpBody = bodyData } if let headerValues = headerValues { for headerValue in headerValues { urlRequest.addValue(headerValue[0], forHTTPHeaderField: headerValue[1]) } } if timeout > 0 { urlRequest.timeoutInterval = timeout } let task = URLSession.shared.dataTask(with: urlRequest as URLRequest) { (data, response, error) in DispatchQueue.main.async(execute: { if let error = error{ print("There was an error \(error)") let urlError = error as NSError if urlError.code == NSURLErrorTimedOut { onTimeout?() }else{ completion(nil) } }else{ if shouldCache { AwesomeCacheManager.cacheObject(urlRequest as URLRequest, response: response, data: data) } completion(data) } }) } task.resume() return task } } // MARK: - Custom Calls extension AwesomeRequester { /* * Fetch data from URL with NSUrlSession * @param urlString: Url to fetch data form * @param body: adds body to request, can be of any kind * @param completion: Returns fetched NSData in a block */ public static func performRequest(_ urlString: String?, body: String?, completion:@escaping (_ data: Data?) -> Void, timeoutAfter timeout: TimeInterval = 0, onTimeout: (()->Void)? = nil) -> URLSessionDataTask?{ if let body = body { return performRequest(urlString, method: nil, bodyData: body.data(using: String.Encoding.utf8), headerValues: nil, shouldCache: false, completion: completion, timeoutAfter: timeout, onTimeout: onTimeout) } return performRequest(urlString, method: nil, bodyData: nil, headerValues: nil, shouldCache: false, completion: completion, timeoutAfter: timeout, onTimeout: onTimeout) } /* * Fetch data from URL with NSUrlSession * @param urlString: Url to fetch data form * @param method: URL method to fetch data using URLMethod enum * @param jsonBody: adds json (Dictionary) body to request * @param completion: Returns fetched NSData in a block */ public static func performRequest(_ urlString: String?, method: URLMethod?, jsonBody: [String: AnyObject]?, completion:@escaping (_ data: Data?) -> Void, timeoutAfter timeout: TimeInterval = 0, onTimeout: (()->Void)? = nil) -> URLSessionDataTask? { var data: Data? var headerValues = [[String]]() if let jsonBody = jsonBody { do { try data = JSONSerialization.data(withJSONObject: jsonBody, options: .prettyPrinted) headerValues.append(["application/json", "Content-Type"]) headerValues.append(["application/json", "Accept"]) } catch{ NSLog("Error unwraping json object") } } return performRequest(urlString, method: method, bodyData: data, headerValues: headerValues, shouldCache: false, completion: completion, timeoutAfter: timeout, onTimeout: onTimeout) } /* * Fetch data from URL with NSUrlSession * @param urlString: Url to fetch data form * @param method: URL method to fetch data using URLMethod enum * @param jsonBody: adds json (Dictionary) body to request * @param authorization: adds request Authorization token to header * @param completion: Returns fetched NSData in a block */ public static func performRequest(_ urlString: String?, method: URLMethod? = .GET, jsonBody: [String: AnyObject]? = nil, authorization: String, completion:@escaping (_ data: Data?) -> Void, timeoutAfter timeout: TimeInterval = 0, onTimeout: (()->Void)? = nil) -> URLSessionDataTask? { return performRequest( urlString, method: method, jsonBody: jsonBody, headers: ["Authorization": authorization], completion: completion, timeoutAfter: timeout, onTimeout: onTimeout ) } /* * Fetch data from URL with NSUrlSession * @param urlString: Url to fetch data form * @param method: URL method to fetch data using URLMethod enum * @param jsonBody: adds json (Dictionary) body to request * @param headers: adds headers to the request * @param timeout: adds the request timeout * @param completion: Returns fetched NSData in a block */ public static func performRequest(_ urlString: String?, method: URLMethod? = .GET, jsonBody: [String: AnyObject]? = nil, headers: [String: String], completion:@escaping (_ data: Data?) -> Void, timeoutAfter timeout: TimeInterval = 0, onTimeout: (()->Void)? = nil) -> URLSessionDataTask? { var data: Data? var headerValues = [[String]]() if let jsonBody = jsonBody { do { try data = JSONSerialization.data(withJSONObject: jsonBody, options: .prettyPrinted) headerValues.append(["application/json", "Content-Type"]) headerValues.append(["application/json", "Accept"]) } catch{ NSLog("Error unwraping json object") } } for (key, value) in headers { headerValues.append([value, key]) } return performRequest( urlString, method: method, bodyData: data, headerValues: headerValues, shouldCache: false, completion: completion, timeoutAfter: timeout, onTimeout: onTimeout ) } }
mit
092842774277164ab304043aba41ca2a
38.487685
307
0.584955
5.070209
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/CodeBuild/CodeBuild_Error.swift
1
2720
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for CodeBuild public struct CodeBuildErrorType: AWSErrorType { enum Code: String { case accountLimitExceededException = "AccountLimitExceededException" case invalidInputException = "InvalidInputException" case oAuthProviderException = "OAuthProviderException" case resourceAlreadyExistsException = "ResourceAlreadyExistsException" case resourceNotFoundException = "ResourceNotFoundException" } private let error: Code public let context: AWSErrorContext? /// initialize CodeBuild public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// An AWS service limit was exceeded for the calling AWS account. public static var accountLimitExceededException: Self { .init(.accountLimitExceededException) } /// The input value that was provided is not valid. public static var invalidInputException: Self { .init(.invalidInputException) } /// There was a problem with the underlying OAuth provider. public static var oAuthProviderException: Self { .init(.oAuthProviderException) } /// The specified AWS resource cannot be created, because an AWS resource with the same settings already exists. public static var resourceAlreadyExistsException: Self { .init(.resourceAlreadyExistsException) } /// The specified AWS resource cannot be found. public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } } extension CodeBuildErrorType: Equatable { public static func == (lhs: CodeBuildErrorType, rhs: CodeBuildErrorType) -> Bool { lhs.error == rhs.error } } extension CodeBuildErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
92a9fb8d2498fa32bfc1c91e8721f09f
38.42029
117
0.679779
5.200765
false
false
false
false
ryanspillsbury90/HaleMeditates
ios/Hale Meditates/UIUtil.swift
1
2839
// // UIUtil.swift // Hale Meditates // // Created by Ryan Pillsbury on 6/18/15. // Copyright (c) 2015 koait. All rights reserved. // import Foundation import UIKit class UIUtil { static let storyboard = UIStoryboard(name: "Main", bundle: nil) static func getViewControllerFromStoryboard(name: String) -> AnyObject! { return storyboard.instantiateViewControllerWithIdentifier(name) } static let primaryColor = UIColor(red: 80 / 256, green: 210 / 256, blue: 194 / 256, alpha: 1) static let secondaryColor = UIColor(red: 132 / 256, green: 128 / 256, blue: 240 / 256, alpha: 1) static let tertiaryColor = UIColor(red: 252 / 256, green: 171 / 256, blue: 83 / 256, alpha: 1) static func formatTimeString(value: Int, longDate: Bool = false) -> String { if (longDate) { return formatTimeStringLong(value); } // long date not supported at the moment var minutes: Int = value / 60 let seconds: Int = value - (minutes * 60); if ((minutes > 0 && seconds > 0) || minutes >= 60) { if (minutes < 10) { return NSString(format: "%dm%02ds", minutes, seconds) as String } else if (minutes < 60) { return "\(minutes)m"; } else { let hours: Int = minutes / 60 minutes = minutes - (hours * 60); if (minutes > 0) { return NSString(format: "%dh%02dm", hours, minutes) as String } else { return "\(hours)h"; } } } else if (minutes > 0 ){ return "\(minutes)m"; } else { return "\(seconds)s"; } } static func formatTimeStringLong(value: Int) -> String { var minutes: Int = value / 60 let m = ((minutes % 60) == 1) ? "minute" : "minutes"; let seconds: Int = value - (minutes * 60); let s = ((seconds % 60) == 1) ? "second" : "seconds"; if ((minutes > 0 && seconds > 0) || minutes >= 60) { if (minutes < 10) { return NSString(format: "%d \(m)%02d \(s)", minutes, seconds) as String } else if (minutes < 60) { return "\(minutes) \(m)"; } else { let hours: Int = minutes / 60 let h = ((hours % 24) == 1) ? "hour" : "hours"; minutes = minutes - (hours * 60); if (minutes > 0) { return NSString(format: "%d \(h)%02d \(m)", hours, minutes) as String } else { return "\(hours) \(h)"; } } } else if (minutes > 0 ){ return "\(minutes) \(m)"; } else { return "\(seconds) \(s)"; } } }
mit
8258d4792a40a117417ba42ee5535ef9
34.936709
100
0.487848
4.156662
false
false
false
false
wosheesh/uchatclient
uchat/Model/Udacity/UConstants.swift
1
2053
// // UConstants.swift // On the Map // // Created by Wojtek Materka on 20/01/2016. // Copyright © 2016 Wojtek Materka. All rights reserved. // extension UClient { // MARK: - Constants struct Constants { // MARK: URLs static let BaseURL: String = "https://www.udacity.com/" // MARK: Timouts static let RequestTimeout : Double = 15 static let ResourceTimeout : Double = 15 } // MARK: - Methods struct Methods { // MARK: Authentication static let UdacitySession = "api/session" // MARK: User Data static let UdacityUserData = "api/users/{user_id}" // MARK: Course Catalogue static let CourseCatalogue = "public-api/v0/courses" } // MARK: - URL Keys struct URLKeys { static let UserId = "user_id" } // MARK: - Parameter Keys struct JSONBodyKeys { static let Username = "username" static let Password = "password" } // MARK: - JSON Response Keys struct JSONResponseKeys { // MARK: General static let Status = "status" static let ErrorMessage = "error" // MARK: Authorization static let UserID = "account.key" static let SessionID = "session.id" // MARK: Public User Data static let UserResults = "user" static let FirstName = "first_name" static let LastName = "last_name" static let UserKey = "key" // MARK: Enrolled courses static let Enrollments = "_enrollments" static let CourseKey = "node_key" // MARK: Course Catalogue static let Courses = "courses" static let CourseKeyCatalogue = "key" static let CourseTitle = "title" static let CourseSubtitle = "subtitle" static let CourseImage = "image" static let CourseBannerImage = "banner_image" } }
mit
2199ed855213c3ccdc57a6c2ff78497d
24.333333
63
0.54922
4.67426
false
false
false
false
vector-im/vector-ios
Riot/Modules/Room/VoiceMessages/VoiceMessageController.swift
1
18087
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import AVFoundation import DSWaveformImage @objc public protocol VoiceMessageControllerDelegate: AnyObject { func voiceMessageControllerDidRequestMicrophonePermission(_ voiceMessageController: VoiceMessageController) func voiceMessageController(_ voiceMessageController: VoiceMessageController, didRequestSendForFileAtURL url: URL, duration: UInt, samples: [Float]?, completion: @escaping (Bool) -> Void) } public class VoiceMessageController: NSObject, VoiceMessageToolbarViewDelegate, VoiceMessageAudioRecorderDelegate, VoiceMessageAudioPlayerDelegate { private enum Constants { static let maximumAudioRecordingDuration: TimeInterval = 120.0 static let maximumAudioRecordingLengthReachedThreshold: TimeInterval = 10.0 static let elapsedTimeFormat = "m:ss" static let fileNameDateFormat = "MM.dd.yyyy HH.mm.ss" static let minimumRecordingDuration = 1.0 } private let themeService: ThemeService private let mediaServiceProvider: VoiceMessageMediaServiceProvider private let _voiceMessageToolbarView: VoiceMessageToolbarView private var displayLink: CADisplayLink! private var audioRecorder: VoiceMessageAudioRecorder? private var audioPlayer: VoiceMessageAudioPlayer? private var waveformAnalyser: WaveformAnalyzer? private var audioSamples: [Float] = [] private var isInLockedMode: Bool = false private var notifiedRemainingTime = false private var recordDuration: TimeInterval? private static let elapsedTimeFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormat = Constants.elapsedTimeFormat return dateFormatter }() private var temporaryFileURL: URL? { guard let roomId = roomId else { return nil } let temporaryFileName = "Voice message-\(roomId)" let temporaryDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) return temporaryDirectoryURL.appendingPathComponent(temporaryFileName).appendingPathExtension("m4a") } @objc public weak var delegate: VoiceMessageControllerDelegate? @objc public var isRecordingAudio: Bool { return audioRecorder?.isRecording ?? false || isInLockedMode } @objc public var voiceMessageToolbarView: UIView { return _voiceMessageToolbarView } @objc public var roomId: String? { didSet { checkForRecording() } } @objc public init(themeService: ThemeService, mediaServiceProvider: VoiceMessageMediaServiceProvider) { self.themeService = themeService self.mediaServiceProvider = mediaServiceProvider _voiceMessageToolbarView = VoiceMessageToolbarView.loadFromNib() super.init() _voiceMessageToolbarView.delegate = self displayLink = CADisplayLink(target: WeakTarget(self, selector: #selector(handleDisplayLinkTick)), selector: WeakTarget.triggerSelector) displayLink.isPaused = true displayLink.add(to: .current, forMode: .common) NotificationCenter.default.addObserver(self, selector: #selector(updateTheme), name: .themeServiceDidChangeTheme, object: nil) updateTheme() NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil) updateUI() } // MARK: - VoiceMessageToolbarViewDelegate func voiceMessageToolbarViewDidRequestRecordingStart(_ toolbarView: VoiceMessageToolbarView) { guard let temporaryFileURL = temporaryFileURL else { return } guard AVAudioSession.sharedInstance().recordPermission == .granted else { delegate?.voiceMessageControllerDidRequestMicrophonePermission(self) return } // Haptic are not played during record on iOS by default. This fix works // only since iOS 13. A workaround for iOS 12 and earlier would be to // dispatch after at least 100ms recordWithOutputURL call if #available(iOS 13.0, *) { try? AVAudioSession.sharedInstance().setCategory(.playAndRecord) try? AVAudioSession.sharedInstance().setAllowHapticsAndSystemSoundsDuringRecording(true) } UIImpactFeedbackGenerator(style: .medium).impactOccurred() audioRecorder = mediaServiceProvider.audioRecorder() audioRecorder?.registerDelegate(self) audioRecorder?.recordWithOutputURL(temporaryFileURL) } func voiceMessageToolbarViewDidRequestRecordingFinish(_ toolbarView: VoiceMessageToolbarView) { finishRecording() } func voiceMessageToolbarViewDidRequestRecordingCancel(_ toolbarView: VoiceMessageToolbarView) { cancelRecording() } func voiceMessageToolbarViewDidRequestLockedModeRecording(_ toolbarView: VoiceMessageToolbarView) { isInLockedMode = true updateUI() } func voiceMessageToolbarViewDidRequestPlaybackToggle(_ toolbarView: VoiceMessageToolbarView) { guard let audioPlayer = audioPlayer, let temporaryFileURL = temporaryFileURL else { return } if audioPlayer.url != nil { if audioPlayer.isPlaying { audioPlayer.pause() } else { audioPlayer.play() } } else { audioPlayer.loadContentFromURL(temporaryFileURL) audioPlayer.play() } } func voiceMessageToolbarViewDidRequestSeek(to progress: CGFloat) { guard let audioPlayer = audioPlayer, let temporaryFileURL = temporaryFileURL, let duration = recordDuration else { return } if audioPlayer.url == nil { audioPlayer.loadContentFromURL(temporaryFileURL) } audioPlayer.seekToTime(duration * Double(progress)) { [weak self] _ in self?.updateUI() } } func voiceMessageToolbarViewDidRequestSend(_ toolbarView: VoiceMessageToolbarView) { guard let temporaryFileURL = temporaryFileURL else { return } audioPlayer?.stop() audioRecorder?.stopRecording() sendRecordingAtURL(temporaryFileURL) isInLockedMode = false updateUI() } // MARK: - AudioRecorderDelegate func audioRecorderDidStartRecording(_ audioRecorder: VoiceMessageAudioRecorder) { notifiedRemainingTime = false updateUI() } func audioRecorderDidFinishRecording(_ audioRecorder: VoiceMessageAudioRecorder) { updateUI() } func audioRecorder(_ audioRecorder: VoiceMessageAudioRecorder, didFailWithError: Error) { isInLockedMode = false updateUI() MXLog.error("Failed recording voice message.") } // MARK: - VoiceMessageAudioPlayerDelegate func audioPlayerDidStartPlaying(_ audioPlayer: VoiceMessageAudioPlayer) { updateUI() } func audioPlayerDidPausePlaying(_ audioPlayer: VoiceMessageAudioPlayer) { updateUI() } func audioPlayerDidStopPlaying(_ audioPlayer: VoiceMessageAudioPlayer) { updateUI() } func audioPlayerDidFinishPlaying(_ audioPlayer: VoiceMessageAudioPlayer) { audioPlayer.seekToTime(0.0) { [weak self] _ in self?.updateUI() } } func audioPlayer(_ audioPlayer: VoiceMessageAudioPlayer, didFailWithError: Error) { updateUI() MXLog.error("Failed playing voice message.") } // MARK: - Private private func checkForRecording() { guard let temporaryFileURL = temporaryFileURL else { return } if FileManager.default.fileExists(atPath: temporaryFileURL.path) { isInLockedMode = true loadDraftRecording() } updateUI() } private func finishRecording() { guard let temporaryFileURL = temporaryFileURL else { return } let recordDuration = audioRecorder?.currentTime self.recordDuration = recordDuration audioRecorder?.stopRecording() guard isInLockedMode else { if recordDuration ?? 0 >= Constants.minimumRecordingDuration { sendRecordingAtURL(temporaryFileURL) } else { cancelRecording() } return } loadDraftRecording() updateUI() } private func cancelRecording() { isInLockedMode = false audioPlayer?.stop() audioRecorder?.stopRecording() deleteRecordingAtURL(temporaryFileURL) UINotificationFeedbackGenerator().notificationOccurred(.error) updateUI() } private func loadDraftRecording() { guard let temporaryFileURL = temporaryFileURL, let roomId = roomId else { return } audioPlayer = mediaServiceProvider.audioPlayerForIdentifier(roomId) audioPlayer?.registerDelegate(self) audioPlayer?.loadContentFromURL(temporaryFileURL) audioSamples = [] } private func sendRecordingAtURL(_ sourceURL: URL) { let dispatchGroup = DispatchGroup() var duration = 0.0 var invertedSamples: [Float]? var finalURL: URL? dispatchGroup.enter() VoiceMessageAudioConverter.mediaDurationAt(sourceURL) { result in switch result { case .success: if let someDuration = try? result.get() { duration = someDuration } else { MXLog.error("[VoiceMessageController] Failed retrieving media duration") } case .failure(let error): MXLog.error("[VoiceMessageController] Failed getting audio duration with: \(error)") } dispatchGroup.leave() } dispatchGroup.enter() let analyser = WaveformAnalyzer(audioAssetURL: sourceURL) analyser?.samples(count: 100, completionHandler: { samples in // Dispatch back from the WaveformAnalyzer's internal queue DispatchQueue.main.async { if let samples = samples { invertedSamples = samples.compactMap { return 1.0 - $0 } // linearly normalized to [0, 1] (1 -> -50 dB) } else { MXLog.error("[VoiceMessageController] Failed sampling recorder voice message.") } dispatchGroup.leave() } }) dispatchGroup.enter() let destinationURL = sourceURL.deletingPathExtension().appendingPathExtension("ogg") VoiceMessageAudioConverter.convertToOpusOgg(sourceURL: sourceURL, destinationURL: destinationURL) { result in switch result { case .success: finalURL = destinationURL case .failure(let error): MXLog.error("Failed failed encoding audio message with: \(error)") } dispatchGroup.leave() } dispatchGroup.notify(queue: .main) { guard let url = finalURL else { return } self.delegate?.voiceMessageController(self, didRequestSendForFileAtURL: url, duration: UInt(duration * 1000), samples: invertedSamples) { [weak self] success in UINotificationFeedbackGenerator().notificationOccurred((success ? .success : .error)) self?.deleteRecordingAtURL(sourceURL) self?.deleteRecordingAtURL(destinationURL) } } } private func deleteRecordingAtURL(_ url: URL?) { guard let url = url else { return } do { try FileManager.default.removeItem(at: url) } catch { MXLog.error(error) } } @objc private func updateTheme() { _voiceMessageToolbarView.update(theme: themeService.theme) } @objc private func applicationWillResignActive() { finishRecording() } @objc private func handleDisplayLinkTick() { updateUI() } private func updateUI() { let shouldUpdateFromAudioPlayer = isInLockedMode && !(audioRecorder?.isRecording ?? false) if shouldUpdateFromAudioPlayer { updateUIFromAudioPlayer() } else { updateUIFromAudioRecorder() } } private func updateUIFromAudioRecorder() { let isRecording = audioRecorder?.isRecording ?? false displayLink.isPaused = !isRecording let requiredNumberOfSamples = _voiceMessageToolbarView.getRequiredNumberOfSamples() if audioSamples.count != requiredNumberOfSamples { padSamplesArrayToSize(requiredNumberOfSamples) } let sample = audioRecorder?.averagePowerForChannelNumber(0) ?? 0.0 audioSamples.insert(sample, at: 0) audioSamples.removeLast() let currentTime = audioRecorder?.currentTime ?? 0.0 if currentTime >= Constants.maximumAudioRecordingDuration { finishRecording() return } var details = VoiceMessageToolbarViewDetails() details.state = (isRecording ? (isInLockedMode ? .lockedModeRecord : .record) : (isInLockedMode ? .lockedModePlayback : .idle)) details.elapsedTime = VoiceMessageController.elapsedTimeFormatter.string(from: Date(timeIntervalSinceReferenceDate: currentTime)) details.audioSamples = audioSamples if isRecording { if currentTime >= Constants.maximumAudioRecordingDuration - Constants.maximumAudioRecordingLengthReachedThreshold { if !self.notifiedRemainingTime { UIImpactFeedbackGenerator(style: .medium).impactOccurred() } notifiedRemainingTime = true let remainingTime = ceil(Constants.maximumAudioRecordingDuration - currentTime) details.toastMessage = VectorL10n.voiceMessageRemainingRecordingTime(String(remainingTime)) } else { details.toastMessage = (isInLockedMode ? VectorL10n.voiceMessageStopLockedModeRecording : VectorL10n.voiceMessageReleaseToSend) } } _voiceMessageToolbarView.configureWithDetails(details) } private func updateUIFromAudioPlayer() { guard let audioPlayer = audioPlayer, let temporaryFileURL = temporaryFileURL else { return } displayLink.isPaused = !audioPlayer.isPlaying let requiredNumberOfSamples = _voiceMessageToolbarView.getRequiredNumberOfSamples() if audioSamples.count != requiredNumberOfSamples && requiredNumberOfSamples > 0 { padSamplesArrayToSize(requiredNumberOfSamples) waveformAnalyser = WaveformAnalyzer(audioAssetURL: temporaryFileURL) waveformAnalyser?.samples(count: requiredNumberOfSamples, completionHandler: { [weak self] samples in guard let samples = samples else { MXLog.error("Could not sample audio recording.") return } DispatchQueue.main.async { self?.audioSamples = samples self?.updateUIFromAudioPlayer() } }) } let duration: TimeInterval if let recordDuration = recordDuration { duration = recordDuration } else { let asset = AVURLAsset(url: temporaryFileURL) duration = asset.duration.seconds recordDuration = duration } var details = VoiceMessageToolbarViewDetails() details.state = (audioRecorder?.isRecording ?? false ? (isInLockedMode ? .lockedModeRecord : .record) : (isInLockedMode ? .lockedModePlayback : .idle)) // Show the current time if the player is paused, show duration when at 0. let currentTime = audioPlayer.currentTime let displayTime = currentTime > 0 ? currentTime : duration details.elapsedTime = VoiceMessageController.elapsedTimeFormatter.string(from: Date(timeIntervalSinceReferenceDate: displayTime)) details.progress = duration > 0 ? currentTime / duration : 0 details.audioSamples = audioSamples details.isPlaying = audioPlayer.isPlaying _voiceMessageToolbarView.configureWithDetails(details) } private func padSamplesArrayToSize(_ size: Int) { let delta = size - audioSamples.count guard delta > 0 else { return } audioSamples = audioSamples + [Float](repeating: 0.0, count: delta) } }
apache-2.0
e71bac7083e30ff31ae0a01685b8969f
35.392354
191
0.63095
5.959473
false
false
false
false
powerytg/PearlCam
PearlCam/PearlFX/Filters/MonochromeFilterNode.swift
2
870
// // MonochromeFilterNode.swift // PearlCam // // Created by Tiangong You on 6/10/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit import GPUImage class MonochromeFilterNode: FilterNode { var monoFilter = MonochromeFilter() init() { super.init(filter: monoFilter) enabled = false monoFilter.color = Color(red: 0.5, green: 0.5, blue: 0.5) } var intensity : Float? { didSet { if intensity != nil { let colorValue = 1.0 - intensity! monoFilter.color = Color(red: colorValue, green: colorValue, blue: colorValue) } } } override func cloneFilter() -> FilterNode? { let clone = MonochromeFilterNode() clone.enabled = enabled clone.intensity = intensity return clone } }
bsd-3-clause
9baff7e7ea7e980c7e5653398490df1e
22.486486
94
0.582278
4.099057
false
false
false
false
studware/Mobile-Applications-for-iOS-Course-Project
iCapucine/RatingControl.swift
1
4424
// // RatingControl.swift // iCapucine // // Created by Angela Teneva on 4/5/17. // Copyright © 2017 Telerik Academy - Sofia, Bulgaria. All rights reserved. // import UIKit @IBDesignable class RatingControl: UIStackView { //MARK: Properties private var ratingButtons = [UIButton]() var rating = 0 { didSet { updateButtonSelectionStates() } } @IBInspectable var starSize: CGSize = CGSize(width: 44.0, height: 44.0){ didSet{ setupButtons() } } @IBInspectable var starCount: Int = 5 { didSet{ setupButtons() } } //MARK: Initialization override init(frame: CGRect) { super.init(frame: frame) setupButtons() } required init(coder: NSCoder) { super.init(coder: coder) setupButtons() } //MARK: Button Action func ratingButtonTapped(button: UIButton) { guard let index = ratingButtons.index(of: button) else { fatalError("The button, \(button), is not in the ratingButtons array: \(ratingButtons)") } // Calculate the rating of the selected button let selectedRating = index + 1 if selectedRating == rating { // If the selected star represents the current rating, reset the rating to 0. rating = 0 } else { // Otherwise set the rating to the selected star rating = selectedRating } } //MARK: Private Methods private func setupButtons(){ // Clear any existing buttons for button in ratingButtons { removeArrangedSubview(button) button.removeFromSuperview() } ratingButtons.removeAll() // Load Button Images let bundle = Bundle(for: type(of: self)) let filledStar = UIImage(named: "filledStar", in: bundle, compatibleWith: self.traitCollection) let emptyStar = UIImage(named:"emptyStar", in: bundle, compatibleWith: self.traitCollection) let highlightedStar = UIImage(named:"highlightedStar", in: bundle, compatibleWith: self.traitCollection) for index in 0..<starCount { let button = UIButton() // Set the button images button.setImage(emptyStar, for: .normal) button.setImage(filledStar, for: .selected) button.setImage(highlightedStar, for: .highlighted) button.setImage(highlightedStar, for: [.highlighted, .selected]) button.translatesAutoresizingMaskIntoConstraints = false button.heightAnchor.constraint(equalToConstant: starSize.height).isActive = true button.widthAnchor.constraint(equalToConstant: starSize.width).isActive = true // Set the accessibility label button.accessibilityLabel = "Set \(index + 1) star rating" button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for:.touchUpInside) addArrangedSubview(button) ratingButtons.append(button) } updateButtonSelectionStates() } private func updateButtonSelectionStates() { for (index, button) in ratingButtons.enumerated() { // If the index of a button is less than the rating, that button should be selected. button.isSelected = index < rating // Set the hint string for the currently selected star let hintString: String? if rating == index + 1 { hintString = "Tap to reset the rating to zero." } else { hintString = nil } // Calculate the value string let valueString: String switch (rating) { case 0: valueString = "No rating set." case 1: valueString = "1 star set." default: valueString = "\(rating) stars set." } // Assign the hint string and value string button.accessibilityHint = hintString button.accessibilityValue = valueString } } }
mit
7928983f8ddf6886174dd3debc2cf606
30.368794
112
0.560253
5.387333
false
false
false
false
soapyigu/LeetCode_Swift
Math/DivideTwoIntegers.swift
1
844
/** * Question Link: https://leetcode.com/problems/divide-two-integers/ * Primary idea: Use left shift and subtraction to get the number of every digit * Time Complexity: O(logn), Space Complexity: O(1) * */ class DivideTwoIntegers { func divide(_ dividend: Int, _ divisor: Int) -> Int { if divisor == 0 { return Int.max } let isNegative = (dividend < 0) != (divisor < 0) var dividend = abs(dividend), divisor = abs(divisor), count = 0 while dividend >= divisor { var shift = 0 while dividend >= (divisor << shift) { shift += 1 } dividend -= divisor << (shift - 1) count += 1 << (shift - 1) } return isNegative ? -count : count } }
mit
ae5e5bd99e313bebb3f764cc19c452dc
27.133333
80
0.50237
4.489362
false
false
false
false
coolmacmaniac/swift-ios
LearnSwift/MusicAlbum/MusicAlbum/Model/Album.swift
1
785
// // Album.swift // MusicAlbum // // Created by Sourabh on 22/06/17. // Copyright © 2017 Home. All rights reserved. // import Foundation class Album { internal static let kKeys = "keys" internal static let kValues = "values" // internal static let kArtist = "Artist" internal static let kCoverUrl = "Cover-Url" internal static let kGenre = "Genre" internal static let kTitle = "Title" internal static let kYear = "Year" public var title: String public var artist: String public var genre: String public var coverUrl: String public var year: String init(title: String, artist: String, genre: String, coverUrl: String, year: String) { self.title = title self.artist = artist self.genre = genre self.coverUrl = coverUrl self.year = year } }
gpl-3.0
ad71d86354be17cdddfc2f327a217166
19.631579
85
0.697704
3.308017
false
false
false
false