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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kingcos/Swift-3-Design-Patterns | 21-Chain_of_Responsibility_Pattern.playground/Contents.swift | 1 | 2685 | //: Playground - noun: a place where people can play
// Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Design-Patterns
import UIKit
// 请求
struct Request {
enum RequestType: String {
case leave = "请假"
case salary = "加薪"
}
var requestType: RequestType
var requestContent: String
var number: Int
}
// 经理协议
protocol Manager {
var name: String { get }
var superior: Manager? { get }
func requestApplications(_ request: Request)
}
// 普通经理
struct CommonManager: Manager {
var name: String
var superior: Manager?
func requestApplications(_ request: Request) {
if request.requestType == .leave && request.number <= 2 {
print("CommonManager 批准:\(request.requestType.rawValue) \(request.number) 天")
} else {
superior!.requestApplications(request)
}
}
}
// 总监
struct Majordomo: Manager {
var name: String
var superior: Manager?
func requestApplications(_ request: Request) {
if request.requestType == .leave && request.number <= 5 {
print("Majordomo 批准:\(request.requestType.rawValue) \(request.number) 天")
} else {
superior!.requestApplications(request)
}
}
}
// 总经理
struct GeneralManager: Manager {
var name: String
var superior: Manager?
init(_ name: String) {
self.name = name
}
func requestApplications(_ request: Request) {
if request.requestType == .leave {
print("GeneralManager 批准:\(request.requestType.rawValue) \(request.number) 天")
} else if request.requestType == .salary
&& request.number <= 500 {
print("GeneralManager 批准:\(request.requestType.rawValue) \(request.number) 元")
} else if request.requestType == .salary
&& request.number > 500 {
print("GeneralManager 考虑考虑")
}
}
}
let generalMng = GeneralManager("总经理")
let majordomo = Majordomo(name: "总监", superior: generalMng)
let commonMng = CommonManager(name: "普通经理", superior: majordomo)
let rqA = Request(requestType: .leave, requestContent: "小菜请假", number: 1)
commonMng.requestApplications(rqA)
let rqB = Request(requestType: .leave, requestContent: "小菜请假", number: 4)
commonMng.requestApplications(rqB)
let rqC = Request(requestType: .salary, requestContent: "小菜加薪", number: 200)
commonMng.requestApplications(rqC)
let rqD = Request(requestType: .salary, requestContent: "小菜加薪", number: 1000)
commonMng.requestApplications(rqD)
| apache-2.0 | 8cc1995951fd54eb8f669ebc8fe67161 | 27.411111 | 90 | 0.644896 | 3.886018 | false | false | false | false |
Mazy-ma/DemoBySwift | CircularImageLoaderAnimation/CircularImageLoaderAnimation/CircularLoaderView.swift | 1 | 3994 | //
// CircularLoaderView.swift
// CircularImageLoaderAnimation
//
// Created by Mazy on 2017/6/28.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
class CircularLoaderView: UIView {
// 画圆环
let circlePathLayer = CAShapeLayer()
// 圆环半径
let circleRadius: CGFloat = 20.0
// 进度
var progress: CGFloat {
get {
return circlePathLayer.strokeEnd
}
set {
if (newValue > 1) {
circlePathLayer.strokeEnd = 1
} else if (newValue < 0) {
circlePathLayer.strokeEnd = 0
} else {
circlePathLayer.strokeEnd = newValue
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
override func layoutSubviews() {
super.layoutSubviews()
circlePathLayer.frame = bounds
circlePathLayer.path = circlePath().cgPath
}
func configure() {
progress = 0
circlePathLayer.frame = bounds
circlePathLayer.lineWidth = 2.0
circlePathLayer.fillColor = UIColor.clear.cgColor
circlePathLayer.strokeColor = UIColor.red.cgColor
layer.addSublayer(circlePathLayer)
backgroundColor = UIColor.white
}
func circleFrame() -> CGRect {
var circleFrame = CGRect(x: 0, y: 0, width: 2*circleRadius, height: 2*circleRadius)
circleFrame.origin.x = circlePathLayer.bounds.midX - circleFrame.midX
circleFrame.origin.y = circlePathLayer.bounds.midY - circleFrame.midY
return circleFrame
}
func circlePath() -> UIBezierPath {
return UIBezierPath(ovalIn: circleFrame())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func reveal() {
// 1
backgroundColor = UIColor.clear
// progress = 1
// 2
// circlePathLayer.removeAnimation(forKey: "strokeEnd")
circlePathLayer.removeAllAnimations()
// 3
circlePathLayer.removeFromSuperlayer()
superview?.layer.mask = circlePathLayer
// 2-1
let center = CGPoint(x: bounds.midX, y: bounds.minY)
let finalRadius = sqrt(center.x * center.x + center.y * center.y)
let radiusInset = finalRadius - circleRadius
let outerRect = circleFrame().insetBy(dx: -radiusInset, dy: -radiusInset)
let toPath = UIBezierPath(ovalIn: outerRect).cgPath
// 2-2
let fromPath = circlePathLayer.path
let fromLineWidth = circlePathLayer.lineWidth
// 2-3
CATransaction.begin()
CATransaction.setValue(kCFBooleanFalse, forKey: kCATransactionDisableActions)
circlePathLayer.lineWidth = 2*finalRadius
circlePathLayer.path = toPath
CATransaction.commit()
// 2-4
let lineWidthAnimation = CABasicAnimation(keyPath: "lineWidth")
lineWidthAnimation.fromValue = fromLineWidth
lineWidthAnimation.toValue = 2*finalRadius
let pathAnimation = CABasicAnimation(keyPath: "path")
pathAnimation.fromValue = fromPath
pathAnimation.toValue = toPath
// 2-5
let groupAnimation = CAAnimationGroup()
groupAnimation.duration = 0.25
groupAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
groupAnimation.animations = [pathAnimation, lineWidthAnimation]
groupAnimation.delegate = self
circlePathLayer.add(groupAnimation, forKey: "strokeWidth")
}
}
extension CircularLoaderView: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
circlePathLayer.removeFromSuperlayer()
superview?.layer.mask = nil
}
}
| apache-2.0 | a0109479634e56535aebb4bf163134af | 28.42963 | 104 | 0.609615 | 5.412807 | false | false | false | false |
AliSoftware/SwiftGen | Sources/SwiftGenKit/Parsers/InterfaceBuilder/Platform.swift | 1 | 1130 | //
// SwiftGenKit
// Copyright © 2020 SwiftGen
// MIT Licence
//
import Foundation
extension InterfaceBuilder {
enum Platform: String, CaseIterable {
case iOS = "iOS.CocoaTouch"
case macOS = "MacOSX.Cocoa"
case tvOS = "AppleTV"
case watchOS = "watchKit"
init?(runtime: String) {
// files without "trait variations" will have a runtime value of (for example):
// "iOS.CocoaTouch.iPad"
if let platform = Platform.allCases.first(where: { runtime.hasPrefix($0.rawValue) }) {
self = platform
} else {
return nil
}
}
var name: String {
switch self {
case .tvOS:
return "tvOS"
case .iOS:
return "iOS"
case .macOS:
return "macOS"
case .watchOS:
return "watchOS"
}
}
var prefix: String {
switch self {
case .iOS, .tvOS, .watchOS:
return "UI"
case .macOS:
return "NS"
}
}
var module: String {
switch self {
case .iOS, .tvOS, .watchOS:
return "UIKit"
case .macOS:
return "AppKit"
}
}
}
}
| mit | 52c6f86e16349bffcc4aeaabe4837bb6 | 18.807018 | 92 | 0.543844 | 4.032143 | false | false | false | false |
ndevenish/KerbalHUD | KerbalHUD/GLKitExtensions.swift | 1 | 2925 | //
// GLKitExtensions.swift
// KerbalHUD
//
// Created by Nicholas Devenish on 29/08/2015.
// Copyright © 2015 Nicholas Devenish. All rights reserved.
//
import Foundation
import GLKit
private let _glErrors = [
GLenum(GL_NO_ERROR) : "",
GLenum(GL_INVALID_ENUM): "GL_INVALID_ENUM",
GLenum(GL_INVALID_VALUE): "GL_INVALID_VALUE",
GLenum(GL_INVALID_OPERATION): "GL_INVALID_OPERATION",
GLenum(GL_INVALID_FRAMEBUFFER_OPERATION): "GL_INVALID_FRAMEBUFFER_OPERATION",
GLenum(GL_OUT_OF_MEMORY): "GL_OUT_OF_MEMORY"
]
func processGLErrors() {
var error = glGetError()
while error != 0 {
print("OpenGL Error: " + _glErrors[error]!)
error = glGetError()
}
}
//infix operator • {}
infix operator ± {}
prefix func -(of: GLKVector3) -> GLKVector3 {
return GLKVector3MultiplyScalar(of, -1)
}
func +(left: GLKVector3, right: GLKVector3) -> GLKVector3 {
return GLKVector3Add(left, right)
}
func -(left: GLKVector3, right: GLKVector3) -> GLKVector3 {
return GLKVector3Subtract(left, right)
}
func *(left: GLKVector3, right: GLfloat) -> GLKVector3 {
return GLKVector3MultiplyScalar(left, right)
}
func *(left: GLfloat, right: GLKVector3) -> GLKVector3 {
return GLKVector3MultiplyScalar(right, left)
}
func •(left: GLKVector3, right: GLKVector3) -> GLfloat {
return GLKVector3DotProduct(left, right)
}
func ±(left: GLfloat, right: GLfloat) -> (GLfloat, GLfloat) {
return (left + right, left - right)
}
func *(left: GLKMatrix4, right: GLKVector3) -> GLKVector3 {
return GLKMatrix4MultiplyVector3(left, right)
}
func *(left: GLKMatrix4, right: GLKVector4) -> GLKVector4 {
return GLKMatrix4MultiplyVector4(left, right)
}
func *(left: GLKMatrix4, right: GLKMatrix4) -> GLKMatrix4 {
return GLKMatrix4Multiply(left, right)
}
extension GLKVector3 {
var length : GLfloat {
return GLKVector3Length(self)
}
static var eX : GLKVector3 { return GLKVector3Make(1, 0, 0) }
static var eY : GLKVector3 { return GLKVector3Make(0, 1, 0) }
static var eZ : GLKVector3 { return GLKVector3Make(0, 0, 1) }
}
extension GLKVector3 : CustomStringConvertible {
public var description : String {
return NSStringFromGLKVector3(self)
}
}
extension GLKVector2 {
var length : GLfloat {
return GLKVector2Length(self)
}
func normalize() -> GLKVector2 {
return GLKVector2Normalize(self)
}
init(x : Float, y: Float) {
self = GLKVector2Make(x, y)
}
}
func +(left: GLKVector2, right: GLKVector2) -> GLKVector2 {
return GLKVector2Add(left, right)
}
func -(left: GLKVector2, right: GLKVector2) -> GLKVector2 {
return GLKVector2Subtract(left, right)
}
func *(left: GLKVector2, right: GLfloat) -> GLKVector2 {
return GLKVector2MultiplyScalar(left, right)
}
func *(left: Float, right: GLKVector2) -> GLKVector2 {
return GLKVector2MultiplyScalar(right, left)
}
func /(left: GLKVector2, right: GLfloat) -> GLKVector2 {
return GLKVector2DivideScalar(left, right)
} | mit | 39d34e9c44b9b4e6b8ca86ec047376b0 | 25.0625 | 79 | 0.708019 | 3.412865 | false | false | false | false |
FlyKite/FKConsole | FKConsoleDemo/ViewController.swift | 1 | 1526 | //
// ViewController.swift
// FKConsoleDemo
//
// Created by FlyKite on 2016/12/2.
// Copyright © 2016年 FlyKite. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let field = UITextField.init(frame: CGRect(x: 50, y: 100, width: 250, height: 20))
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
field.placeholder = "Log message..."
self.view.addSubview(field)
let button = UIButton.init(type: UIButtonType.system)
button.frame = CGRect(x: 50, y: 120, width: 100, height: 50)
button.setTitle("print it", for: UIControlState.normal)
button.addTarget(self, action: #selector(printMessage), for: UIControlEvents.touchUpInside)
self.view.addSubview(button)
let tips = UILabel.init(frame: CGRect(x: 50, y: 200, width: 250, height: 100))
tips.text = "Double tap with 3 fingers to show console window, you should register FKConsole before use it (see AppDelegate)."
tips.numberOfLines = 0
self.view.addSubview(tips)
Log.d("Debug start...")
}
func printMessage() {
Log.v(field.text)
Log.d(field.text)
Log.i(field.text)
Log.w(field.text)
Log.e(field.text)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 65ce65ddf22f5246914fa1181a2bb0eb | 29.46 | 134 | 0.629022 | 4.094086 | false | false | false | false |
remenkoff/core-data-by-udemy | HomeReport/HomeReport/CoreDataStack.swift | 1 | 988 | //
// CoreDataStack.swift
// HomeReport
//
// Created by Ruslan Remenkov on 07.07.17.
// Copyright © 2017 Ruslan Remenkov. All rights reserved.
//
import Foundation
import CoreData
final class CoreDataStack {
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "HomeReport")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 6660926a587615f785420d7218a27567 | 24.973684 | 88 | 0.574468 | 5.222222 | false | false | false | false |
uberbruns/CasingTools | Sources/CasingTools/main.swift | 1 | 1989 | //
// main.swift
// CasingTools
//
// Created by Karsten Bruns on 10.11.18.
// Copyright © 2018 bruns.me. All rights reserved.
//
import Foundation
import Moderator
let sampleText = "SoLong, andTHX_forAll the-fish!"
let arguments = Moderator(description: "Tool for transforming the casing of text.")
let casings: [String : (String) -> String] = [
"lowerCamelCase": Casing.lowerCamelCase,
"upperCamelCase": Casing.upperCamelCase,
"uppercaseTrainCase": Casing.uppercaseTrainCase,
"lowercaseTrainCase": Casing.lowercaseTrainCase,
"uppercaseSnailCase": Casing.uppercaseSnailCase,
"lowercaseSnailCase": Casing.lowercaseSnailCase,
"titleCase": Casing.titleCase,
"sentenceCase": Casing.sentenceCase,
]
let casingList = casings.keys.sorted()
var casingOptions = [FutureValue<Bool>]()
let stringOption = arguments.add(
Argument<String>.optionWithValue("t", "text", name: "Text", description: "The input text you want to transform. For example: \"\(sampleText)\"")
)
let helpOption = arguments.add(
Argument<String>.option("h", "help", description: "Prints this help page.")
)
for casingName in casingList {
let casingFunc = casings[casingName]!
let description = "Exemplary result: \"" + casingFunc("So long, and THX for all the fish!") + "\""
let option = arguments.add(Argument<String>
.option(casingName.lowercased(), description: description))
casingOptions.append(option)
}
do {
try arguments.parse()
if let string = stringOption.value {
for (index, casingOption) in casingOptions.enumerated() where casingOption.value {
let casingName = casingList[index]
let casingFunc = casings[casingName]!
print(casingFunc(string))
exit(0)
}
} else if helpOption.value {
print(arguments.usagetext)
exit(0)
} else {
print(arguments.usagetext)
exit(1)
}
} catch {
print(error)
exit(Int32(error._code))
}
| mit | 2973839d6f3e3788237ceeaef419f502 | 29.121212 | 148 | 0.678068 | 3.793893 | false | false | false | false |
Gaantz/SocketsIO---iOS | socket.io-client-swift-master/SocketIOClientSwift/SocketEventHandler.swift | 4 | 2376 | //
// EventHandler.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 1/18/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
private func emitAckCallback(socket: SocketIOClient?, num: Int?)
(items: AnyObject...) -> Void {
socket?.emitAck(num ?? -1, withItems: items)
}
private func emitAckCallbackObjectiveC(socket: SocketIOClient?, num: Int?)
(items: NSArray) -> Void {
socket?.emitAck(num ?? -1, withItems: items as [AnyObject])
}
struct SocketEventHandler {
let event: String
let callback: NormalCallback?
let callBackObjectiveC: NormalCallbackObjectiveC?
init(event: String, callback: NormalCallback) {
self.event = event
self.callback = callback
self.callBackObjectiveC = nil
}
init(event: String, callback: NormalCallbackObjectiveC) {
self.event = event
self.callback = nil
self.callBackObjectiveC = callback
}
func executeCallback(items:NSArray? = nil, withAck ack:Int? = nil, withAckType type:Int? = nil,
withSocket socket:SocketIOClient? = nil) {
self.callback != nil ?
self.callback?(items, emitAckCallback(socket, num: ack))
: self.callBackObjectiveC?(items, emitAckCallbackObjectiveC(socket, num: ack))
}
}
| mit | 40d7bafa434e6a8ba89e76d83acbd2ef | 38.6 | 99 | 0.699495 | 4.304348 | false | false | false | false |
argon/mas | Carthage/Checkouts/Quick/Externals/Nimble/Sources/Nimble/ExpectationMessage.swift | 2 | 10619 | public indirect enum ExpectationMessage {
// --- Primary Expectations ---
/// includes actual value in output ("expected to <message>, got <actual>")
case expectedActualValueTo(/* message: */ String)
/// uses a custom actual value string in output ("expected to <message>, got <actual>")
case expectedCustomValueTo(/* message: */ String, actual: String)
/// excludes actual value in output ("expected to <message>")
case expectedTo(/* message: */ String)
/// allows any free-form message ("<message>")
case fail(/* message: */ String)
// --- Composite Expectations ---
// Generally, you'll want the methods, appended(message:) and appended(details:) instead.
/// Not Fully Implemented Yet.
case prepends(/* Prepended Message */ String, ExpectationMessage)
/// appends after an existing message ("<expectation> (use beNil() to match nils)")
case appends(ExpectationMessage, /* Appended Message */ String)
/// provides long-form multi-line explainations ("<expectation>\n\n<string>")
case details(ExpectationMessage, String)
internal var sampleMessage: String {
let asStr = toString(actual: "<ACTUAL>", expected: "expected", to: "to")
let asFailureMessage = FailureMessage()
update(failureMessage: asFailureMessage)
// swiftlint:disable:next line_length
return "(toString(actual:expected:to:) -> \(asStr) || update(failureMessage:) -> \(asFailureMessage.stringValue))"
}
/// Returns the smallest message after the "expected to" string that summarizes the error.
///
/// Returns the message part from ExpectationMessage, ignoring all .appends and .details.
public var expectedMessage: String {
switch self {
case let .fail(msg):
return msg
case let .expectedTo(msg):
return msg
case let .expectedActualValueTo(msg):
return msg
case let .expectedCustomValueTo(msg, _):
return msg
case let .prepends(_, expectation):
return expectation.expectedMessage
case let .appends(expectation, msg):
return "\(expectation.expectedMessage)\(msg)"
case let .details(expectation, _):
return expectation.expectedMessage
}
}
/// Appends a message after the primary expectation message
public func appended(message: String) -> ExpectationMessage {
switch self {
case .fail, .expectedTo, .expectedActualValueTo, .expectedCustomValueTo, .appends, .prepends:
return .appends(self, message)
case let .details(expectation, msg):
return .details(expectation.appended(message: message), msg)
}
}
/// Appends a message hinting to use beNil() for when the actual value given was nil.
public func appendedBeNilHint() -> ExpectationMessage {
return appended(message: " (use beNil() to match nils)")
}
/// Appends a detailed (aka - multiline) message after the primary expectation message
/// Detailed messages will be placed after .appended(message:) calls.
public func appended(details: String) -> ExpectationMessage {
return .details(self, details)
}
internal func visitLeafs(_ f: (ExpectationMessage) -> ExpectationMessage) -> ExpectationMessage {
// swiftlint:disable:previous identifier_name
switch self {
case .fail, .expectedTo, .expectedActualValueTo, .expectedCustomValueTo:
return f(self)
case let .prepends(msg, expectation):
return .prepends(msg, expectation.visitLeafs(f))
case let .appends(expectation, msg):
return .appends(expectation.visitLeafs(f), msg)
case let .details(expectation, msg):
return .details(expectation.visitLeafs(f), msg)
}
}
/// Replaces a primary expectation with one returned by f. Preserves all composite expectations
/// that were built upon it (aka - all appended(message:) and appended(details:).
public func replacedExpectation(_ f: @escaping (ExpectationMessage) -> ExpectationMessage) -> ExpectationMessage {
// swiftlint:disable:previous identifier_name
func walk(_ msg: ExpectationMessage) -> ExpectationMessage {
switch msg {
case .fail, .expectedTo, .expectedActualValueTo, .expectedCustomValueTo:
return f(msg)
default:
return msg
}
}
return visitLeafs(walk)
}
/// Wraps a primary expectation with text before and after it.
/// Alias to prepended(message: before).appended(message: after)
public func wrappedExpectation(before: String, after: String) -> ExpectationMessage {
return prepended(expectation: before).appended(message: after)
}
/// Prepends a message by modifying the primary expectation
public func prepended(expectation message: String) -> ExpectationMessage {
func walk(_ msg: ExpectationMessage) -> ExpectationMessage {
switch msg {
case let .expectedTo(msg):
return .expectedTo(message + msg)
case let .expectedActualValueTo(msg):
return .expectedActualValueTo(message + msg)
case let .expectedCustomValueTo(msg, actual):
return .expectedCustomValueTo(message + msg, actual: actual)
default:
return msg.visitLeafs(walk)
}
}
return visitLeafs(walk)
}
// swiftlint:disable:next todo
// TODO: test & verify correct behavior
internal func prepended(message: String) -> ExpectationMessage {
return .prepends(message, self)
}
/// Converts the tree of ExpectationMessages into a final built string.
public func toString(actual: String, expected: String = "expected", to: String = "to") -> String {
switch self {
case let .fail(msg):
return msg
case let .expectedTo(msg):
return "\(expected) \(to) \(msg)"
case let .expectedActualValueTo(msg):
return "\(expected) \(to) \(msg), got \(actual)"
case let .expectedCustomValueTo(msg, actual):
return "\(expected) \(to) \(msg), got \(actual)"
case let .prepends(msg, expectation):
return "\(msg)\(expectation.toString(actual: actual, expected: expected, to: to))"
case let .appends(expectation, msg):
return "\(expectation.toString(actual: actual, expected: expected, to: to))\(msg)"
case let .details(expectation, msg):
return "\(expectation.toString(actual: actual, expected: expected, to: to))\n\n\(msg)"
}
}
// Backwards compatibility: converts ExpectationMessage tree to FailureMessage
internal func update(failureMessage: FailureMessage) {
switch self {
case let .fail(msg) where !msg.isEmpty:
failureMessage.stringValue = msg
case .fail:
break
case let .expectedTo(msg):
failureMessage.actualValue = nil
failureMessage.postfixMessage = msg
case let .expectedActualValueTo(msg):
failureMessage.postfixMessage = msg
case let .expectedCustomValueTo(msg, actual):
failureMessage.postfixMessage = msg
failureMessage.actualValue = actual
case let .prepends(msg, expectation):
expectation.update(failureMessage: failureMessage)
if let desc = failureMessage.userDescription {
failureMessage.userDescription = "\(msg)\(desc)"
} else {
failureMessage.userDescription = msg
}
case let .appends(expectation, msg):
expectation.update(failureMessage: failureMessage)
failureMessage.appendMessage(msg)
case let .details(expectation, msg):
expectation.update(failureMessage: failureMessage)
failureMessage.appendDetails(msg)
}
}
}
extension FailureMessage {
internal func toExpectationMessage() -> ExpectationMessage {
let defaultMessage = FailureMessage()
if expected != defaultMessage.expected || _stringValueOverride != nil {
return .fail(stringValue)
}
var message: ExpectationMessage = .fail(userDescription ?? "")
if actualValue != "" && actualValue != nil {
message = .expectedCustomValueTo(postfixMessage, actual: actualValue ?? "")
} else if postfixMessage != defaultMessage.postfixMessage {
if actualValue == nil {
message = .expectedTo(postfixMessage)
} else {
message = .expectedActualValueTo(postfixMessage)
}
}
if postfixActual != defaultMessage.postfixActual {
message = .appends(message, postfixActual)
}
if let extended = extendedMessage {
message = .details(message, extended)
}
return message
}
}
#if canImport(Darwin)
import class Foundation.NSObject
public class NMBExpectationMessage: NSObject {
private let msg: ExpectationMessage
internal init(swift msg: ExpectationMessage) {
self.msg = msg
}
public init(expectedTo message: String) {
self.msg = .expectedTo(message)
}
public init(expectedActualValueTo message: String) {
self.msg = .expectedActualValueTo(message)
}
public init(expectedActualValueTo message: String, customActualValue actual: String) {
self.msg = .expectedCustomValueTo(message, actual: actual)
}
public init(fail message: String) {
self.msg = .fail(message)
}
public init(prepend message: String, child: NMBExpectationMessage) {
self.msg = .prepends(message, child.msg)
}
public init(appendedMessage message: String, child: NMBExpectationMessage) {
self.msg = .appends(child.msg, message)
}
public init(prependedMessage message: String, child: NMBExpectationMessage) {
self.msg = .prepends(message, child.msg)
}
public init(details message: String, child: NMBExpectationMessage) {
self.msg = .details(child.msg, message)
}
public func appendedBeNilHint() -> NMBExpectationMessage {
return NMBExpectationMessage(swift: msg.appendedBeNilHint())
}
public func toSwift() -> ExpectationMessage { return self.msg }
}
extension ExpectationMessage {
func toObjectiveC() -> NMBExpectationMessage {
return NMBExpectationMessage(swift: self)
}
}
#endif
| mit | 7d3c32bf2ce6e72f310a81afe7ddcb3c | 38.921053 | 122 | 0.640173 | 5.18 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/NaturalLanguageUnderstandingV1/NaturalLanguageUnderstanding.swift | 1 | 63757 | /**
* (C) Copyright IBM Corp. 2017, 2022.
*
* 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.
**/
/**
* IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428
**/
// swiftlint:disable file_length
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
import IBMSwiftSDKCore
public typealias WatsonError = RestError
public typealias WatsonResponse = RestResponse
/**
Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural
Language Understanding will give you results for the features you request. The service cleans HTML content before
analysis by default, so the results can ignore most advertisements and other unwanted content.
You can create [custom
models](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing)
with Watson Knowledge Studio to detect custom entities and relations in Natural Language Understanding.
*/
public class NaturalLanguageUnderstanding {
/// The base URL to use when contacting the service.
public var serviceURL: String? = "https://api.us-south.natural-language-understanding.watson.cloud.ibm.com"
/// Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is
/// `2021-08-01`.
public var version: String
/// Service identifiers
public static let defaultServiceName = "natural-language-understanding"
// Service info for SDK headers
internal let serviceName = defaultServiceName
internal let serviceVersion = "v1"
internal let serviceSdkName = "natural_language_understanding"
/// The default HTTP headers for all requests to the service.
public var defaultHeaders = [String: String]()
var session = URLSession(configuration: URLSessionConfiguration.default)
public let authenticator: Authenticator
#if os(Linux)
/**
Create a `NaturalLanguageUnderstanding` object.
If an authenticator is not supplied, the initializer will retrieve credentials from the environment or
a local credentials file and construct an appropriate authenticator using these credentials.
The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env.
Make sure to add the credentials file to your project so that it can be loaded at runtime.
If an authenticator is not supplied and credentials are not available in the environment or a local
credentials file, initialization will fail by throwing an exception.
In that case, try another initializer that directly passes in the credentials.
- parameter version: Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The
current version is `2021-08-01`.
- parameter authenticator: The Authenticator object used to authenticate requests to the service
- serviceName: String = defaultServiceName
*/
public init(version: String, authenticator: Authenticator? = nil, serviceName: String = defaultServiceName) throws {
self.version = version
self.authenticator = try authenticator ?? ConfigBasedAuthenticatorFactory.getAuthenticator(credentialPrefix: serviceName)
if let serviceURL = CredentialUtils.getServiceURL(credentialPrefix: serviceName) {
self.serviceURL = serviceURL
}
RestRequest.userAgent = Shared.userAgent
}
#else
/**
Create a `NaturalLanguageUnderstanding` object.
- parameter version: Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The
current version is `2021-08-01`.
- parameter authenticator: The Authenticator object used to authenticate requests to the service
*/
public init(version: String, authenticator: Authenticator) {
self.version = version
self.authenticator = authenticator
RestRequest.userAgent = Shared.userAgent
}
#endif
#if !os(Linux)
/**
Allow network requests to a server without verification of the server certificate.
**IMPORTANT**: This should ONLY be used if truly intended, as it is unsafe otherwise.
*/
public func disableSSLVerification() {
session = InsecureConnection.session()
}
#endif
/**
Use the HTTP response and data received by the Natural Language Understanding service to extract
information about the error that occurred.
- parameter data: Raw data returned by the service that may represent an error.
- parameter response: the URL response returned by the service.
*/
func errorResponseDecoder(data: Data, response: HTTPURLResponse) -> RestError {
let statusCode = response.statusCode
var errorMessage: String?
var metadata = [String: Any]()
do {
let json = try JSON.decoder.decode([String: JSON].self, from: data)
metadata["response"] = json
if case let .some(.array(errors)) = json["errors"],
case let .some(.object(error)) = errors.first,
case let .some(.string(message)) = error["message"] {
errorMessage = message
} else if case let .some(.string(message)) = json["error"] {
errorMessage = message
} else if case let .some(.string(message)) = json["message"] {
errorMessage = message
} else {
errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode)
}
} catch {
metadata["response"] = data
errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode)
}
return RestError.http(statusCode: statusCode, message: errorMessage, metadata: metadata)
}
/**
Analyze text.
Analyzes text, HTML, or a public webpage for the following features:
- Categories
- Classifications
- Concepts
- Emotion
- Entities
- Keywords
- Metadata
- Relations
- Semantic roles
- Sentiment
- Syntax
- Summarization (Experimental)
If a language for the input text is not specified with the `language` parameter, the service [automatically detects
the
language](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-detectable-languages).
- parameter features: Specific features to analyze the document for.
- parameter text: The plain text to analyze. One of the `text`, `html`, or `url` parameters is required.
- parameter html: The HTML file to analyze. One of the `text`, `html`, or `url` parameters is required.
- parameter url: The webpage to analyze. One of the `text`, `html`, or `url` parameters is required.
- parameter clean: Set this to `false` to disable webpage cleaning. For more information about webpage cleaning,
see [Analyzing
webpages](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages).
- parameter xpath: An [XPath
query](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages#xpath)
to perform on `html` or `url` input. Results of the query will be appended to the cleaned webpage text before it
is analyzed. To analyze only the results of the XPath query, set the `clean` parameter to `false`.
- parameter fallbackToRaw: Whether to use raw HTML content if text cleaning fails.
- parameter returnAnalyzedText: Whether or not to return the analyzed text.
- parameter language: ISO 639-1 code that specifies the language of your text. This overrides automatic language
detection. Language support differs depending on the features you include in your analysis. For more information,
see [Language
support](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-language-support).
- parameter limitTextCharacters: Sets the maximum number of characters that are processed by the service.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func analyze(
features: Features,
text: String? = nil,
html: String? = nil,
url: String? = nil,
clean: Bool? = nil,
xpath: String? = nil,
fallbackToRaw: Bool? = nil,
returnAnalyzedText: Bool? = nil,
language: String? = nil,
limitTextCharacters: Int? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<AnalysisResults>?, WatsonError?) -> Void)
{
// construct body
let analyzeRequest = AnalyzeRequest(
features: features,
text: text,
html: html,
url: url,
clean: clean,
xpath: xpath,
fallback_to_raw: fallbackToRaw,
return_analyzed_text: returnAnalyzedText,
language: language,
limit_text_characters: limitTextCharacters)
guard let body = try? JSON.encoder.encode(analyzeRequest) else {
completionHandler(nil, RestError.serialization(values: "request body"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "analyze")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + "/v1/analyze",
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
// Private struct for the analyze request body
private struct AnalyzeRequest: Encodable {
// swiftlint:disable identifier_name
let features: Features
let text: String?
let html: String?
let url: String?
let clean: Bool?
let xpath: String?
let fallback_to_raw: Bool?
let return_analyzed_text: Bool?
let language: String?
let limit_text_characters: Int?
// swiftlint:enable identifier_name
}
/**
List models.
Lists Watson Knowledge Studio [custom entities and relations
models](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing)
that are deployed to your Natural Language Understanding service.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listModels(
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<ListModelsResults>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listModels")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + "/v1/models",
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Delete model.
Deletes a custom model.
- parameter modelID: Model ID of the model to delete.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteModel(
modelID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<DeleteModelResults>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/models/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Create sentiment model.
(Beta) Creates a custom sentiment model by uploading training data and associated metadata. The model begins the
training and deploying process and is ready to use when the `status` is `available`.
- parameter language: The 2-letter language code of this model.
- parameter trainingData: Training data in CSV format. For more information, see [Sentiment training data
requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-custom-sentiment#sentiment-training-data-requirements).
- parameter name: An optional name for the model.
- parameter description: An optional description of the model.
- parameter modelVersion: An optional version string.
- parameter workspaceID: ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language
Understanding.
- parameter versionDescription: The description of the version.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func createSentimentModel(
language: String,
trainingData: Data,
name: String? = nil,
description: String? = nil,
modelVersion: String? = nil,
workspaceID: String? = nil,
versionDescription: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<SentimentModel>?, WatsonError?) -> Void)
{
// construct body
let multipartFormData = MultipartFormData()
if let languageData = language.data(using: .utf8) {
multipartFormData.append(languageData, withName: "language")
}
multipartFormData.append(trainingData, withName: "training_data", mimeType: "text/csv", fileName: "filename")
if let name = name {
if let nameData = name.data(using: .utf8) {
multipartFormData.append(nameData, withName: "name")
}
}
if let description = description {
if let descriptionData = description.data(using: .utf8) {
multipartFormData.append(descriptionData, withName: "description")
}
}
if let modelVersion = modelVersion {
if let modelVersionData = modelVersion.data(using: .utf8) {
multipartFormData.append(modelVersionData, withName: "model_version")
}
}
if let workspaceID = workspaceID {
if let workspaceIDData = workspaceID.data(using: .utf8) {
multipartFormData.append(workspaceIDData, withName: "workspace_id")
}
}
if let versionDescription = versionDescription {
if let versionDescriptionData = versionDescription.data(using: .utf8) {
multipartFormData.append(versionDescriptionData, withName: "version_description")
}
}
guard let body = try? multipartFormData.toData() else {
completionHandler(nil, RestError.serialization(values: "request multipart form data"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createSentimentModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = multipartFormData.contentType
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + "/v1/models/sentiment",
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
List sentiment models.
(Beta) Returns all custom sentiment models associated with this service instance.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listSentimentModels(
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<ListSentimentModelsResponse>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listSentimentModels")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + "/v1/models/sentiment",
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Get sentiment model details.
(Beta) Returns the status of the sentiment model with the given model ID.
- parameter modelID: ID of the model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getSentimentModel(
modelID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<SentimentModel>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getSentimentModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/models/sentiment/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Update sentiment model.
(Beta) Overwrites the training data associated with this custom sentiment model and retrains the model. The new
model replaces the current deployment.
- parameter modelID: ID of the model.
- parameter language: The 2-letter language code of this model.
- parameter trainingData: Training data in CSV format. For more information, see [Sentiment training data
requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-custom-sentiment#sentiment-training-data-requirements).
- parameter name: An optional name for the model.
- parameter description: An optional description of the model.
- parameter modelVersion: An optional version string.
- parameter workspaceID: ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language
Understanding.
- parameter versionDescription: The description of the version.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func updateSentimentModel(
modelID: String,
language: String,
trainingData: Data,
name: String? = nil,
description: String? = nil,
modelVersion: String? = nil,
workspaceID: String? = nil,
versionDescription: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<SentimentModel>?, WatsonError?) -> Void)
{
// construct body
let multipartFormData = MultipartFormData()
if let languageData = language.data(using: .utf8) {
multipartFormData.append(languageData, withName: "language")
}
multipartFormData.append(trainingData, withName: "training_data", mimeType: "text/csv", fileName: "filename")
if let name = name {
if let nameData = name.data(using: .utf8) {
multipartFormData.append(nameData, withName: "name")
}
}
if let description = description {
if let descriptionData = description.data(using: .utf8) {
multipartFormData.append(descriptionData, withName: "description")
}
}
if let modelVersion = modelVersion {
if let modelVersionData = modelVersion.data(using: .utf8) {
multipartFormData.append(modelVersionData, withName: "model_version")
}
}
if let workspaceID = workspaceID {
if let workspaceIDData = workspaceID.data(using: .utf8) {
multipartFormData.append(workspaceIDData, withName: "workspace_id")
}
}
if let versionDescription = versionDescription {
if let versionDescriptionData = versionDescription.data(using: .utf8) {
multipartFormData.append(versionDescriptionData, withName: "version_description")
}
}
guard let body = try? multipartFormData.toData() else {
completionHandler(nil, RestError.serialization(values: "request multipart form data"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateSentimentModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = multipartFormData.contentType
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/models/sentiment/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "PUT",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Delete sentiment model.
(Beta) Un-deploys the custom sentiment model with the given model ID and deletes all associated customer data,
including any training data or binary artifacts.
- parameter modelID: ID of the model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteSentimentModel(
modelID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<DeleteModelResults>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteSentimentModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/models/sentiment/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Create categories model.
(Beta) Creates a custom categories model by uploading training data and associated metadata. The model begins the
training and deploying process and is ready to use when the `status` is `available`.
- parameter language: The 2-letter language code of this model.
- parameter trainingData: Training data in JSON format. For more information, see [Categories training data
requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories##categories-training-data-requirements).
- parameter trainingDataContentType: The content type of trainingData.
- parameter name: An optional name for the model.
- parameter description: An optional description of the model.
- parameter modelVersion: An optional version string.
- parameter workspaceID: ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language
Understanding.
- parameter versionDescription: The description of the version.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func createCategoriesModel(
language: String,
trainingData: Data,
trainingDataContentType: String? = nil,
name: String? = nil,
description: String? = nil,
modelVersion: String? = nil,
workspaceID: String? = nil,
versionDescription: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<CategoriesModel>?, WatsonError?) -> Void)
{
// construct body
let multipartFormData = MultipartFormData()
if let languageData = language.data(using: .utf8) {
multipartFormData.append(languageData, withName: "language")
}
multipartFormData.append(trainingData, withName: "training_data", mimeType: trainingDataContentType, fileName: "filename")
if let name = name {
if let nameData = name.data(using: .utf8) {
multipartFormData.append(nameData, withName: "name")
}
}
if let description = description {
if let descriptionData = description.data(using: .utf8) {
multipartFormData.append(descriptionData, withName: "description")
}
}
if let modelVersion = modelVersion {
if let modelVersionData = modelVersion.data(using: .utf8) {
multipartFormData.append(modelVersionData, withName: "model_version")
}
}
if let workspaceID = workspaceID {
if let workspaceIDData = workspaceID.data(using: .utf8) {
multipartFormData.append(workspaceIDData, withName: "workspace_id")
}
}
if let versionDescription = versionDescription {
if let versionDescriptionData = versionDescription.data(using: .utf8) {
multipartFormData.append(versionDescriptionData, withName: "version_description")
}
}
guard let body = try? multipartFormData.toData() else {
completionHandler(nil, RestError.serialization(values: "request multipart form data"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createCategoriesModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = multipartFormData.contentType
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + "/v1/models/categories",
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
List categories models.
(Beta) Returns all custom categories models associated with this service instance.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listCategoriesModels(
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<CategoriesModelList>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listCategoriesModels")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + "/v1/models/categories",
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Get categories model details.
(Beta) Returns the status of the categories model with the given model ID.
- parameter modelID: ID of the model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getCategoriesModel(
modelID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<CategoriesModel>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getCategoriesModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/models/categories/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Update categories model.
(Beta) Overwrites the training data associated with this custom categories model and retrains the model. The new
model replaces the current deployment.
- parameter modelID: ID of the model.
- parameter language: The 2-letter language code of this model.
- parameter trainingData: Training data in JSON format. For more information, see [Categories training data
requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories##categories-training-data-requirements).
- parameter trainingDataContentType: The content type of trainingData.
- parameter name: An optional name for the model.
- parameter description: An optional description of the model.
- parameter modelVersion: An optional version string.
- parameter workspaceID: ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language
Understanding.
- parameter versionDescription: The description of the version.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func updateCategoriesModel(
modelID: String,
language: String,
trainingData: Data,
trainingDataContentType: String? = nil,
name: String? = nil,
description: String? = nil,
modelVersion: String? = nil,
workspaceID: String? = nil,
versionDescription: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<CategoriesModel>?, WatsonError?) -> Void)
{
// construct body
let multipartFormData = MultipartFormData()
if let languageData = language.data(using: .utf8) {
multipartFormData.append(languageData, withName: "language")
}
multipartFormData.append(trainingData, withName: "training_data", mimeType: trainingDataContentType, fileName: "filename")
if let name = name {
if let nameData = name.data(using: .utf8) {
multipartFormData.append(nameData, withName: "name")
}
}
if let description = description {
if let descriptionData = description.data(using: .utf8) {
multipartFormData.append(descriptionData, withName: "description")
}
}
if let modelVersion = modelVersion {
if let modelVersionData = modelVersion.data(using: .utf8) {
multipartFormData.append(modelVersionData, withName: "model_version")
}
}
if let workspaceID = workspaceID {
if let workspaceIDData = workspaceID.data(using: .utf8) {
multipartFormData.append(workspaceIDData, withName: "workspace_id")
}
}
if let versionDescription = versionDescription {
if let versionDescriptionData = versionDescription.data(using: .utf8) {
multipartFormData.append(versionDescriptionData, withName: "version_description")
}
}
guard let body = try? multipartFormData.toData() else {
completionHandler(nil, RestError.serialization(values: "request multipart form data"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateCategoriesModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = multipartFormData.contentType
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/models/categories/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "PUT",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Delete categories model.
(Beta) Un-deploys the custom categories model with the given model ID and deletes all associated customer data,
including any training data or binary artifacts.
- parameter modelID: ID of the model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteCategoriesModel(
modelID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<DeleteModelResults>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteCategoriesModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/models/categories/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Create classifications model.
Creates a custom classifications model by uploading training data and associated metadata. The model begins the
training and deploying process and is ready to use when the `status` is `available`.
- parameter language: The 2-letter language code of this model.
- parameter trainingData: Training data in JSON format. For more information, see [Classifications training data
requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-classifications#classification-training-data-requirements).
- parameter trainingDataContentType: The content type of trainingData.
- parameter name: An optional name for the model.
- parameter description: An optional description of the model.
- parameter modelVersion: An optional version string.
- parameter workspaceID: ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language
Understanding.
- parameter versionDescription: The description of the version.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func createClassificationsModel(
language: String,
trainingData: Data,
trainingDataContentType: String? = nil,
name: String? = nil,
description: String? = nil,
modelVersion: String? = nil,
workspaceID: String? = nil,
versionDescription: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<ClassificationsModel>?, WatsonError?) -> Void)
{
// construct body
let multipartFormData = MultipartFormData()
if let languageData = language.data(using: .utf8) {
multipartFormData.append(languageData, withName: "language")
}
multipartFormData.append(trainingData, withName: "training_data", mimeType: trainingDataContentType, fileName: "filename")
if let name = name {
if let nameData = name.data(using: .utf8) {
multipartFormData.append(nameData, withName: "name")
}
}
if let description = description {
if let descriptionData = description.data(using: .utf8) {
multipartFormData.append(descriptionData, withName: "description")
}
}
if let modelVersion = modelVersion {
if let modelVersionData = modelVersion.data(using: .utf8) {
multipartFormData.append(modelVersionData, withName: "model_version")
}
}
if let workspaceID = workspaceID {
if let workspaceIDData = workspaceID.data(using: .utf8) {
multipartFormData.append(workspaceIDData, withName: "workspace_id")
}
}
if let versionDescription = versionDescription {
if let versionDescriptionData = versionDescription.data(using: .utf8) {
multipartFormData.append(versionDescriptionData, withName: "version_description")
}
}
guard let body = try? multipartFormData.toData() else {
completionHandler(nil, RestError.serialization(values: "request multipart form data"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createClassificationsModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = multipartFormData.contentType
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "POST",
url: serviceEndpoint + "/v1/models/classifications",
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
List classifications models.
Returns all custom classifications models associated with this service instance.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func listClassificationsModels(
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<ClassificationsModelList>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listClassificationsModels")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + "/v1/models/classifications",
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Get classifications model details.
Returns the status of the classifications model with the given model ID.
- parameter modelID: ID of the model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func getClassificationsModel(
modelID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<ClassificationsModel>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getClassificationsModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/models/classifications/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "GET",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Update classifications model.
Overwrites the training data associated with this custom classifications model and retrains the model. The new
model replaces the current deployment.
- parameter modelID: ID of the model.
- parameter language: The 2-letter language code of this model.
- parameter trainingData: Training data in JSON format. For more information, see [Classifications training data
requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-classifications#classification-training-data-requirements).
- parameter trainingDataContentType: The content type of trainingData.
- parameter name: An optional name for the model.
- parameter description: An optional description of the model.
- parameter modelVersion: An optional version string.
- parameter workspaceID: ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language
Understanding.
- parameter versionDescription: The description of the version.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func updateClassificationsModel(
modelID: String,
language: String,
trainingData: Data,
trainingDataContentType: String? = nil,
name: String? = nil,
description: String? = nil,
modelVersion: String? = nil,
workspaceID: String? = nil,
versionDescription: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<ClassificationsModel>?, WatsonError?) -> Void)
{
// construct body
let multipartFormData = MultipartFormData()
if let languageData = language.data(using: .utf8) {
multipartFormData.append(languageData, withName: "language")
}
multipartFormData.append(trainingData, withName: "training_data", mimeType: trainingDataContentType, fileName: "filename")
if let name = name {
if let nameData = name.data(using: .utf8) {
multipartFormData.append(nameData, withName: "name")
}
}
if let description = description {
if let descriptionData = description.data(using: .utf8) {
multipartFormData.append(descriptionData, withName: "description")
}
}
if let modelVersion = modelVersion {
if let modelVersionData = modelVersion.data(using: .utf8) {
multipartFormData.append(modelVersionData, withName: "model_version")
}
}
if let workspaceID = workspaceID {
if let workspaceIDData = workspaceID.data(using: .utf8) {
multipartFormData.append(workspaceIDData, withName: "workspace_id")
}
}
if let versionDescription = versionDescription {
if let versionDescriptionData = versionDescription.data(using: .utf8) {
multipartFormData.append(versionDescriptionData, withName: "version_description")
}
}
guard let body = try? multipartFormData.toData() else {
completionHandler(nil, RestError.serialization(values: "request multipart form data"))
return
}
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateClassificationsModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = multipartFormData.contentType
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/models/classifications/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "PUT",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
/**
Delete classifications model.
Un-deploys the custom classifications model with the given model ID and deletes all associated customer data,
including any training data or binary artifacts.
- parameter modelID: ID of the model.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter completionHandler: A function executed when the request completes with a successful result or error
*/
public func deleteClassificationsModel(
modelID: String,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<DeleteModelResults>?, WatsonError?) -> Void)
{
// construct header parameters
var headerParameters = defaultHeaders
let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteClassificationsModel")
headerParameters.merge(sdkHeaders) { (_, new) in new }
headerParameters["Accept"] = "application/json"
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/models/classifications/\(modelID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
completionHandler(nil, RestError.urlEncoding(path: path))
return
}
// ensure that serviceURL is set
guard let serviceEndpoint = serviceURL else {
completionHandler(nil, RestError.noEndpoint)
return
}
let request = RestRequest(
session: session,
authenticator: authenticator,
errorResponseDecoder: errorResponseDecoder,
method: "DELETE",
url: serviceEndpoint + encodedPath,
headerParameters: headerParameters,
queryItems: queryParameters
)
// execute REST request
request.responseObject(completionHandler: completionHandler)
}
}
| apache-2.0 | 72171ed46e17f12af794c45870f249b8 | 41.962938 | 175 | 0.660649 | 5.609943 | false | false | false | false |
Onix-Systems/RainyRefreshControl | Sources/RainScene.swift | 2 | 1169 | //
// RainScene.swift
// raintest
//
// Created by Anton Dolzhenko on 14.11.16.
// Copyright © 2016 Onix Systems. All rights reserved.
//
import UIKit
import SpriteKit
final class RainScene: SKScene {
var particles:SKEmitterNode!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(size: CGSize) {
super.init(size: size)
setup()
}
func setup(){
let bundle = Bundle(for: type(of: self))
let bundleName = bundle.infoDictionary!["CFBundleName"] as! String
let path = Bundle(for: type(of: self)).path(forResource: "rain", ofType: "sks", inDirectory: "\(bundleName).bundle")
if let path = path, let p = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? SKEmitterNode, let texture = UIImage(named: "\(bundleName).bundle/spark", in: bundle, compatibleWith: nil) {
p.particleTexture = SKTexture(image: texture)
particles = p
layout()
addChild(particles)
}
}
func layout(){
particles.position = CGPoint(x: size.width/2, y: size.height)
}
}
| mit | 3cfc211b4cdf5124ca2ea19730579bf7 | 27.487805 | 198 | 0.612158 | 4.013746 | false | false | false | false |
VasilStoyanov/Smartphone-picker | Smartphone picker/Smartphone picker/AddPhoneValidator.swift | 1 | 2169 | import UIKit
@objc class PhoneValidator: NSObject {
var reasonForFail = "Fill all fields";
@objc func modelIsValid(model:String) -> (Bool){
if(model.isEmpty){
reasonForFail = "Model name cannot be empty."
return false;
}
else if(model.characters.count < 2) {
reasonForFail = "Model name cannot be less than 2 characters.";
return false;
}
else if(model.characters.count >= 30) {
reasonForFail = "Model name cannot be more than 30 characters."
return false;
}
return true;
}
@objc func priceIsValid(price:Double) -> (Bool){
if(price <= 0){
reasonForFail = "Price cannot be negative or zero"
return false;
}
else if(price > 100000) {
reasonForFail = "So expensive phone? C'mon..."
return false;
}
return true;
}
@objc func manufacturerNameIsValid(manufacturer:String) -> (Bool){
if(manufacturer.isEmpty){
reasonForFail = "Manufacturer name cannot be empty.";
return false;
}
else if(manufacturer.characters.count < 2) {
reasonForFail = "Manufacturer name cannot be less than 2 characters.";
return false;
}
else if(manufacturer.characters.count >= 30) {
reasonForFail = "Manufacturer name cannot be more than 30 characters."
return false;
}
return true;
}
@objc func descriptionIsValid(deviceDescription:String) -> (Bool){
if(deviceDescription.isEmpty){
reasonForFail = "Description cannot be empty.";
return false;
}
else if(deviceDescription.characters.count < 6) {
reasonForFail = "Description cannot be less than 6 characters.";
return false;
}
else if(deviceDescription.characters.count >= 250) {
reasonForFail = "Description cannot be more than 250 characters."
return false;
}
return true;
}
}
| agpl-3.0 | 48a84105ad21d79622e39c5cbedff35c | 29.985714 | 82 | 0.553711 | 5.12766 | false | false | false | false |
J3D1-WARR10R/WikiRaces | WikiRaces/Shared/Menu View Controllers/MenuViewController/MenuView/MedalView.swift | 2 | 2073 | //
// MedalView.swift
// WikiRaces
//
// Created by Andrew Finke on 3/6/19.
// Copyright © 2019 Andrew Finke. All rights reserved.
//
import SpriteKit
final class MedalView: SKView {
// MARK: - Properties -
private let medalScene = MedalScene(size: .zero)
// MARK: - Initalization -
init() {
super.init(frame: .zero)
presentScene(medalScene)
ignoresSiblingOrder = true
allowsTransparency = true
isUserInteractionEnabled = false
preferredFramesPerSecond = UIScreen.main.maximumFramesPerSecond
medalScene.isPaused = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Life Cycle -
override func layoutSubviews() {
super.layoutSubviews()
scene?.size = bounds.size
}
func showMedals() {
guard medalScene.isPaused else { return }
let firstMedals = PlayerUserDefaultsStat.mpcRaceFinishFirst.value() +
PlayerUserDefaultsStat.gkRaceFinishFirst.value()
let secondMedals = PlayerUserDefaultsStat.mpcRaceFinishSecond.value() +
PlayerUserDefaultsStat.gkRaceFinishSecond.value()
let thirdMedals = PlayerUserDefaultsStat.mpcRaceFinishThird.value() +
PlayerUserDefaultsStat.gkRaceFinishThird.value()
let dnfCount = PlayerUserDefaultsStat.mpcRaceDNF.value() +
PlayerUserDefaultsStat.gkRaceDNF.value()
let metalCount = Int(firstMedals + secondMedals + thirdMedals)
PlayerFirebaseAnalytics.log(event: .displayedMedals, attributes: ["Medals": metalCount])
PlayerUserDefaultsStat.triggeredEasterEgg.increment()
guard metalCount > 0 else { return }
medalScene.showMedals(gold: Int(firstMedals),
silver: Int(secondMedals),
bronze: Int(thirdMedals),
dnf: Int(dnfCount))
medalScene.isPaused = false
UIImpactFeedbackGenerator().impactOccurred()
}
}
| mit | 01c258df9824d56980c9db51b525097c | 30.393939 | 96 | 0.649131 | 5.004831 | false | false | false | false |
niunaruto/DeDaoAppSwift | DeDaoSwift/DeDaoSwift/BaseClass/DDBaseViewController.swift | 1 | 1715 | //
// DDBaseViewController.swift
// DeDaoSwift
//
// Created by niuting on 2017/3/3.
// Copyright © 2017年 niuNaruto. All rights reserved.
//
import UIKit
class DDBaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
initialize()
}
}
extension DDBaseViewController {
/// 初始化基本属性(非数据、非UI的东西,例如某些功能属性的设置...
func initialize() {
}
}
// MARK: 设置navItem
extension DDBaseViewController {
func setLeftSearchNavItem() {
self.navigationItem.leftBarButtonItem = UIBarButtonItem.creatBarButtonItem("new_main_navbar_search_black-1")
}
/// 设置右侧navItem 默认一个play
func setRightNavItems(_ itemsImageName:Array<String>? = nil) {
var rightBarButtonItems = Array<UIBarButtonItem>()
if var imageArray = itemsImageName{
imageArray.insert("navbar_playing_icon_anim_1", at: 0)
for i in 0...(imageArray.count - 1) {
rightBarButtonItems.append(UIBarButtonItem.creatBarButtonItem(imageArray[i],-(i+1)))
}
}else{
rightBarButtonItems.append(UIBarButtonItem.creatBarButtonItem("navbar_playing_icon_anim_1",-1))
}
self.navigationItem.rightBarButtonItems = rightBarButtonItems
}
}
// MARK: 处理navItem点击事件
extension DDBaseViewController {
func clickVideoPlayItem() {
}
func clickLeftSearchNavItem() {
navigationController?.pushViewController(DDSearchViewController(), animated: true)
}
}
| mit | e82d070bda96822d518bb182951c0e37 | 23.606061 | 117 | 0.640394 | 4.72093 | false | false | false | false |
lukaskollmer/RuntimeKit | RuntimeKit/Sources/MethodLookup.swift | 1 | 3161 | //
// Methods.swift
// RuntimeKit
//
// Created by Lukas Kollmer on 30.03.17.
// Copyright © 2017 Lukas Kollmer. All rights reserved.
//
import Foundation
import ObjectiveC
/// An Objective-C method
public struct ObjCMethodInfo {
/// The method's name
public let name: String
/// The method's selector
public let selector: Selector
/// The method's type (whether it's an instace method or a class method)
public let type: MethodType
/// A String describing the method's return type
public var returnType: ObjCTypeEncoding {
return ObjCTypeEncoding(String(cString: method_copyReturnType(_method)))
}
/// Number of arguments accepted by the method
public var numberOfArguments: Int {
return Int(method_getNumberOfArguments(_method))
}
/// The method's argument types
public var argumentTypes: [ObjCTypeEncoding] {
var argTypes = [String]()
for i in 0..<numberOfArguments {
argTypes.append(String(cString: method_copyArgumentType(_method, UInt32(i))!))
}
return argTypes.map(ObjCTypeEncoding.init)
}
/// The method's implementation
public var implementation: IMP {
return method_getImplementation(_method)
}
public let _method: Method
/// Create a new ObjCMethod instance from a `Method` object and a `MethodType` case
///
/// - Parameters:
/// - method: The actual ObjC method
/// - type: The method's type
init(_ method: Method, type: MethodType) {
self._method = method
self.type = type
self.selector = method_getName(method)
self.name = NSStringFromSelector(self.selector)
}
}
public extension NSObject {
/// An object's instance methods
public static var instanceMethods: [ObjCMethodInfo] {
var count: UInt32 = 0
let methodList = class_copyMethodList(self.classForCoder(), &count)
return ObjCMethodArrayFromMethodList(methodList, count, .instance)
}
/// An object's class methods
public static var classMethods: [ObjCMethodInfo] {
var count: UInt32 = 0
let methodList = class_copyMethodList(object_getClass(self), &count)!
return ObjCMethodArrayFromMethodList(methodList, count, .class)
}
public static func methodInfo(for: Selector, type: MethodType) throws -> ObjCMethodInfo {
let cls: AnyClass = type == .instance ? self : object_getClass(self)!
guard let method = class_getMethod(cls, `for`, type) else {
throw RuntimeKitError.methodNotFound
}
return ObjCMethodInfo(method, type: type)
}
}
fileprivate func ObjCMethodArrayFromMethodList(_ methodList: UnsafeMutablePointer<Method>?, _ count: UInt32, _ methodType: MethodType) -> [ObjCMethodInfo] {
guard let methodList = methodList else { return [] }
var methods = [ObjCMethodInfo]()
for i in 0..<count {
let method = methodList[Int(i)]
methods.append(ObjCMethodInfo(method, type: methodType))
}
return methods
}
| mit | ab845ab2c040339a129b27489d04a613 | 29.384615 | 156 | 0.641772 | 4.759036 | false | false | false | false |
mdiep/Logician | Sources/Variable.swift | 1 | 6132 | //
// Variable.swift
// Logician
//
// Created by Matt Diephouse on 9/2/16.
// Copyright © 2016 Matt Diephouse. All rights reserved.
//
import Foundation
public protocol VariableProtocol: PropertyProtocol where Value: Equatable {
/// Extracts the variable from the receiver.
var variable: Variable<Value> { get }
}
/// A function that transforms a state based a bijection, throwing an error if
/// the bijection fails to unify.
internal typealias Bijection = (State) throws -> State
private func biject<From: Equatable, To: Equatable>(
_ lhs: AnyVariable,
_ rhs: AnyVariable,
_ transform: @escaping (From) -> To
) -> Bijection {
return { state in
guard let value = state.value(of: lhs) else { return state }
return try state.unifying(rhs, transform(value as! From))
}
}
extension VariableProtocol {
/// Create a new variable that's related to this one by a transformation.
public func bimap<A: Equatable>(
forward: @escaping (Value) -> A,
backward: @escaping (A) -> Value
) -> Variable<A> {
let source = variable.erased
let a = AnyVariable(A.self)
let bijections = [
a: biject(source, a, forward),
source: biject(a, source, backward),
]
return Variable<A>(a, bijections: bijections)
}
/// Create a new variable that's related to this one by a transformation.
///
/// - important: The `identity` must uniquely identify this bimap so that
/// Logician will know that the new variables are the same if
/// it's executed multiple times.
///
/// - parameters:
/// - identity: A string that uniquely identifies this bimap.
/// - forward: A block that maps this value into two values.
/// - backward: A block that maps two values back into the this value.
public func bimap<A: Hashable, B: Hashable>(
identity: String,
forward: @escaping (Value) -> (A, B),
backward: @escaping ((A, B)) -> Value
) -> (Variable<A>, Variable<B>) {
let source = variable.erased
let a = AnyVariable(A.self, source, key: "\(identity).0")
let b = AnyVariable(B.self, source, key: "\(identity).1")
let unifySource: Bijection = { state in
guard let a = state.value(of: a), let b = state.value(of: b) else {
return state
}
return try state.unifying(source, backward((a as! A, b as! B)))
}
let bijections = [
a: biject(source, a) { forward($0).0 },
b: biject(source, b) { forward($0).1 },
source: unifySource,
]
return (
Variable<A>(a, bijections: bijections),
Variable<B>(b, bijections: bijections)
)
}
/// Create a new variable that's related to this one by a transformation.
///
/// - note: The location of this bimap in the source code determines its
/// identity. If you need it to live in multiple locations, you need
/// to specify an explicit identity.
///
/// - parameters:
/// - identity: A string that uniquely identifies this bimap.
/// - forward: A block that maps this value into two values.
/// - backward: A block that maps two values back into the this value.
public func bimap<A: Hashable, B: Hashable>(
file: StaticString = #file,
line: Int = #line,
function: StaticString = #function,
forward: @escaping (Value) -> (A, B),
backward: @escaping ((A, B)) -> Value
) -> (Variable<A>, Variable<B>) {
let identity = "\(file):\(line):\(function)"
return bimap(identity: identity, forward: forward, backward: backward)
}
}
/// An unknown value in a logic problem.
public struct Variable<Value: Equatable> {
/// A type-erased version of the variable.
internal var erased: AnyVariable
/// The bijection information if this variable was created with `bimap`.
internal let bijections: [AnyVariable: Bijection]
/// Create a new variable.
public init() {
self.init(AnyVariable(Value.self))
}
/// Create a new variable.
fileprivate init(_ erased: AnyVariable, bijections: [AnyVariable: Bijection] = [:]) {
self.erased = erased
self.bijections = bijections
}
}
extension Variable: VariableProtocol {
public var property: Property<Value> {
return Property(self, { $0 })
}
public var variable: Variable<Value> {
return self
}
}
/// A type-erased, hashable `Variable`.
internal class AnyVariable: Hashable {
internal struct Basis {
typealias Key = String
let source: AnyVariable
let key: Key
}
/// The basis of the variable if it is derived.
internal let basis: Basis?
/// A type-erased function that will test two values for equality.
internal let equal: (Any, Any) -> Bool
/// Create a new identity.
fileprivate init<Value: Equatable>(_ type: Value.Type) {
basis = nil
self.equal = { ($0 as! Value) == ($1 as! Value) }
}
/// Create a variable based on another variable.
fileprivate init<Value: Equatable>(
_ type: Value.Type,
_ source: AnyVariable,
key: String
) {
basis = Basis(source: source, key: key)
self.equal = { ($0 as! Value) == ($1 as! Value) }
}
var hashValue: Int {
if let basis = self.basis {
return basis.source.hashValue ^ basis.key.hashValue
} else {
return ObjectIdentifier(self).hashValue
}
}
static func ==(lhs: AnyVariable, rhs: AnyVariable) -> Bool {
if let lhs = lhs.basis, let rhs = rhs.basis {
return lhs.source == rhs.source && lhs.key == rhs.key
} else {
return lhs === rhs
}
}
}
/// Test whether the variables have the same identity.
internal func == <Left, Right>(lhs: Variable<Left>, rhs: Variable<Right>) -> Bool {
return lhs.erased == rhs.erased
}
| mit | 75764cde34f37b0c235a6d348175a893 | 32.502732 | 89 | 0.593052 | 4.263561 | false | false | false | false |
jindulys/Leetcode_Solutions_Swift | Sources/String/394_DecodeString.swift | 1 | 1342 | //
// 394_DecodeString.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-11-27.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:394 Decode String
URL: https://leetcode.com/problems/decode-string/
Space: O(N)
Time: O(N)
*/
class DecodeString_Solution {
func decodeString(_ s: String) -> String {
guard s.characters.count > 0 else {
return ""
}
var numberStack: [Int] = []
var prefixStringStack: [String] = []
let characters = Array(s.characters)
var currentPrefix = ""
var currentNumber = ""
let numbers: [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for i in 0..<characters.count {
if numbers.contains(characters[i]) {
currentNumber += String(characters[i])
} else if characters[i] == "]" {
let repeatedTimes = numberStack.pop()!
currentPrefix = currentPrefix * repeatedTimes
let previousPrefix = prefixStringStack.pop()!
currentPrefix = previousPrefix + currentPrefix
} else if characters[i] != "[" {
currentPrefix += String(characters[i])
} else {
prefixStringStack.push(currentPrefix)
numberStack.push(Int(String(currentNumber))!)
currentPrefix = ""
currentNumber = ""
}
}
return currentPrefix
}
}
| mit | dd8ae20e45304f02252e17e1b5e3514d | 26.9375 | 81 | 0.609247 | 3.788136 | false | false | false | false |
phatblat/WatchKitCoreData | WatchKitCoreData/AppDelegate.swift | 1 | 3742 | //
// AppDelegate.swift
// WatchKitCoreData
//
// Created by Ben Chatelain on 5/14/15.
// Copyright (c) 2015 Ben Chatelain. All rights reserved.
//
import UIKit
import CoreData
import WatchKitCoreDataFramework
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var dataController: DataController?
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
println(NSHomeDirectory())
dataController = AppGroupDataController() {
[unowned self] () -> Void in
// Prevent standing up the UI when being launched in the background
if (application.applicationState != .Background) {
self.setupUI()
}
}
return true
}
/// Called after state restoration
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
return true
}
/// 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 applicationWillResignActive(application: UIApplication) {
saveData()
}
/// 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 applicationDidEnterBackground(application: UIApplication) {
saveData()
}
/// 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 applicationWillEnterForeground(application: UIApplication) {
// If launched in the background, but then transitioning into the foreground, we need to stand up the UI
if window == nil {
setupUI()
}
}
/// 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 applicationDidBecomeActive(application: UIApplication) { }
/// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
/// Saves changes in the application's managed object context before the application terminates.
func applicationWillTerminate(application: UIApplication) {
saveData()
}
// MARK: - Private
/// Tells the dataController to save.
private func saveData () {
dataController?.save()
}
/// Stands up the initial UI of the app.
private func setupUI() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let vc = storyboard.instantiateInitialViewController() as? UIViewController {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.rootViewController = vc
window.makeKeyAndVisible()
self.window = window
// Pass the data controller down through the UI
if let dc = vc as? DataConsumer {
dc.dataController = dataController
}
}
}
}
| mit | 626cea8682b29cfdc54c8345b79644f9 | 38.808511 | 282 | 0.696419 | 5.576751 | false | false | false | false |
ysnrkdm/Graphene | Sources/Graphene/SimpleEvaluator.swift | 1 | 1716 | //
// SimpleEvaluator.swift
// FlatReversi
//
// Created by Kodama Yoshinori on 12/14/14.
// Copyright (c) 2014 Yoshinori Kodama. All rights reserved.
//
import Foundation
open class SimpleEvaluator: BitBoardEvaluator {
var wPossibleMoves: [Double] = [1.0]
var wEdge: [Double] = [1.0]
var wFixedPieces: [Double] = [1.0]
var wOpenness: [Double] = [1.0]
var wBoardEvaluation: [Double] = [1.0]
var zones: Zones = Zones(width: 8, height: 8, initVal: 1)
func configure(_ wPossibleMoves: [Double], wEdge: [Double], wFixedPieces: [Double], wOpenness: [Double], wBoardEvaluation: [Double], zones: Zones) {
self.wPossibleMoves = wPossibleMoves
self.wEdge = wEdge
self.wFixedPieces = wFixedPieces
self.wOpenness = wOpenness
self.wBoardEvaluation = wBoardEvaluation
self.zones = zones
}
override open func evaluate(_ boardRepresentation: BoardRepresentation, forPlayer: Pieces) -> Double {
let ePossibleMoves = cs_double_random()
return ePossibleMoves
}
override open func evaluateBitBoard(_ board: BitBoard, forPlayer: Pieces) -> Double {
let ePossibleMoves = cs_double_random()
return ePossibleMoves
}
// MARK: Factors
func possibleMoves(_ board: BoardRepresentation, forPlayer: Pieces) -> Int {
return board.getPuttables(forPlayer).count
}
// MARK: Private functions
func getWeightByPhase(_ weight: [Double], board: BoardRepresentation) -> Double {
let perPhase: Int = 60 / weight.count
var phase: Int = (60 - board.getNumVacant()) / perPhase
phase = phase >= weight.count ? phase - 1 : phase
return weight[phase]
}
}
| mit | a45effd36a858c41b8cb6b247168826f | 31.377358 | 152 | 0.655594 | 3.788079 | false | false | false | false |
unsignedapps/FileSelectionController | FileSelectionController/FileSelectionCollectionViewCell.swift | 1 | 3046 | //
// FileSelectionCollectionViewCell.swift
// FileSelectionController
//
// Created by Robert Amos on 10/11/2015.
// Copyright © 2015 Unsigned Apps. All rights reserved.
//
import UIKit
@IBDesignable
class FileSelectionCollectionViewCell: UICollectionViewCell
{
@IBInspectable var selectedBorderColor: UIColor = UIColor.blue
@IBInspectable var selectedBorderWidth: Float = 1.0
@IBInspectable var selectedCornerRadius: Float = 8.0
@IBInspectable var selectedTextColor: UIColor = UIColor.white
var selectedOrder: Int?
{
didSet
{
self.selectedOrderLabel?.text = self.selectedOrder != nil ? String(self.selectedOrder!) : nil;
}
}
@IBOutlet var selectedOrderLabel: UILabel?
@IBOutlet var imageView: UIImageView?
var image: UIImage? = nil
{
didSet
{
guard let imageView = self.imageView else { return; }
imageView.image = self.image;
}
}
override var isSelected: Bool
{
didSet
{
if self.isSelected
{
self.layer.borderColor = self.selectedBorderColor.cgColor;
self.layer.borderWidth = CGFloat(self.selectedBorderWidth);
self.cornerRadius = CGFloat(self.selectedCornerRadius);
self.selectedOrderLabel?.isHidden = false;
self.clipsToBounds = true;
self.contentView.clipsToBounds = true;
self.selectedOrderLabel?.backgroundColor = self.selectedBorderColor;
self.selectedOrderLabel?.textColor = self.selectedTextColor;
} else
{
self.layer.borderWidth = 0.0;
self.layer.borderColor = nil;
self.cornerRadius = 0.0;
self.selectedOrderLabel?.isHidden = true;
self.clipsToBounds = true;
self.contentView.clipsToBounds = true;
}
}
}
override func awakeFromNib()
{
super.awakeFromNib();
guard let label = self.selectedOrderLabel else { return; }
// we want to round only a couple of corners in self.selectedOrderLabel
label.translatesAutoresizingMaskIntoConstraints = false;
let layer = CAShapeLayer();
let radius = CGSize(width: CGFloat(self.selectedCornerRadius), height: CGFloat(self.selectedCornerRadius));
layer.path = UIBezierPath(roundedRect: label.bounds, byRoundingCorners: [.topRight, .bottomLeft], cornerRadii: radius).cgPath;
label.layer.mask = layer;
}
override func prepareForReuse()
{
super.prepareForReuse();
self.selectedOrder = nil;
}
static var nib: UINib
{
return UINib(nibName: String(describing: FileSelectionCollectionViewCell.self), bundle: Bundle(for: self));
}
static var reuseIdentifier: String
{
return String(describing: FileSelectionCollectionViewCell.self);
}
}
| mit | 5dd390739883a5c12950b1c23a55bfae | 31.052632 | 134 | 0.617077 | 5.342105 | false | false | false | false |
KevinCoble/AIToolbox | iOS Playgrounds/NeuralNetwork.playground/Sources/RecurrentNeuralNetwork.swift | 2 | 35775 | //
// RecurrentNeuralNetwork.swift
// AIToolbox
//
// Created by Kevin Coble on 5/5/16.
// Copyright © 2016 Kevin Coble. All rights reserved.
//
import Foundation
import Accelerate
final class RecurrentNeuralNode {
// Activation function
let activation : NeuralActivationFunction
let numWeights : Int // This includes weights from inputs and from feedback
let numInputs : Int
let numFeedback : Int
var W : [Double] // Weights for inputs from previous layer
var U : [Double] // Weights for recurrent input data from this layer
var h : Double // Last result calculated
var outputHistory : [Double] // History of output for the sequence
var 𝟃E𝟃h : Double // Gradient in error for this time step and future time steps with respect to output of this node
var 𝟃E𝟃z : Double // Gradient of error with respect to weighted sum
var 𝟃E𝟃W : [Double] // Accumulated weight W change gradient
var 𝟃E𝟃U : [Double] // Accumulated weight U change gradient
var rmspropDecay : Double? // Decay rate for rms prop weight updates. If nil, rmsprop is not used
/// Create the neural network node with a set activation function
init(numInputs : Int, numFeedbacks : Int, activationFunction: NeuralActivationFunction)
{
activation = activationFunction
self.numInputs = numInputs + 1 // Add one weight for the bias term
self.numFeedback = numFeedbacks
numWeights = self.numInputs + self.numFeedback
W = []
U = []
h = 0.0
outputHistory = []
𝟃E𝟃h = 0.0
𝟃E𝟃z = 0.0
𝟃E𝟃W = []
𝟃E𝟃U = []
}
// Initialize the weights
func initWeights(_ startWeights: [Double]!)
{
if let startWeights = startWeights {
if (startWeights.count == 1) {
W = [Double](repeating: startWeights[0], count: numInputs)
U = [Double](repeating: startWeights[0], count: numFeedback)
}
else if (startWeights.count == numInputs+numFeedback) {
// Full weight array, just split into the two weight arrays
W = Array(startWeights[0..<numInputs])
U = Array(startWeights[numInputs..<numInputs+numFeedback])
}
else {
W = []
var index = 0 // First number (if more than 1) goes into the bias weight, then repeat the initial
for _ in 0..<numInputs-1 {
if (index >= startWeights.count-1) { index = 0 } // Wrap if necessary
W.append(startWeights[index])
index += 1
}
W.append(startWeights[startWeights.count-1]) // Add the bias term
index = 0
U = []
for _ in 0..<numFeedback {
if (index >= startWeights.count-1) { index = 1 } // Wrap if necessary
U.append(startWeights[index])
index += 1
}
}
}
else {
W = []
for _ in 0..<numInputs-1 {
W.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numInputs-1))) // input weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs
}
W.append(Gaussian.gaussianRandom(0.0, standardDeviation:1.0)) // Bias weight - Initialize to a random number to break initial symmetry of the network
U = []
for _ in 0..<numFeedback {
U.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numFeedback))) // feedback weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs
}
}
}
func setRMSPropDecay(_ decay: Double?)
{
rmspropDecay = decay
}
func feedForward(_ x: [Double], hPrev: [Double]) -> Double
{
// Get the weighted sum: z = W⋅x + U⋅h(t-1)
var z = 0.0
var sum = 0.0
vDSP_dotprD(W, 1, x, 1, &z, vDSP_Length(numInputs))
vDSP_dotprD(U, 1, hPrev, 1, &sum, vDSP_Length(numFeedback))
z += sum
// Use the activation function function for the nonlinearity: h = act(z)
switch (activation) {
case .none:
h = z
break
case .hyperbolicTangent:
h = tanh(z)
break
case .sigmoidWithCrossEntropy:
fallthrough
case .sigmoid:
h = 1.0 / (1.0 + exp(-z))
break
case .rectifiedLinear:
h = z
if (z < 0) { h = 0.0 }
break
case .softSign:
h = z / (1.0 + abs(z))
break
case .softMax:
h = exp(z)
break
}
return h
}
// Get the partial derivitive of the error with respect to the weighted sum
func getFinalNode𝟃E𝟃zs(_ 𝟃E𝟃h: Double)
{
// Calculate 𝟃E/𝟃z. 𝟃E/𝟃z = 𝟃E/𝟃h ⋅ 𝟃h/𝟃z = 𝟃E/𝟃h ⋅ derivitive of nonlinearity
// derivitive of the non-linearity: tanh' -> 1 - result^2, sigmoid -> result - result^2, rectlinear -> 0 if result<0 else 1
switch (activation) {
case .none:
𝟃E𝟃z = 𝟃E𝟃h
break
case .hyperbolicTangent:
𝟃E𝟃z = 𝟃E𝟃h * (1 - h * h)
break
case .sigmoid:
𝟃E𝟃z = 𝟃E𝟃h * (h - h * h)
break
case .sigmoidWithCrossEntropy:
𝟃E𝟃z = 𝟃E𝟃h
break
case .rectifiedLinear:
𝟃E𝟃z = h <= 0.0 ? 0.0 : 𝟃E𝟃h
break
case .softSign:
// Reconstitute z from h
var z : Double
if (h < 0) { // Negative z
z = h / (1.0 + h)
𝟃E𝟃z = -𝟃E𝟃h / ((1.0 + z) * (1.0 + z))
}
else { // Positive z
z = h / (1.0 - h)
𝟃E𝟃z = 𝟃E𝟃h / ((1.0 + z) * (1.0 + z))
}
break
case .softMax:
𝟃E𝟃z = 𝟃E𝟃h
break
}
}
func reset𝟃E𝟃hs()
{
𝟃E𝟃h = 0.0
}
func addTo𝟃E𝟃hs(_ addition: Double)
{
𝟃E𝟃h += addition
}
func getWeightTimes𝟃E𝟃zs(_ weightIndex: Int) ->Double
{
return W[weightIndex] * 𝟃E𝟃z
}
func getFeedbackWeightTimes𝟃E𝟃zs(_ weightIndex: Int) ->Double
{
return U[weightIndex] * 𝟃E𝟃z
}
func get𝟃E𝟃z()
{
// 𝟃E𝟃h contains 𝟃E/𝟃h for the current time step plus all future time steps.
// Calculate 𝟃E𝟃z. 𝟃E/𝟃z = 𝟃E/𝟃h ⋅ 𝟃h/𝟃z = 𝟃E/𝟃h ⋅ derivitive of non-linearity
// derivitive of the non-linearity: tanh' -> 1 - result^2, sigmoid -> result - result^2, rectlinear -> 0 if result<0 else 1
switch (activation) {
case .none:
break
case .hyperbolicTangent:
𝟃E𝟃z = 𝟃E𝟃h * (1 - h * h)
break
case .sigmoidWithCrossEntropy:
fallthrough
case .sigmoid:
𝟃E𝟃z = 𝟃E𝟃h * (h - h * h)
break
case .rectifiedLinear:
𝟃E𝟃z = h < 0.0 ? 0.0 : 𝟃E𝟃h
break
case .softSign:
// Reconstitute z from h
var z : Double
if (h < 0) { // Negative z
z = h / (1.0 + h)
𝟃E𝟃z = -𝟃E𝟃h / ((1.0 + z) * (1.0 + z))
}
else { // Positive z
z = h / (1.0 - h)
𝟃E𝟃z = 𝟃E𝟃h / ((1.0 + z) * (1.0 + z))
}
break
case .softMax:
// Should not get here - SoftMax is only valid on output layer
break
}
}
func clearWeightChanges()
{
𝟃E𝟃W = [Double](repeating: 0.0, count: numInputs)
𝟃E𝟃U = [Double](repeating: 0.0, count: numFeedback)
}
func appendWeightChanges(_ x: [Double], hPrev: [Double]) -> Double
{
// Update each weight accumulation
// z = W⋅x + U⋅hPrev, therefore
// 𝟃E/𝟃W = 𝟃E/𝟃z ⋅ 𝟃z/𝟃W = 𝟃E/𝟃z ⋅ x
// 𝟃E/𝟃U = 𝟃E/𝟃z ⋅ 𝟃z/𝟃U = 𝟃E/𝟃z ⋅ hPrev
// 𝟃E/𝟃W += 𝟃E/𝟃z ⋅ 𝟃z/𝟃W = 𝟃E/𝟃z ⋅ x
vDSP_vsmaD(x, 1, &𝟃E𝟃z, 𝟃E𝟃W, 1, &𝟃E𝟃W, 1, vDSP_Length(numInputs))
// 𝟃E/𝟃U += 𝟃E/𝟃z ⋅ 𝟃z/𝟃U = 𝟃E/𝟃z ⋅ hPrev
vDSP_vsmaD(hPrev, 1, &𝟃E𝟃z, 𝟃E𝟃U, 1, &𝟃E𝟃U, 1, vDSP_Length(numFeedback))
return h // return output for next layer
}
func updateWeightsFromAccumulations(_ averageTrainingRate: Double)
{
// Update the weights from the accumulations
// weights -= accumulation * averageTrainingRate
var η = -averageTrainingRate // Needed for unsafe pointer conversion - negate for multiply-and-add vector operation
vDSP_vsmaD(𝟃E𝟃W, 1, &η, W, 1, &W, 1, vDSP_Length(numInputs))
vDSP_vsmaD(𝟃E𝟃U, 1, &η, U, 1, &U, 1, vDSP_Length(numFeedback))
}
func decayWeights(_ decayFactor : Double)
{
var λ = decayFactor // Needed for unsafe pointer conversion
vDSP_vsmulD(W, 1, &λ, &W, 1, vDSP_Length(numInputs-1))
vDSP_vsmulD(U, 1, &λ, &U, 1, vDSP_Length(numFeedback))
}
func resetSequence()
{
h = 0.0
outputHistory = [0.0] // first 'previous' value is zero
𝟃E𝟃z = 0.0 // Backward propogation previous 𝟃E𝟃z (𝟃E𝟃z from next time step in sequence) is zero
}
func storeRecurrentValues()
{
outputHistory.append(h)
}
func getLastRecurrentValue()
{
h = outputHistory.removeLast()
}
func getPreviousOutputValue() -> Double
{
let hPrev = outputHistory.last
if (hPrev == nil) { return 0.0 }
return hPrev!
}
func gradientCheck(x: [Double], ε: Double, Δ: Double, network: NeuralNetwork) -> Bool
{
var result = true
// Iterate through each W parameter
for index in 0..<W.count {
let oldValue = W[index]
// Get the network loss with a small addition to the parameter
W[index] += ε
_ = network.feedForward(x)
var plusLoss : [Double]
do {
plusLoss = try network.getResultLoss()
}
catch {
return false
}
// Get the network loss with a small subtraction from the parameter
W[index] = oldValue - ε
_ = network.feedForward(x)
var minusLoss : [Double]
do {
minusLoss = try network.getResultLoss()
}
catch {
return false
}
W[index] = oldValue
// Iterate over the results
for resultIndex in 0..<plusLoss.count {
// Get the numerical gradient estimate 𝟃E/𝟃W
let gradient = (plusLoss[resultIndex] - minusLoss[resultIndex]) / (2.0 * ε)
// Compare with the analytical gradient
let difference = abs(gradient - 𝟃E𝟃W[index])
// print("difference = \(difference)")
if (difference > Δ) {
result = false
}
}
}
// Iterate through each U parameter
for index in 0..<U.count {
let oldValue = U[index]
// Get the network loss with a small addition to the parameter
U[index] += ε
_ = network.feedForward(x)
var plusLoss : [Double]
do {
plusLoss = try network.getResultLoss()
}
catch {
return false
}
// Get the network loss with a small subtraction from the parameter
U[index] = oldValue - ε
_ = network.feedForward(x)
var minusLoss : [Double]
do {
minusLoss = try network.getResultLoss()
}
catch {
return false
}
U[index] = oldValue
// Iterate over the results
for resultIndex in 0..<plusLoss.count {
// Get the numerical gradient estimate 𝟃E/𝟃U
let gradient = (plusLoss[resultIndex] - minusLoss[resultIndex]) / (2.0 * ε)
// Compare with the analytical gradient
let difference = abs(gradient - 𝟃E𝟃U[index])
// print("difference = \(difference)")
if (difference > Δ) {
result = false
}
}
}
return result
}
}
/// Class for a recurrent network layer with individual nodes (slower, but easier to get into details)
final class RecurrentNeuralLayerWithNodes: NeuralLayer {
// Nodes
var nodes : [RecurrentNeuralNode]
var bpttSequenceIndex: Int
/// Create the neural network layer based on a tuple (number of nodes, activation function)
init(numInputs : Int, layerDefinition: (layerType: NeuronLayerType, numNodes: Int, activation: NeuralActivationFunction, auxiliaryData: AnyObject?))
{
nodes = []
for _ in 0..<layerDefinition.numNodes {
nodes.append(RecurrentNeuralNode(numInputs: numInputs, numFeedbacks: layerDefinition.numNodes, activationFunction: layerDefinition.activation))
}
bpttSequenceIndex = 0
}
// Initialize the weights
func initWeights(_ startWeights: [Double]!)
{
if let startWeights = startWeights {
if (startWeights.count >= nodes.count * nodes[0].numWeights) {
// If there are enough weights for all nodes, split the weights and initialize
var startIndex = 0
for node in nodes {
let subArray = Array(startWeights[startIndex...(startIndex+node.numWeights-1)])
node.initWeights(subArray)
startIndex += node.numWeights
}
}
else {
// If there are not enough weights for all nodes, initialize each node with the set given
for node in nodes {
node.initWeights(startWeights)
}
}
}
else {
// No specified weights - just initialize normally
for node in nodes {
node.initWeights(nil)
}
}
}
func getWeights() -> [Double]
{
var weights: [Double] = []
for node in nodes {
weights += node.W
weights += node.U
}
return weights
}
func setRMSPropDecay(_ decay: Double?)
{
for node in nodes {
node.setRMSPropDecay(decay)
}
}
func getLastOutput() -> [Double]
{
var h: [Double] = []
for node in nodes {
h.append(node.h)
}
return h
}
func getNodeCount() -> Int
{
return nodes.count
}
func getWeightsPerNode()-> Int
{
return nodes[0].numWeights
}
func getActivation()-> NeuralActivationFunction
{
return nodes[0].activation
}
func feedForward(_ x: [Double]) -> [Double]
{
// Gather the previous outputs for the feedback
var hPrev : [Double] = []
for node in nodes {
hPrev.append(node.getPreviousOutputValue())
}
var outputs : [Double] = []
// Assume input array already has bias constant 1.0 appended
// Fully-connected nodes means all nodes get the same input array
if (nodes[0].activation == .softMax) {
var sum = 0.0
for node in nodes { // Sum each output
sum += node.feedForward(x, hPrev: hPrev)
}
let scale = 1.0 / sum // Do division once for efficiency
for node in nodes { // Get the outputs scaled by the sum to give the probability distribuition for the output
node.h *= scale
outputs.append(node.h)
}
}
else {
for node in nodes {
outputs.append(node.feedForward(x, hPrev: hPrev))
}
}
return outputs
}
func getFinalLayer𝟃E𝟃zs(_ 𝟃E𝟃h: [Double])
{
for nNodeIndex in 0..<nodes.count {
// Start with the portion from the squared error term
nodes[nNodeIndex].getFinalNode𝟃E𝟃zs(𝟃E𝟃h[nNodeIndex])
}
}
func getLayer𝟃E𝟃zs(_ nextLayer: NeuralLayer)
{
// Get 𝟃E/𝟃h
for nNodeIndex in 0..<nodes.count {
nodes[nNodeIndex].reset𝟃E𝟃hs()
// Add each portion from the nodes in the next forward layer to get 𝟃Enow/𝟃h
nodes[nNodeIndex].addTo𝟃E𝟃hs(nextLayer.get𝟃E𝟃hForNodeInPreviousLayer(nNodeIndex))
// Add each portion from the nodes in this layer, using the feedback weights. This adds 𝟃Efuture/𝟃h
for node in nodes {
nodes[nNodeIndex].addTo𝟃E𝟃hs(node.getFeedbackWeightTimes𝟃E𝟃zs(nNodeIndex))
}
}
// Calculate 𝟃E/𝟃z from 𝟃E/𝟃h
for node in nodes {
node.get𝟃E𝟃z()
}
}
func get𝟃E𝟃hForNodeInPreviousLayer(_ inputIndex: Int) ->Double
{
var sum = 0.0
for node in nodes {
sum += node.getWeightTimes𝟃E𝟃zs(inputIndex)
}
return sum
}
func clearWeightChanges()
{
for node in nodes {
node.clearWeightChanges()
}
}
func appendWeightChanges(_ x: [Double]) -> [Double]
{
// Gather the previous outputs for the feedback
var hPrev : [Double] = []
for node in nodes {
hPrev.append(node.getPreviousOutputValue())
}
var outputs : [Double] = []
// Assume input array already has bias constant 1.0 appended
// Fully-connected nodes means all nodes get the same input array
for node in nodes {
outputs.append(node.appendWeightChanges(x, hPrev: hPrev))
}
return outputs
}
func updateWeightsFromAccumulations(_ averageTrainingRate: Double, weightDecay: Double)
{
// Have each node update it's weights from the accumulations
for node in nodes {
if (weightDecay < 1) { node.decayWeights(weightDecay) }
node.updateWeightsFromAccumulations(averageTrainingRate)
}
}
func decayWeights(_ decayFactor : Double)
{
for node in nodes {
node.decayWeights(decayFactor)
}
}
func getSingleNodeClassifyValue() -> Double
{
let activation = nodes[0].activation
if (activation == .hyperbolicTangent || activation == .rectifiedLinear) { return 0.0 }
return 0.5
}
func resetSequence()
{
// Have each node reset
for node in nodes {
node.resetSequence()
}
}
func storeRecurrentValues()
{
for node in nodes {
node.storeRecurrentValues()
}
}
func retrieveRecurrentValues(_ sequenceIndex: Int)
{
bpttSequenceIndex = sequenceIndex
// Set the last recurrent value in the history array to the last output
for node in nodes {
node.getLastRecurrentValue()
}
}
func gradientCheck(x: [Double], ε: Double, Δ: Double, network: NeuralNetwork) -> Bool
{
var result = true
for node in nodes {
if (!node.gradientCheck(x: x, ε: ε, Δ: Δ, network: network)) { result = false }
}
return result
}
}
/// Class for a recurrent network layer without individual nodes (faster, but some things hidden in the matrix math)
final class RecurrentNeuralLayer: NeuralLayer {
var activation : NeuralActivationFunction
var numInputs = 0
var numNodes : Int
var W : [Double] = [] // Weights for inputs from previous layer
var U : [Double] = [] // Weights for recurrent input data from this layer
var h : [Double] // Last result calculated
var outputHistory : [[Double]] // History of output for the sequence
var 𝟃E𝟃z : [Double] // Gradient in error with respect to weighted sum
var 𝟃E𝟃W : [Double] = [] // Accumulated weight W change gradient
var 𝟃E𝟃U : [Double] = [] // Accumulated weight U change gradient
var bpttSequenceIndex : Int
var rmspropDecay : Double? // Decay rate for rms prop weight updates. If nil, rmsprop is not used
/// Create the neural network layer based on a tuple (number of nodes, activation function)
init(numInputs : Int, layerDefinition: (layerType: NeuronLayerType, numNodes: Int, activation: NeuralActivationFunction, auxiliaryData: AnyObject?))
{
activation = layerDefinition.activation
self.numInputs = numInputs
self.numNodes = layerDefinition.numNodes
h = [Double](repeating: 0.0, count: numNodes)
outputHistory = []
𝟃E𝟃z = [Double](repeating: 0.0, count: numNodes)
bpttSequenceIndex = 0
}
// Initialize the weights
func initWeights(_ startWeights: [Double]!)
{
let numWeights = (numInputs + 1) * numNodes // Add bias offset
let numRcurrentWeights = numNodes * numNodes // Add bias offset
W = []
U = []
if let startWeights = startWeights {
if (startWeights.count >= numNodes * (numInputs + 1 + numNodes)) {
// If there are enough weights for all nodes, split the weights and initialize
W = Array(startWeights[0..<(numNodes * (numInputs + 1))])
U = Array(startWeights[(numNodes * (numInputs + 1))..<(numNodes * (numInputs + 1 + numNodes))])
}
else {
// If there are not enough weights for all nodes, initialize each weight set with the set given
var index = 0
for _ in 0..<((numInputs + 1) * numNodes) {
W.append(startWeights[index])
index += 1
if (index >= startWeights.count) { index = 0 }
}
for _ in 0..<(numNodes * numNodes) {
U.append(startWeights[index])
index += 1
if (index >= startWeights.count) { index = 0 }
}
}
}
else {
// No specified weights - just initialize normally
// Allocate the weight array using 'Xavier' initialization
var weightDiviser: Double
if (activation == .rectifiedLinear) {
weightDiviser = 1 / sqrt(Double(numInputs) * 0.5)
}
else {
weightDiviser = 1 / sqrt(Double(numInputs))
}
for _ in 0..<numWeights {
W.append(Gaussian.gaussianRandom(0.0, standardDeviation : 1.0) * weightDiviser)
}
if (activation == .rectifiedLinear) {
weightDiviser = 1 / sqrt(Double(numNodes) * 0.5)
}
else {
weightDiviser = 1 / sqrt(Double(numNodes))
}
for _ in 0..<numRcurrentWeights {
U.append(Gaussian.gaussianRandom(0.0, standardDeviation : 1.0) * weightDiviser)
}
}
}
func getWeights() -> [Double]
{
var weights = W
weights += U
return weights
}
func setRMSPropDecay(_ decay: Double?)
{
rmspropDecay = decay
}
func getLastOutput() -> [Double]
{
return h
}
func getNodeCount() -> Int
{
return numNodes
}
func getWeightsPerNode()-> Int
{
return numInputs + numNodes + 1
}
func getActivation()-> NeuralActivationFunction
{
return activation
}
func feedForward(_ x: [Double]) -> [Double]
{
// Gather the previous outputs for the feedback
var hPrev : [Double] = []
if let temp = outputHistory.last {
hPrev = temp
}
else {
hPrev = [Double](repeating: 0.0, count: numNodes)
}
var z = [Double](repeating: 0.0, count: numNodes)
var uz = [Double](repeating: 0.0, count: numNodes)
// Assume input array already has bias constant 1.0 appended
// Fully-connected nodes means all nodes get the same input array
vDSP_mmulD(W, 1, x, 1, &z, 1, vDSP_Length(numNodes), 1, vDSP_Length(numInputs+1))
vDSP_mmulD(U, 1, hPrev, 1, &uz, 1, vDSP_Length(numNodes), 1, vDSP_Length(numNodes))
vDSP_vaddD(z, 1, uz, 1, &z, 1, vDSP_Length(numNodes))
// Run through the non-linearity
var sum = 0.0
for node in 0..<numNodes {
switch (activation) {
case .none:
h[node] = z[node]
break
case .hyperbolicTangent:
h[node] = tanh(z[node])
break
case .sigmoidWithCrossEntropy:
h[node] = 1.0 / (1.0 + exp(-z[node]))
sum += h[node]
break
case .sigmoid:
h[node] = 1.0 / (1.0 + exp(-z[node]))
break
case .rectifiedLinear:
h[node] = z[node]
if (z[node] < 0) { h[node] = 0.0 }
break
case .softSign:
h[node] = z[node] / (1.0 + abs(z[node]))
break
case .softMax:
h[node] = exp(z[node])
break
}
}
if (activation == .softMax) {
var scale = 1.0 / sum // Do division once for efficiency
vDSP_vsmulD(h, 1, &scale, &h, 1, vDSP_Length(numNodes))
}
return h
}
func getFinalLayer𝟃E𝟃zs(_ 𝟃E𝟃h: [Double])
{
// Calculate 𝟃E/𝟃z from 𝟃E/𝟃h
switch (activation) {
case .none:
𝟃E𝟃z = 𝟃E𝟃h
break
case .hyperbolicTangent:
vDSP_vsqD(h, 1, &𝟃E𝟃z, 1, vDSP_Length(numNodes)) // h²
let ones = [Double](repeating: 1.0, count: numNodes)
vDSP_vsubD(𝟃E𝟃z, 1, ones, 1, &𝟃E𝟃z, 1, vDSP_Length(numNodes)) // 1 - h²
vDSP_vmulD(𝟃E𝟃z, 1, 𝟃E𝟃h, 1, &𝟃E𝟃z, 1, vDSP_Length(numNodes)) // 𝟃E𝟃h * (1 - h²)
break
case .sigmoidWithCrossEntropy:
fallthrough
case .sigmoid:
vDSP_vsqD(h, 1, &𝟃E𝟃z, 1, vDSP_Length(numNodes)) // h²
vDSP_vsubD(𝟃E𝟃z, 1, h, 1, &𝟃E𝟃z, 1, vDSP_Length(numNodes)) // h - h²
vDSP_vmulD(𝟃E𝟃z, 1, 𝟃E𝟃h, 1, &𝟃E𝟃z, 1, vDSP_Length(numNodes)) // 𝟃E𝟃h * (h - h²)
break
case .rectifiedLinear:
for i in 0..<numNodes {
𝟃E𝟃z[i] = h[i] <= 0.0 ? 0.0 : 𝟃E𝟃h[i]
}
break
case .softSign:
for i in 0..<numNodes {
// Reconstitute z from h
var z : Double
//!! - this might be able to be sped up with vector operations
if (h[i] < 0) { // Negative z
z = h[i] / (1.0 + h[i])
𝟃E𝟃z[i] = -𝟃E𝟃h[i] / ((1.0 + z) * (1.0 + z))
}
else { // Positive z
z = h[i] / (1.0 - h[i])
𝟃E𝟃z[i] = 𝟃E𝟃h[i] / ((1.0 + z) * (1.0 + z))
}
}
break
case .softMax:
// This should be done outside of the layer
break
}
}
func getLayer𝟃E𝟃zs(_ nextLayer: NeuralLayer)
{
// Get 𝟃E/𝟃h from the next layer
var 𝟃E𝟃h = [Double](repeating: 0.0, count: numNodes)
for node in 0..<numNodes {
𝟃E𝟃h[node] = nextLayer.get𝟃E𝟃hForNodeInPreviousLayer(node)
}
// Calculate 𝟃E/𝟃z from 𝟃E/𝟃h
getFinalLayer𝟃E𝟃zs(𝟃E𝟃h)
}
func get𝟃E𝟃hForNodeInPreviousLayer(_ inputIndex: Int) ->Double
{
var sum = 0.0
var offset = inputIndex
for node in 0..<numNodes {
sum += 𝟃E𝟃z[node] * W[offset]
offset += numInputs+1
}
return sum
}
func clearWeightChanges()
{
𝟃E𝟃W = [Double](repeating: 0.0, count: W.count)
𝟃E𝟃U = [Double](repeating: 0.0, count: U.count)
}
func appendWeightChanges(_ x: [Double]) -> [Double]
{
// Gather the previous outputs for the feedback
var hPrev : [Double] = []
if let temp = outputHistory.last {
hPrev = temp
}
else {
hPrev = [Double](repeating: 0.0, count: numNodes)
}
// Assume input array already has bias constant 1.0 appended
// Update each weight accumulation
var weightWChange = [Double](repeating: 0.0, count: W.count)
vDSP_mmulD(𝟃E𝟃z, 1, x, 1, &weightWChange, 1, vDSP_Length(numNodes), vDSP_Length(numInputs+1), 1)
vDSP_vaddD(weightWChange, 1, 𝟃E𝟃W, 1, &𝟃E𝟃W, 1, vDSP_Length(W.count))
var weightUChange = [Double](repeating: 0.0, count: U.count)
vDSP_mmulD(𝟃E𝟃z, 1, hPrev, 1, &weightUChange, 1, vDSP_Length(numNodes), vDSP_Length(numNodes), 1)
vDSP_vaddD(weightUChange, 1, 𝟃E𝟃U, 1, &𝟃E𝟃U, 1, vDSP_Length(U.count))
return h
}
func updateWeightsFromAccumulations(_ averageTrainingRate: Double, weightDecay: Double)
{
// Update the weights from the accumulations
if (weightDecay < 1) { decayWeights(weightDecay) }
var trainRate = -averageTrainingRate
vDSP_vsmaD(𝟃E𝟃W, 1, &trainRate, W, 1, &W, 1, vDSP_Length(W.count))
vDSP_vsmaD(𝟃E𝟃U, 1, &trainRate, U, 1, &U, 1, vDSP_Length(U.count))
}
func decayWeights(_ decayFactor : Double)
{
var decay = decayFactor
vDSP_vsmulD(W, 1, &decay, &W, 1, vDSP_Length(W.count))
vDSP_vsmulD(U, 1, &decay, &U, 1, vDSP_Length(U.count))
}
func getSingleNodeClassifyValue() -> Double
{
if (activation == .hyperbolicTangent || activation == .rectifiedLinear) { return 0.0 }
return 0.5
}
func resetSequence()
{
// Have each node reset
h = [Double](repeating: 0.0, count: numNodes)
outputHistory = [[Double](repeating: 0.0, count: numNodes)] // first 'previous' value is zero
𝟃E𝟃z = [Double](repeating: 0.0, count: numNodes) // Backward propogation previous 𝟃E𝟃z (𝟃E𝟃z from next time step in sequence) is zero
}
func storeRecurrentValues()
{
outputHistory.append(h)
}
func retrieveRecurrentValues(_ sequenceIndex: Int)
{
bpttSequenceIndex = sequenceIndex
// Set the last recurrent value in the history array to the last output
h = outputHistory.removeLast()
}
func gradientCheck(x: [Double], ε: Double, Δ: Double, network: NeuralNetwork) -> Bool
{
var result = true
// Iterate through each W parameter
for index in 0..<W.count {
let oldValue = W[index]
// Get the network loss with a small addition to the parameter
W[index] += ε
_ = network.feedForward(x)
var plusLoss : [Double]
do {
plusLoss = try network.getResultLoss()
}
catch {
return false
}
// Get the network loss with a small subtraction from the parameter
W[index] = oldValue - ε
_ = network.feedForward(x)
var minusLoss : [Double]
do {
minusLoss = try network.getResultLoss()
}
catch {
return false
}
W[index] = oldValue
// Iterate over the results
for resultIndex in 0..<plusLoss.count {
// Get the numerical gradient estimate 𝟃E/𝟃W
let gradient = (plusLoss[resultIndex] - minusLoss[resultIndex]) / (2.0 * ε)
// Compare with the analytical gradient
let difference = abs(gradient - 𝟃E𝟃W[index])
// print("difference = \(difference)")
if (difference > Δ) {
result = false
}
}
}
// Iterate through each U parameter
for index in 0..<U.count {
let oldValue = U[index]
// Get the network loss with a small addition to the parameter
U[index] += ε
_ = network.feedForward(x)
var plusLoss : [Double]
do {
plusLoss = try network.getResultLoss()
}
catch {
return false
}
// Get the network loss with a small subtraction from the parameter
U[index] = oldValue - ε
_ = network.feedForward(x)
var minusLoss : [Double]
do {
minusLoss = try network.getResultLoss()
}
catch {
return false
}
U[index] = oldValue
// Iterate over the results
for resultIndex in 0..<plusLoss.count {
// Get the numerical gradient estimate 𝟃E/𝟃U
let gradient = (plusLoss[resultIndex] - minusLoss[resultIndex]) / (2.0 * ε)
// Compare with the analytical gradient
let difference = abs(gradient - 𝟃E𝟃U[index])
// print("difference = \(difference)")
if (difference > Δ) {
result = false
}
}
}
return result
}
}
| apache-2.0 | 5f45c26ae3f892337cdbab7190778b1d | 33.027451 | 219 | 0.501729 | 4.324446 | false | false | false | false |
Gitliming/Demoes | Demoes/Demoes/Address Book/AddressController.swift | 1 | 1179 | //
// loginController.swift
// Dispersive switch
//
// Created by xpming on 16/7/7.
// Copyright © 2016年 xpming. All rights reserved.
//
import UIKit
class AddressController: BaseViewController {
var loginBtn:UIButton?
override func viewDidLoad() {
super.viewDidLoad()
prepareUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func prepareUI() {
view.layer.contents = UIImage(named: "address_2")?.cgImage
title = "进入通讯录"
loginBtn = UIButton()
loginBtn?.center = view.center
loginBtn?.bounds.size = CGSize(width: 338, height: 95)
loginBtn?.setTitle("获取通讯录", for: UIControlState())
loginBtn?.setTitleColor(UIColor.green, for: UIControlState())
loginBtn?.setBackgroundImage(UIImage(named: "loginBtn"), for: UIControlState())
loginBtn?.addTarget(self, action: #selector(AddressController.login), for: .touchUpInside)
view.addSubview(loginBtn!)
}
func login() {
print("login")
}
}
| apache-2.0 | 96f3d56fa20511eebec0e91dad0758d3 | 25.883721 | 98 | 0.628028 | 4.551181 | false | false | false | false |
lorentey/swift | test/Parse/dollar_identifier.swift | 9 | 2620 | // RUN: %target-typecheck-verify-swift -swift-version 4
// SR-1661: Dollar was accidentally allowed as an identifier in Swift 3.
// SE-0144: Reject this behavior in the future.
func dollarVar() {
var $ : Int = 42 // expected-error {{'$' is not an identifier; use backticks to escape it}} {{7-8=`$`}}
$ += 1 // expected-error {{'$' is not an identifier; use backticks to escape it}} {{3-4=`$`}}
print($) // expected-error {{'$' is not an identifier; use backticks to escape it}} {{9-10=`$`}}
}
func dollarLet() {
let $ = 42 // expected-error {{'$' is not an identifier; use backticks to escape it}} {{7-8=`$`}}
print($) // expected-error {{'$' is not an identifier; use backticks to escape it}} {{9-10=`$`}}
}
func dollarClass() {
class $ {} // expected-error {{'$' is not an identifier; use backticks to escape it}} {{9-10=`$`}}
}
func dollarEnum() {
enum $ {} // expected-error {{'$' is not an identifier; use backticks to escape it}} {{8-9=`$`}}
}
func dollarStruct() {
struct $ {} // expected-error {{'$' is not an identifier; use backticks to escape it}} {{10-11=`$`}}
}
func dollarFunc() {
func $($ dollarParam: Int) {}
// expected-error@-1 {{'$' is not an identifier; use backticks to escape it}} {{8-9=`$`}}
// expected-error@-2 {{'$' is not an identifier; use backticks to escape it}} {{10-11=`$`}}
$($: 24)
// expected-error@-1 {{'$' is not an identifier; use backticks to escape it}} {{3-4=`$`}}
// expected-error@-2 {{'$' is not an identifier; use backticks to escape it}} {{5-6=`$`}}
}
func escapedDollarVar() {
var `$` : Int = 42 // no error
`$` += 1
print(`$`)
}
func escapedDollarLet() {
let `$` = 42 // no error
print(`$`)
}
func escapedDollarClass() {
class `$` {} // no error
}
func escapedDollarEnum() {
enum `$` {} // no error
}
func escapedDollarStruct() {
struct `$` {} // no error
}
func escapedDollarFunc() {
func `$`(`$`: Int) {} // no error
`$`(`$`: 25) // no error
}
func escapedDollarAnd() {
// FIXME: Bad diagnostics.
`$0` = 1 // expected-error {{expected expression}}
`$$` = 2
`$abc` = 3
}
func $declareWithDollar() { // expected-error{{cannot declare entity named '$declareWithDollar'}}
var $foo = 17 // expected-error{{cannot declare entity named '$foo'}}
// expected-warning@-1 {{initialization of variable '$foo' was never used; consider replacing with assignment to '_' or removing it}}
func $bar() { } // expected-error{{cannot declare entity named '$bar'}}
func wibble(
$a: Int, // expected-error{{cannot declare entity named '$a'}}
$b c: Int) { } // expected-error{{cannot declare entity named '$b'}}
}
| apache-2.0 | 4b0802c0ac04c90867b5ef767870d786 | 35.388889 | 135 | 0.61145 | 3.674614 | false | false | false | false |
azfx/Sapporo | Example/Example/DynamicSize/DynamicSizeViewController.swift | 1 | 1454 | //
// DynamicSizeViewController.swift
// Example
//
// Created by Le VanNghia on 7/9/15.
// Copyright (c) 2015 Le Van Nghia. All rights reserved.
//
import UIKit
import Sapporo
var longDes = "Swift is a new programming language for iOS and OS X apps that builds on the best of C and Objective-C, without the constraints of C compatibility. Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible, and more fun. Swift’s clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to reimagine how software development works."
class DynamicSizeViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
lazy var sapporo: Sapporo = { [unowned self] in
return Sapporo(collectionView: self.collectionView)
}()
override func viewDidLoad() {
super.viewDidLoad()
sapporo.registerNibForClass(DynamicSizeCell)
sapporo.registerNibForClass(DynamicImageSizeCell)
let layout = SAFlowLayout()
sapporo.setLayout(layout)
let section = sapporo[0]
//sapporo.bump()
let title = " title "
let des = " description "
//let cellmodel = DynamicImageSizeCellModel(title: title)
let cellmodel = DynamicSizeCellModel(title: title, des: longDes)
section.append(cellmodel)
sapporo.bump()
delay(3) {
cellmodel.des = des
cellmodel.bump()
}
}
deinit {
collectionView.delegate = nil
}
} | mit | 1675016e388974cd9ff73a583ab37b26 | 28.06 | 438 | 0.741047 | 3.882353 | false | false | false | false |
dflax/amazeballs | Legacy Versions/Swift 2.x Version/AmazeBalls/BallScene.swift | 1 | 7084 | //
// BallScene.swift
// AmazeBalls
//
// Created by Daniel Flax on 5/18/15.
// Copyright (c) 2015 Daniel Flax. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import UIKit
import SpriteKit
import CoreMotion
class BallScene: SKScene, SKPhysicsContactDelegate {
var contentCreated : Bool!
var currentGravity : Float!
var activeBall : Int!
var bouncyness : Float!
var boundingWall : Bool!
var accelerometerSetting: Bool!
let motionManager: CMMotionManager = CMMotionManager()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder) is not used in this app")
}
override init(size: CGSize) {
super.init(size: size)
}
override func didMoveToView(view: SKView) {
// Set the overall physicsWorld and outer wall characteristics
physicsWorld.contactDelegate = self
physicsBody?.categoryBitMask = CollisionCategories.EdgeBody
// Load the brickwall background
let wallTexture = SKTexture(imageNamed: "brickwall")
let wallSprite = SKSpriteNode(texture: wallTexture)
wallSprite.size = ScreenSize
wallSprite.position = ScreenCenter
wallSprite.zPosition = -10
self.addChild(wallSprite)
// Load the floor for the bottom of the scene
let floor = Floor()
floor.zPosition = 100
self.addChild(floor)
updateWorldPhysicsSettings()
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
// Go though all touch points in the set
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
// If it's not already a ball, drop a new ball at that location
self.addChild(Ball(location: location, ballType: activeBall, bouncyness: CGFloat(bouncyness)))
if touch.tapCount == 2 {
self.stopBalls()
}
}
}
//MARK: - Detect Collisions and Handle
// SKPhysicsContactDelegate - to handle collisions between objects
func didBeginContact(contact: SKPhysicsContact) {
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
// Check if the collision is between Ball and Floor
if ((firstBody.categoryBitMask & CollisionCategories.Ball != 0) && (secondBody.categoryBitMask & CollisionCategories.Floor != 0)) {
// Ball and Floor collided
// println("Ball and Floor collided")
}
// Checck if the collision is between Ball and Floor
if ((firstBody.categoryBitMask & CollisionCategories.Ball != 0) && (secondBody.categoryBitMask & CollisionCategories.EdgeBody != 0)) {
// println("Ball and wall collide")
}
}
// Stop all balls from moving
func stopBalls() {
self.enumerateChildNodesWithName("ball") {
node, stop in
node.speed = 0
}
}
// Use to remove any balls that have fallen off the screen
override func update(currentTime: CFTimeInterval) {
}
// Loop through all ballNodes, and execute the passed in block if they've falled more than 500 points below the screen, they aren't coming back.
override func didSimulatePhysics() {
self.enumerateChildNodesWithName("ball") {
node, stop in
if node.position.y < -500 {
node.removeFromParent()
}
}
}
//MARK: - Settings for the Physics World
// This is the main method to update the physics for the scene based on the settings the user has entered on the Settings View.
func updateWorldPhysicsSettings() {
// Grab the standard user defaults handle
let userDefaults = NSUserDefaults.standardUserDefaults()
// Pull values for the different settings. Substitute in defaults if the NSUserDefaults doesn't include any value
currentGravity = userDefaults.valueForKey("gravityValue") != nil ? -1*abs(userDefaults.valueForKey("gravityValue") as! Float) : -9.8
activeBall = userDefaults.valueForKey("activeBall") != nil ? userDefaults.valueForKey("activeBall") as! Int : 2000
bouncyness = userDefaults.valueForKey("bouncyness") != nil ? userDefaults.valueForKey("bouncyness") as! Float : 0.5
boundingWall = userDefaults.valueForKey("boundingWallSetting") != nil ? userDefaults.valueForKey("boundingWallSetting") as! Bool : false
accelerometerSetting = userDefaults.valueForKey("accelerometerSetting") != nil ? userDefaults.valueForKey("accelerometerSetting") as! Bool : false
// If no Accelerometer, set the simple gravity for the world
if (!accelerometerSetting) {
physicsWorld.gravity = CGVector(dx: 0.0, dy: CGFloat(currentGravity))
// In case it's on, turn off the accelerometer
motionManager.stopAccelerometerUpdates()
} else {
// Turn on the accelerometer to handle setting the gravityself
startComplexGravity()
}
// Loop through all balls and update their bouncyness values
self.enumerateChildNodesWithName("ball") {
node, stop in
node.physicsBody?.restitution = CGFloat(self.bouncyness)
}
// Set whether there is a bounding wall (edge loop) around the frame
if boundingWall == true {
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: ScreenRect)
} else {
self.physicsBody = nil
}
}
//MARK: - Accelerate Framework Methods
// If the user selects to have the accelerometer active, complex gravity must be calculated whenever the Core Motion delegate is called
func startComplexGravity() {
// Check if the accelerometer is available
if (motionManager.accelerometerAvailable) {
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue()) {
(data, error) in
// Take the x and y acceleration vectors and multiply by the gravity values to come up with a full gravity vector
let xGravity = CGFloat(data.acceleration.x) * CGFloat(self.currentGravity)
let yGravity = CGFloat(data.acceleration.y) * CGFloat(self.currentGravity)
self.physicsWorld.gravity = CGVector(dx: yGravity, dy: -xGravity)
}
}
}
}
| mit | fb8627b29b8ca71459adfee825eb8bfd | 34.59799 | 150 | 0.725438 | 4.24955 | false | false | false | false |
Takanu/Pelican | Sources/Pelican/API/Types/User/User.swift | 1 | 2000 | //
// User.swift
// Pelican
//
// Created by Takanu Kyriako on 31/08/2017.
//
import Foundation
/**
Represents a Telegram user or bot.
*/
public struct User: Codable {
public let messageTypeName = "user"
/// Unique identifier for the user or bot.
public var tgID: String
/// If true, this user is a bot.
public var isBot: Bool
/// User's or bot's first name.
public var firstName: String
/// User's or bot's last name.
public var lastName: String?
/// User's or bot's username.
public var username: String?
/// IETF language tag of the user's language.
public var languageCode: String?
enum CodingKeys: String, CodingKey {
case tgID = "id"
case isBot = "is_bot"
case firstName = "first_name"
case lastName = "last_name"
case username = "username"
case languageCode = "language_code"
}
public init(id: String, isBot: Bool, firstName: String) {
self.tgID = id
self.isBot = isBot
self.firstName = firstName
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
tgID = try String(values.decode(Int.self, forKey: .tgID))
isBot = try values.decodeIfPresent(Bool.self, forKey: .isBot) ?? false
firstName = try values.decode(String.self, forKey: .firstName)
lastName = try values.decodeIfPresent(String.self, forKey: .lastName)
username = try values.decodeIfPresent(String.self, forKey: .username)
languageCode = try values.decodeIfPresent(String.self, forKey: .languageCode)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
let intID = Int(tgID)
try container.encode(intID, forKey: .tgID)
try container.encodeIfPresent(isBot, forKey: .isBot)
try container.encode(firstName, forKey: .firstName)
try container.encodeIfPresent(lastName, forKey: .lastName)
try container.encodeIfPresent(username, forKey: .username)
try container.encodeIfPresent(languageCode, forKey: .languageCode)
}
}
| mit | 87a34966d3e4eb4b18a30881c89b5f01 | 25.315789 | 79 | 0.714 | 3.539823 | false | false | false | false |
WhisperSystems/Signal-iOS | Signal/src/views/LinkPreviewView.swift | 1 | 28313 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
public extension CGPoint {
func offsetBy(dx: CGFloat) -> CGPoint {
return CGPoint(x: x + dx, y: y)
}
func offsetBy(dy: CGFloat) -> CGPoint {
return CGPoint(x: x, y: y + dy)
}
}
// MARK: -
@objc
public enum LinkPreviewImageState: Int {
case none
case loading
case loaded
case invalid
}
// MARK: -
@objc
public protocol LinkPreviewState {
func isLoaded() -> Bool
func urlString() -> String?
func displayDomain() -> String?
func title() -> String?
func imageState() -> LinkPreviewImageState
func image() -> UIImage?
}
// MARK: -
@objc
public class LinkPreviewLoading: NSObject, LinkPreviewState {
override init() {
}
public func isLoaded() -> Bool {
return false
}
public func urlString() -> String? {
return nil
}
public func displayDomain() -> String? {
return nil
}
public func title() -> String? {
return nil
}
public func imageState() -> LinkPreviewImageState {
return .none
}
public func image() -> UIImage? {
return nil
}
}
// MARK: -
@objc
public class LinkPreviewDraft: NSObject, LinkPreviewState {
private let linkPreviewDraft: OWSLinkPreviewDraft
@objc
public required init(linkPreviewDraft: OWSLinkPreviewDraft) {
self.linkPreviewDraft = linkPreviewDraft
}
public func isLoaded() -> Bool {
return true
}
public func urlString() -> String? {
return linkPreviewDraft.urlString
}
public func displayDomain() -> String? {
guard let displayDomain = linkPreviewDraft.displayDomain() else {
owsFailDebug("Missing display domain")
return nil
}
return displayDomain
}
public func title() -> String? {
guard let value = linkPreviewDraft.title,
value.count > 0 else {
return nil
}
return value
}
public func imageState() -> LinkPreviewImageState {
if linkPreviewDraft.imageData != nil {
return .loaded
} else {
return .none
}
}
public func image() -> UIImage? {
assert(imageState() == .loaded)
guard let imageData = linkPreviewDraft.imageData else {
return nil
}
guard let image = UIImage(data: imageData) else {
owsFailDebug("Could not load image: \(imageData.count)")
return nil
}
return image
}
}
// MARK: -
@objc
public class LinkPreviewSent: NSObject, LinkPreviewState {
private let linkPreview: OWSLinkPreview
private let imageAttachment: TSAttachment?
@objc public let conversationStyle: ConversationStyle
@objc
public var imageSize: CGSize {
guard let attachmentStream = imageAttachment as? TSAttachmentStream else {
return CGSize.zero
}
return attachmentStream.imageSize()
}
@objc
public required init(linkPreview: OWSLinkPreview,
imageAttachment: TSAttachment?,
conversationStyle: ConversationStyle) {
self.linkPreview = linkPreview
self.imageAttachment = imageAttachment
self.conversationStyle = conversationStyle
}
public func isLoaded() -> Bool {
return true
}
public func urlString() -> String? {
guard let urlString = linkPreview.urlString else {
owsFailDebug("Missing url")
return nil
}
return urlString
}
public func displayDomain() -> String? {
guard let displayDomain = linkPreview.displayDomain() else {
Logger.error("Missing display domain")
return nil
}
return displayDomain
}
public func title() -> String? {
guard let value = linkPreview.title,
value.count > 0 else {
return nil
}
return value
}
public func imageState() -> LinkPreviewImageState {
guard linkPreview.imageAttachmentId != nil else {
return .none
}
guard let imageAttachment = imageAttachment else {
owsFailDebug("Missing imageAttachment.")
return .none
}
guard let attachmentStream = imageAttachment as? TSAttachmentStream else {
return .loading
}
guard attachmentStream.isImage,
attachmentStream.isValidImage else {
return .invalid
}
return .loaded
}
public func image() -> UIImage? {
assert(imageState() == .loaded)
guard let attachmentStream = imageAttachment as? TSAttachmentStream else {
owsFailDebug("Could not load image.")
return nil
}
guard attachmentStream.isImage,
attachmentStream.isValidImage else {
return nil
}
guard let imageFilepath = attachmentStream.originalFilePath else {
owsFailDebug("Attachment is missing file path.")
return nil
}
guard NSData.ows_isValidImage(atPath: imageFilepath, mimeType: attachmentStream.contentType) else {
owsFailDebug("Invalid image.")
return nil
}
let imageClass: UIImage.Type
if attachmentStream.contentType == OWSMimeTypeImageWebp {
imageClass = YYImage.self
} else {
imageClass = UIImage.self
}
guard let image = imageClass.init(contentsOfFile: imageFilepath) else {
owsFailDebug("Could not load image: \(imageFilepath)")
return nil
}
return image
}
}
// MARK: -
@objc
public protocol LinkPreviewViewDraftDelegate {
func linkPreviewCanCancel() -> Bool
func linkPreviewDidCancel()
}
// MARK: -
@objc
public class LinkPreviewImageView: UIImageView {
private let maskLayer = CAShapeLayer()
private let hasAsymmetricalRounding: Bool
@objc
public init(hasAsymmetricalRounding: Bool) {
self.hasAsymmetricalRounding = hasAsymmetricalRounding
super.init(frame: .zero)
self.layer.mask = maskLayer
}
public required init?(coder aDecoder: NSCoder) {
self.hasAsymmetricalRounding = false
super.init(coder: aDecoder)
}
public override var bounds: CGRect {
didSet {
updateMaskLayer()
}
}
public override var frame: CGRect {
didSet {
updateMaskLayer()
}
}
public override var center: CGPoint {
didSet {
updateMaskLayer()
}
}
private func updateMaskLayer() {
let layerBounds = self.bounds
// One of the corners has assymetrical rounding to match the input toolbar border.
// This is somewhat inconvenient.
let upperLeft = CGPoint(x: 0, y: 0)
let upperRight = CGPoint(x: layerBounds.size.width, y: 0)
let lowerRight = CGPoint(x: layerBounds.size.width, y: layerBounds.size.height)
let lowerLeft = CGPoint(x: 0, y: layerBounds.size.height)
let bigRounding: CGFloat = 14
let smallRounding: CGFloat = 4
let upperLeftRounding: CGFloat
let upperRightRounding: CGFloat
if hasAsymmetricalRounding {
upperLeftRounding = CurrentAppContext().isRTL ? smallRounding : bigRounding
upperRightRounding = CurrentAppContext().isRTL ? bigRounding : smallRounding
} else {
upperLeftRounding = smallRounding
upperRightRounding = smallRounding
}
let lowerRightRounding = smallRounding
let lowerLeftRounding = smallRounding
let path = UIBezierPath()
// It's sufficient to "draw" the rounded corners and not the edges that connect them.
path.addArc(withCenter: upperLeft.offsetBy(dx: +upperLeftRounding).offsetBy(dy: +upperLeftRounding),
radius: upperLeftRounding,
startAngle: CGFloat.pi * 1.0,
endAngle: CGFloat.pi * 1.5,
clockwise: true)
path.addArc(withCenter: upperRight.offsetBy(dx: -upperRightRounding).offsetBy(dy: +upperRightRounding),
radius: upperRightRounding,
startAngle: CGFloat.pi * 1.5,
endAngle: CGFloat.pi * 0.0,
clockwise: true)
path.addArc(withCenter: lowerRight.offsetBy(dx: -lowerRightRounding).offsetBy(dy: -lowerRightRounding),
radius: lowerRightRounding,
startAngle: CGFloat.pi * 0.0,
endAngle: CGFloat.pi * 0.5,
clockwise: true)
path.addArc(withCenter: lowerLeft.offsetBy(dx: +lowerLeftRounding).offsetBy(dy: -lowerLeftRounding),
radius: lowerLeftRounding,
startAngle: CGFloat.pi * 0.5,
endAngle: CGFloat.pi * 1.0,
clockwise: true)
maskLayer.path = path.cgPath
}
}
// MARK: -
@objc
public class LinkPreviewView: UIStackView {
private weak var draftDelegate: LinkPreviewViewDraftDelegate?
@objc
public var state: LinkPreviewState? {
didSet {
AssertIsOnMainThread()
assert(state == nil || oldValue == nil)
updateContents()
}
}
@objc
public var hasAsymmetricalRounding: Bool = false {
didSet {
AssertIsOnMainThread()
if hasAsymmetricalRounding != oldValue {
updateContents()
}
}
}
@available(*, unavailable, message:"use other constructor instead.")
required init(coder aDecoder: NSCoder) {
notImplemented()
}
@available(*, unavailable, message:"use other constructor instead.")
override init(frame: CGRect) {
notImplemented()
}
private var cancelButton: UIButton?
private weak var heroImageView: UIView?
private weak var sentBodyView: UIView?
private var layoutConstraints = [NSLayoutConstraint]()
@objc
public init(draftDelegate: LinkPreviewViewDraftDelegate?) {
self.draftDelegate = draftDelegate
super.init(frame: .zero)
if let draftDelegate = draftDelegate,
draftDelegate.linkPreviewCanCancel() {
self.isUserInteractionEnabled = true
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(wasTapped)))
}
}
private var isDraft: Bool {
return draftDelegate != nil
}
private func resetContents() {
for subview in subviews {
subview.removeFromSuperview()
}
self.axis = .horizontal
self.alignment = .center
self.distribution = .fill
self.spacing = 0
self.isLayoutMarginsRelativeArrangement = false
self.layoutMargins = .zero
cancelButton = nil
heroImageView = nil
sentBodyView = nil
NSLayoutConstraint.deactivate(layoutConstraints)
layoutConstraints = []
}
private func updateContents() {
resetContents()
guard let state = state else {
return
}
guard isDraft else {
createSentContents()
return
}
guard state.isLoaded() else {
createDraftLoadingContents()
return
}
createDraftContents(state: state)
}
private func createSentContents() {
guard let state = state as? LinkPreviewSent else {
owsFailDebug("Invalid state")
return
}
self.addBackgroundView(withBackgroundColor: Theme.backgroundColor)
if let imageView = createImageView(state: state) {
if sentIsHero(state: state) {
createHeroSentContents(state: state,
imageView: imageView)
} else {
createNonHeroSentContents(state: state,
imageView: imageView)
}
} else {
createNonHeroSentContents(state: state,
imageView: nil)
}
}
private func sentHeroImageSize(state: LinkPreviewSent) -> CGSize {
let maxMessageWidth = state.conversationStyle.maxMessageWidth
let imageSize = state.imageSize
let minImageHeight: CGFloat = maxMessageWidth * 0.5
let maxImageHeight: CGFloat = maxMessageWidth
let rawImageHeight = maxMessageWidth * imageSize.height / imageSize.width
let imageHeight: CGFloat = min(maxImageHeight, max(minImageHeight, rawImageHeight))
return CGSizeCeil(CGSize(width: maxMessageWidth, height: imageHeight))
}
private func createHeroSentContents(state: LinkPreviewSent,
imageView: UIImageView) {
self.layoutMargins = .zero
self.axis = .vertical
self.alignment = .fill
let heroImageSize = sentHeroImageSize(state: state)
imageView.autoSetDimensions(to: heroImageSize)
imageView.contentMode = .scaleAspectFill
imageView.setContentHuggingHigh()
imageView.setCompressionResistanceHigh()
imageView.clipsToBounds = true
// TODO: Cropping, stroke.
addArrangedSubview(imageView)
let textStack = createSentTextStack(state: state)
textStack.isLayoutMarginsRelativeArrangement = true
textStack.layoutMargins = UIEdgeInsets(top: sentHeroVMargin, left: sentHeroHMargin, bottom: sentHeroVMargin, right: sentHeroHMargin)
addArrangedSubview(textStack)
heroImageView = imageView
sentBodyView = textStack
}
private func createNonHeroSentContents(state: LinkPreviewSent,
imageView: UIImageView?) {
self.layoutMargins = .zero
self.axis = .horizontal
self.isLayoutMarginsRelativeArrangement = true
self.layoutMargins = UIEdgeInsets(top: sentNonHeroVMargin, left: sentNonHeroHMargin, bottom: sentNonHeroVMargin, right: sentNonHeroHMargin)
self.spacing = sentNonHeroHSpacing
if let imageView = imageView {
imageView.autoSetDimensions(to: CGSize(width: sentNonHeroImageSize, height: sentNonHeroImageSize))
imageView.contentMode = .scaleAspectFill
imageView.setContentHuggingHigh()
imageView.setCompressionResistanceHigh()
imageView.clipsToBounds = true
// TODO: Cropping, stroke.
addArrangedSubview(imageView)
}
let textStack = createSentTextStack(state: state)
addArrangedSubview(textStack)
sentBodyView = self
}
private func createSentTextStack(state: LinkPreviewSent) -> UIStackView {
let textStack = UIStackView()
textStack.axis = .vertical
textStack.spacing = sentVSpacing
if let titleLabel = sentTitleLabel(state: state) {
textStack.addArrangedSubview(titleLabel)
}
let domainLabel = sentDomainLabel(state: state)
textStack.addArrangedSubview(domainLabel)
return textStack
}
private let sentMinimumHeroSize: CGFloat = 200
private let sentTitleFontSizePoints: CGFloat = 17
private let sentDomainFontSizePoints: CGFloat = 12
private let sentVSpacing: CGFloat = 4
// The "sent message" mode has two submodes: "hero" and "non-hero".
private let sentNonHeroHMargin: CGFloat = 6
private let sentNonHeroVMargin: CGFloat = 6
private let sentNonHeroImageSize: CGFloat = 72
private let sentNonHeroHSpacing: CGFloat = 8
private let sentHeroHMargin: CGFloat = 12
private let sentHeroVMargin: CGFloat = 7
private func sentIsHero(state: LinkPreviewSent) -> Bool {
if isSticker(state: state) {
return false
}
let imageSize = state.imageSize
return imageSize.width >= sentMinimumHeroSize && imageSize.height >= sentMinimumHeroSize
}
private func isSticker(state: LinkPreviewSent) -> Bool {
guard let urlString = state.urlString() else {
owsFailDebug("Link preview is missing url.")
return false
}
guard let url = URL(string: urlString) else {
owsFailDebug("Could not parse URL.")
return false
}
return StickerPackInfo.isStickerPackShare(url)
}
private let sentTitleLineCount: Int = 2
private func sentTitleLabel(state: LinkPreviewState) -> UILabel? {
guard let text = state.title() else {
return nil
}
let label = UILabel()
label.text = text
label.font = UIFont.systemFont(ofSize: sentTitleFontSizePoints).ows_mediumWeight()
label.textColor = Theme.primaryColor
label.numberOfLines = sentTitleLineCount
label.lineBreakMode = .byWordWrapping
return label
}
private func sentDomainLabel(state: LinkPreviewState) -> UILabel {
let label = UILabel()
if let displayDomain = state.displayDomain(),
displayDomain.count > 0 {
label.text = displayDomain.uppercased()
} else {
label.text = NSLocalizedString("LINK_PREVIEW_UNKNOWN_DOMAIN", comment: "Label for link previews with an unknown host.").uppercased()
}
label.font = UIFont.systemFont(ofSize: sentDomainFontSizePoints)
label.textColor = Theme.secondaryColor
return label
}
private let draftHeight: CGFloat = 72
private let draftMarginTop: CGFloat = 6
private func createDraftContents(state: LinkPreviewState) {
self.axis = .horizontal
self.alignment = .fill
self.distribution = .fill
self.spacing = 8
self.isLayoutMarginsRelativeArrangement = true
self.layoutConstraints.append(self.autoSetDimension(.height, toSize: draftHeight + draftMarginTop))
// Image
let draftImageView = createDraftImageView(state: state)
if let imageView = draftImageView {
imageView.contentMode = .scaleAspectFill
imageView.autoPinToSquareAspectRatio()
let imageSize = draftHeight
imageView.autoSetDimensions(to: CGSize(width: imageSize, height: imageSize))
imageView.setContentHuggingHigh()
imageView.setCompressionResistanceHigh()
imageView.clipsToBounds = true
addArrangedSubview(imageView)
}
let hasImage = draftImageView != nil
let hMarginLeading: CGFloat = hasImage ? 6 : 12
let hMarginTrailing: CGFloat = 12
self.layoutMargins = UIEdgeInsets(top: draftMarginTop,
leading: hMarginLeading,
bottom: 0,
trailing: hMarginTrailing)
// Right
let rightStack = UIStackView()
rightStack.axis = .horizontal
rightStack.alignment = .fill
rightStack.distribution = .equalSpacing
rightStack.spacing = 8
rightStack.setContentHuggingHorizontalLow()
rightStack.setCompressionResistanceHorizontalLow()
addArrangedSubview(rightStack)
// Text
let textStack = UIStackView()
textStack.axis = .vertical
textStack.alignment = .leading
textStack.spacing = 2
textStack.setContentHuggingHorizontalLow()
textStack.setCompressionResistanceHorizontalLow()
if let title = state.title(),
title.count > 0 {
let label = UILabel()
label.text = title
label.textColor = Theme.primaryColor
label.font = UIFont.ows_dynamicTypeBody
textStack.addArrangedSubview(label)
}
if let displayDomain = state.displayDomain(),
displayDomain.count > 0 {
let label = UILabel()
label.text = displayDomain.uppercased()
label.textColor = Theme.secondaryColor
label.font = UIFont.ows_dynamicTypeCaption1
textStack.addArrangedSubview(label)
}
let textWrapper = UIStackView(arrangedSubviews: [textStack])
textWrapper.axis = .horizontal
textWrapper.alignment = .center
textWrapper.setContentHuggingHorizontalLow()
textWrapper.setCompressionResistanceHorizontalLow()
rightStack.addArrangedSubview(textWrapper)
// Cancel
let cancelStack = UIStackView()
cancelStack.axis = .horizontal
cancelStack.alignment = .top
cancelStack.setContentHuggingHigh()
cancelStack.setCompressionResistanceHigh()
let cancelImage = UIImage(named: "compose-cancel")?.withRenderingMode(.alwaysTemplate)
let cancelButton = UIButton(type: .custom)
cancelButton.setImage(cancelImage, for: .normal)
cancelButton.addTarget(self, action: #selector(didTapCancel(sender:)), for: .touchUpInside)
self.cancelButton = cancelButton
cancelButton.tintColor = Theme.secondaryColor
cancelButton.setContentHuggingHigh()
cancelButton.setCompressionResistanceHigh()
cancelStack.addArrangedSubview(cancelButton)
rightStack.addArrangedSubview(cancelStack)
// Stroke
let strokeView = UIView()
strokeView.backgroundColor = Theme.secondaryColor
rightStack.addSubview(strokeView)
strokeView.autoPinWidthToSuperview()
strokeView.autoPinEdge(toSuperviewEdge: .bottom)
strokeView.autoSetDimension(.height, toSize: CGHairlineWidth())
}
private func createImageView(state: LinkPreviewState) -> UIImageView? {
guard state.isLoaded() else {
owsFailDebug("State not loaded.")
return nil
}
guard state.imageState() == .loaded else {
return nil
}
guard let image = state.image() else {
owsFailDebug("Could not load image.")
return nil
}
let imageView = UIImageView()
imageView.image = image
return imageView
}
private func createDraftImageView(state: LinkPreviewState) -> UIImageView? {
guard state.isLoaded() else {
owsFailDebug("State not loaded.")
return nil
}
guard state.imageState() == .loaded else {
return nil
}
guard let image = state.image() else {
owsFailDebug("Could not load image.")
return nil
}
let imageView = LinkPreviewImageView(hasAsymmetricalRounding: self.hasAsymmetricalRounding)
imageView.image = image
return imageView
}
private func createDraftLoadingContents() {
self.axis = .vertical
self.alignment = .center
self.layoutConstraints.append(self.autoSetDimension(.height, toSize: draftHeight + draftMarginTop))
let activityIndicatorStyle: UIActivityIndicatorView.Style = (Theme.isDarkThemeEnabled
? .white
: .gray)
let activityIndicator = UIActivityIndicatorView(style: activityIndicatorStyle)
activityIndicator.startAnimating()
addArrangedSubview(activityIndicator)
let activityIndicatorSize: CGFloat = 25
activityIndicator.autoSetDimensions(to: CGSize(width: activityIndicatorSize, height: activityIndicatorSize))
// Stroke
let strokeView = UIView()
strokeView.backgroundColor = Theme.secondaryColor
self.addSubview(strokeView)
strokeView.autoPinWidthToSuperview(withMargin: 12)
strokeView.autoPinEdge(toSuperviewEdge: .bottom)
strokeView.autoSetDimension(.height, toSize: CGHairlineWidth())
}
// MARK: Events
@objc func wasTapped(sender: UIGestureRecognizer) {
guard sender.state == .recognized else {
return
}
if let cancelButton = cancelButton {
let cancelLocation = sender.location(in: cancelButton)
// Permissive hot area to make it very easy to cancel the link preview.
let hotAreaInset: CGFloat = -20
let cancelButtonHotArea = cancelButton.bounds.insetBy(dx: hotAreaInset, dy: hotAreaInset)
if cancelButtonHotArea.contains(cancelLocation) {
self.draftDelegate?.linkPreviewDidCancel()
return
}
}
}
// MARK: Measurement
@objc
public func measure(withSentState state: LinkPreviewSent) -> CGSize {
switch state.imageState() {
case .loaded:
if sentIsHero(state: state) {
return measureSentHero(state: state)
} else {
return measureSentNonHero(state: state, hasImage: true)
}
default:
return measureSentNonHero(state: state, hasImage: false)
}
}
private func measureSentHero(state: LinkPreviewSent) -> CGSize {
let maxMessageWidth = state.conversationStyle.maxMessageWidth
var messageHeight: CGFloat = 0
let heroImageSize = sentHeroImageSize(state: state)
messageHeight += heroImageSize.height
let textStackSize = sentTextStackSize(state: state, maxWidth: maxMessageWidth - 2 * sentHeroHMargin)
messageHeight += textStackSize.height + 2 * sentHeroVMargin
return CGSizeCeil(CGSize(width: maxMessageWidth, height: messageHeight))
}
private func measureSentNonHero(state: LinkPreviewSent, hasImage: Bool) -> CGSize {
let maxMessageWidth = state.conversationStyle.maxMessageWidth
var maxTextWidth = maxMessageWidth - 2 * sentNonHeroHMargin
if hasImage {
maxTextWidth -= (sentNonHeroImageSize + sentNonHeroHSpacing)
}
let textStackSize = sentTextStackSize(state: state, maxWidth: maxTextWidth)
var result = textStackSize
if hasImage {
result.width += sentNonHeroImageSize + sentNonHeroHSpacing
result.height = max(result.height, sentNonHeroImageSize)
}
result.width += 2 * sentNonHeroHMargin
result.height += 2 * sentNonHeroVMargin
return CGSizeCeil(result)
}
private func sentTextStackSize(state: LinkPreviewSent, maxWidth: CGFloat) -> CGSize {
let domainLabel = sentDomainLabel(state: state)
let domainLabelSize = CGSizeCeil(domainLabel.sizeThatFits(CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude)))
var result = domainLabelSize
if let titleLabel = sentTitleLabel(state: state) {
let titleLabelSize = CGSizeCeil(titleLabel.sizeThatFits(CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude)))
let maxTitleLabelHeight: CGFloat = ceil(CGFloat(sentTitleLineCount) * titleLabel.font.lineHeight)
result.width = max(result.width, titleLabelSize.width)
result.height += min(maxTitleLabelHeight, titleLabelSize.height) + sentVSpacing
}
return result
}
@objc
public func addBorderViews(bubbleView: OWSBubbleView) {
if let heroImageView = self.heroImageView {
let borderView = OWSBubbleShapeView(draw: ())
borderView.strokeColor = Theme.primaryColor
borderView.strokeThickness = CGHairlineWidthFraction(1.8)
heroImageView.addSubview(borderView)
bubbleView.addPartnerView(borderView)
borderView.ows_autoPinToSuperviewEdges()
}
if let sentBodyView = self.sentBodyView {
let borderView = OWSBubbleShapeView(draw: ())
let borderColor = (Theme.isDarkThemeEnabled ? UIColor.ows_gray60 : UIColor.ows_gray15)
borderView.strokeColor = borderColor
borderView.strokeThickness = CGHairlineWidthFraction(1.8)
sentBodyView.addSubview(borderView)
bubbleView.addPartnerView(borderView)
borderView.ows_autoPinToSuperviewEdges()
} else {
owsFailDebug("Missing sentBodyView")
}
}
@objc func didTapCancel(sender: UIButton) {
self.draftDelegate?.linkPreviewDidCancel()
}
}
| gpl-3.0 | 2b75c20b6282000c5e8fcd90384f4617 | 31.394737 | 147 | 0.627556 | 5.545045 | false | false | false | false |
apple/swift-corelibs-foundation | Sources/Foundation/FileManager+Win32.swift | 1 | 47883 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
@_implementationOnly import CoreFoundation
#if os(Windows)
internal func joinPath(prefix: String, suffix: String) -> String {
var pszPath: PWSTR?
guard !prefix.isEmpty else { return suffix }
guard !suffix.isEmpty else { return prefix }
_ = try! FileManager.default._fileSystemRepresentation(withPath: prefix, andPath: suffix) {
PathAllocCombine($0, $1, ULONG(PATHCCH_ALLOW_LONG_PATHS.rawValue), &pszPath)
}
let path: String = String(decodingCString: pszPath!, as: UTF16.self)
LocalFree(pszPath)
return path
}
extension FileManager {
internal func _mountedVolumeURLs(includingResourceValuesForKeys propertyKeys: [URLResourceKey]?, options: VolumeEnumerationOptions = []) -> [URL]? {
var urls: [URL] = []
var wszVolumeName: [WCHAR] = Array<WCHAR>(repeating: 0, count: Int(MAX_PATH))
var hVolumes: HANDLE = FindFirstVolumeW(&wszVolumeName, DWORD(wszVolumeName.count))
guard hVolumes != INVALID_HANDLE_VALUE else { return nil }
defer { FindVolumeClose(hVolumes) }
repeat {
var dwCChReturnLength: DWORD = 0
GetVolumePathNamesForVolumeNameW(&wszVolumeName, nil, 0, &dwCChReturnLength)
var wszPathNames: [WCHAR] = Array<WCHAR>(repeating: 0, count: Int(dwCChReturnLength + 1))
if !GetVolumePathNamesForVolumeNameW(&wszVolumeName, &wszPathNames, DWORD(wszPathNames.count), &dwCChReturnLength) {
// TODO(compnerd) handle error
continue
}
// GetVolumePathNamesForVolumeNameW writes an array of
// null terminated wchar strings followed by an additional
// null terminator.
// e.g. [ "C", ":", "\\", "\0", "D", ":", "\\", "\0", "\0"]
var remaining = wszPathNames[...]
while !remaining.isEmpty {
let path = remaining.withUnsafeBufferPointer {
String(decodingCString: $0.baseAddress!, as: UTF16.self)
}
if !path.isEmpty {
urls.append(URL(fileURLWithPath: path, isDirectory: true))
}
remaining = remaining.dropFirst(path.count + 1)
}
} while FindNextVolumeW(hVolumes, &wszVolumeName, DWORD(wszVolumeName.count))
return urls
}
internal func _urls(for directory: SearchPathDirectory, in domainMask: SearchPathDomainMask) -> [URL] {
let domains = _SearchPathDomain.allInSearchOrder(from: domainMask)
var urls: [URL] = []
for domain in domains {
urls.append(contentsOf: windowsURLs(for: directory, in: domain))
}
return urls
}
private class func url(for id: KNOWNFOLDERID) -> URL {
var pszPath: PWSTR?
let hResult: HRESULT = withUnsafePointer(to: id) { id in
SHGetKnownFolderPath(id, DWORD(KF_FLAG_DEFAULT.rawValue), nil, &pszPath)
}
precondition(hResult >= 0, "SHGetKnownFolderpath failed \(GetLastError())")
let url: URL = URL(fileURLWithPath: String(decodingCString: pszPath!, as: UTF16.self), isDirectory: true)
CoTaskMemFree(pszPath)
return url
}
private func windowsURLs(for directory: SearchPathDirectory, in domain: _SearchPathDomain) -> [URL] {
switch directory {
case .autosavedInformationDirectory:
// FIXME(compnerd) where should this go?
return []
case .desktopDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_Desktop)]
case .documentDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_Documents)]
case .cachesDirectory:
guard domain == .user else { return [] }
return [URL(fileURLWithPath: NSTemporaryDirectory())]
case .applicationSupportDirectory:
switch domain {
case .local:
return [FileManager.url(for: FOLDERID_ProgramData)]
case .user:
return [FileManager.url(for: FOLDERID_LocalAppData)]
default:
return []
}
case .downloadsDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_Downloads)]
case .userDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_UserProfiles)]
case .moviesDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_Videos)]
case .musicDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_Music)]
case .picturesDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_PicturesLibrary)]
case .sharedPublicDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_Public)]
case .trashDirectory:
guard domain == .user else { return [] }
return [FileManager.url(for: FOLDERID_RecycleBinFolder)]
// None of these are supported outside of Darwin:
case .applicationDirectory,
.demoApplicationDirectory,
.developerApplicationDirectory,
.adminApplicationDirectory,
.libraryDirectory,
.developerDirectory,
.documentationDirectory,
.coreServiceDirectory,
.inputMethodsDirectory,
.preferencePanesDirectory,
.applicationScriptsDirectory,
.allApplicationsDirectory,
.allLibrariesDirectory,
.printerDescriptionDirectory,
.itemReplacementDirectory:
return []
}
}
internal func _createDirectory(atPath path: String, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey : Any]? = [:]) throws {
if createIntermediates {
var isDir: ObjCBool = false
if fileExists(atPath: path, isDirectory: &isDir) {
guard isDir.boolValue else { throw _NSErrorWithErrno(EEXIST, reading: false, path: path) }
return
}
let parent = path._nsObject.deletingLastPathComponent
if !parent.isEmpty && !fileExists(atPath: parent, isDirectory: &isDir) {
try createDirectory(atPath: parent, withIntermediateDirectories: true, attributes: attributes)
}
}
try FileManager.default._fileSystemRepresentation(withPath: path) { fsr in
var saAttributes: SECURITY_ATTRIBUTES =
SECURITY_ATTRIBUTES(nLength: DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size),
lpSecurityDescriptor: nil,
bInheritHandle: false)
try withUnsafeMutablePointer(to: &saAttributes) {
if !CreateDirectoryW(fsr, $0) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [path])
}
}
if let attr = attributes {
try self.setAttributes(attr, ofItemAtPath: path)
}
}
}
internal func _contentsOfDir(atPath path: String, _ closure: (String, Int32) throws -> () ) throws {
guard path != "" else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInvalidFileName.rawValue, userInfo: [NSFilePathErrorKey : NSString(path)])
}
try FileManager.default._fileSystemRepresentation(withPath: path + "\\*") {
var ffd: WIN32_FIND_DATAW = WIN32_FIND_DATAW()
let hDirectory: HANDLE = FindFirstFileW($0, &ffd)
if hDirectory == INVALID_HANDLE_VALUE {
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}
defer { FindClose(hDirectory) }
repeat {
let path: String = withUnsafePointer(to: &ffd.cFileName) {
$0.withMemoryRebound(to: UInt16.self, capacity: MemoryLayout.size(ofValue: $0) / MemoryLayout<WCHAR>.size) {
String(decodingCString: $0, as: UTF16.self)
}
}
if path != "." && path != ".." {
try closure(path.standardizingPath, Int32(ffd.dwFileAttributes))
}
} while FindNextFileW(hDirectory, &ffd)
}
}
internal func _subpathsOfDirectory(atPath path: String) throws -> [String] {
var contents: [String] = []
try _contentsOfDir(atPath: path, { (entryName, entryType) throws in
contents.append(entryName)
if entryType & FILE_ATTRIBUTE_DIRECTORY == FILE_ATTRIBUTE_DIRECTORY
&& entryType & FILE_ATTRIBUTE_REPARSE_POINT != FILE_ATTRIBUTE_REPARSE_POINT {
let subPath: String = joinPath(prefix: path, suffix: entryName)
let entries = try subpathsOfDirectory(atPath: subPath)
contents.append(contentsOf: entries.map { joinPath(prefix: entryName, suffix: $0).standardizingPath })
}
})
return contents
}
internal func windowsFileAttributes(atPath path: String) throws -> WIN32_FILE_ATTRIBUTE_DATA {
return try FileManager.default._fileSystemRepresentation(withPath: path) {
var faAttributes: WIN32_FILE_ATTRIBUTE_DATA = WIN32_FILE_ATTRIBUTE_DATA()
if !GetFileAttributesExW($0, GetFileExInfoStandard, &faAttributes) {
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}
return faAttributes
}
}
internal func _attributesOfFileSystemIncludingBlockSize(forPath path: String) throws -> (attributes: [FileAttributeKey : Any], blockSize: UInt64?) {
return (attributes: try _attributesOfFileSystem(forPath: path), blockSize: nil)
}
internal func _attributesOfFileSystem(forPath path: String) throws -> [FileAttributeKey : Any] {
var result: [FileAttributeKey:Any] = [:]
try FileManager.default._fileSystemRepresentation(withPath: path) {
let dwLength: DWORD = GetFullPathNameW($0, 0, nil, nil)
guard dwLength > 0 else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}
var szVolumePath: [WCHAR] = Array<WCHAR>(repeating: 0, count: Int(dwLength + 1))
guard GetVolumePathNameW($0, &szVolumePath, dwLength) else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}
var liTotal: ULARGE_INTEGER = ULARGE_INTEGER()
var liFree: ULARGE_INTEGER = ULARGE_INTEGER()
guard GetDiskFreeSpaceExW(&szVolumePath, nil, &liTotal, &liFree) else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}
let hr: HRESULT = PathCchStripToRoot(&szVolumePath, szVolumePath.count)
guard hr == S_OK || hr == S_FALSE else {
throw _NSErrorWithWindowsError(DWORD(hr & 0xffff), reading: true, paths: [path])
}
var volumeSerialNumber: DWORD = 0
guard GetVolumeInformationW(&szVolumePath, nil, 0, &volumeSerialNumber, nil, nil, nil, 0) else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}
result[.systemSize] = NSNumber(value: liTotal.QuadPart)
result[.systemFreeSize] = NSNumber(value: liFree.QuadPart)
result[.systemNumber] = NSNumber(value: volumeSerialNumber)
// FIXME(compnerd): what about .systemNodes, .systemFreeNodes?
}
return result
}
internal func _createSymbolicLink(atPath path: String, withDestinationPath destPath: String, isDirectory: Bool? = nil) throws {
var dwFlags = DWORD(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)
// If destPath is relative, we should look for it relative to `path`, not our current working directory
switch isDirectory {
case .some(true):
dwFlags |= DWORD(SYMBOLIC_LINK_FLAG_DIRECTORY)
case .some(false):
break;
case .none:
let resolvedDest =
destPath.isAbsolutePath ? destPath
: joinPath(prefix: path.deletingLastPathComponent,
suffix: destPath)
// NOTE: windowsfileAttributes will throw if the destPath is not
// found. Since on Windows, you are required to know the type
// of the symlink target (file or directory) during creation,
// and assuming one or the other doesn't make a lot of sense, we
// allow it to throw, thus disallowing the creation of broken
// symlinks on Windows is the target is of unknown type.
guard let faAttributes = try? windowsFileAttributes(atPath: resolvedDest) else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path, destPath])
}
if faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) == DWORD(FILE_ATTRIBUTE_DIRECTORY) {
dwFlags |= DWORD(SYMBOLIC_LINK_FLAG_DIRECTORY)
}
}
try FileManager.default._fileSystemRepresentation(withPath: path, andPath: destPath) {
guard CreateSymbolicLinkW($0, $1, dwFlags) != 0 else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path, destPath])
}
}
}
internal func _destinationOfSymbolicLink(atPath path: String) throws -> String {
let faAttributes = try windowsFileAttributes(atPath: path)
guard faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_REPARSE_POINT) == DWORD(FILE_ATTRIBUTE_REPARSE_POINT) else {
throw _NSErrorWithWindowsError(DWORD(ERROR_BAD_ARGUMENTS), reading: false)
}
let handle: HANDLE = try FileManager.default._fileSystemRepresentation(withPath: path) {
CreateFileW($0, GENERIC_READ,
DWORD(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE),
nil, DWORD(OPEN_EXISTING),
DWORD(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS),
nil)
}
if handle == INVALID_HANDLE_VALUE {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
}
defer { CloseHandle(handle) }
// Since REPARSE_DATA_BUFFER ends with an arbitrarily long buffer, we
// have to manually get the path buffer out of it since binding it to a
// type will truncate the path buffer.
//
// 20 is the sum of the offsets of:
// ULONG ReparseTag
// USHORT ReparseDataLength
// USHORT Reserved
// USHORT SubstituteNameOffset
// USHORT SubstituteNameLength
// USHORT PrintNameOffset
// USHORT PrintNameLength
// ULONG Flags (Symlink only)
let symLinkPathBufferOffset = 20 // 4 + 2 + 2 + 2 + 2 + 2 + 2 + 4
let mountPointPathBufferOffset = 16 // 4 + 2 + 2 + 2 + 2 + 2 + 2
let buff = UnsafeMutableRawBufferPointer.allocate(byteCount: Int(MAXIMUM_REPARSE_DATA_BUFFER_SIZE),
alignment: 8)
guard let buffBase = buff.baseAddress else {
throw _NSErrorWithWindowsError(DWORD(ERROR_INVALID_DATA), reading: false)
}
var bytesWritten: DWORD = 0
guard DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, nil, 0,
buffBase, DWORD(MAXIMUM_REPARSE_DATA_BUFFER_SIZE),
&bytesWritten, nil) else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true)
}
guard bytesWritten >= MemoryLayout<REPARSE_DATA_BUFFER>.size else {
throw _NSErrorWithWindowsError(DWORD(ERROR_INVALID_DATA), reading: false)
}
let bound = buff.bindMemory(to: REPARSE_DATA_BUFFER.self)
guard let reparseDataBuffer = bound.first else {
throw _NSErrorWithWindowsError(DWORD(ERROR_INVALID_DATA), reading: false)
}
guard reparseDataBuffer.ReparseTag == IO_REPARSE_TAG_SYMLINK
|| reparseDataBuffer.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT else {
throw _NSErrorWithWindowsError(DWORD(ERROR_BAD_ARGUMENTS), reading: false)
}
let pathBufferPtr: UnsafeMutableRawPointer
let substituteNameBytes: Int
let substituteNameOffset: Int
switch reparseDataBuffer.ReparseTag {
case IO_REPARSE_TAG_SYMLINK:
pathBufferPtr = buffBase + symLinkPathBufferOffset
substituteNameBytes = Int(reparseDataBuffer.SymbolicLinkReparseBuffer.SubstituteNameLength)
substituteNameOffset = Int(reparseDataBuffer.SymbolicLinkReparseBuffer.SubstituteNameOffset)
case IO_REPARSE_TAG_MOUNT_POINT:
pathBufferPtr = buffBase + mountPointPathBufferOffset
substituteNameBytes = Int(reparseDataBuffer.MountPointReparseBuffer.SubstituteNameLength)
substituteNameOffset = Int(reparseDataBuffer.MountPointReparseBuffer.SubstituteNameOffset)
default:
throw _NSErrorWithWindowsError(DWORD(ERROR_BAD_ARGUMENTS), reading: false)
}
guard substituteNameBytes + substituteNameOffset <= bytesWritten else {
throw _NSErrorWithWindowsError(DWORD(ERROR_INVALID_DATA), reading: false)
}
let substituteNameBuff = Data(bytes: pathBufferPtr + substituteNameOffset, count: substituteNameBytes)
guard var substitutePath = String(data: substituteNameBuff, encoding: .utf16LittleEndian) else {
throw _NSErrorWithWindowsError(DWORD(ERROR_INVALID_DATA), reading: false)
}
// Canonicalize the NT Object Manager Path to the DOS style path
// instead. Unfortunately, there is no nice API which can allow us to
// do this in a guranteed way.
let kObjectManagerPrefix = "\\??\\"
if substitutePath.hasPrefix(kObjectManagerPrefix) {
substitutePath = String(substitutePath.dropFirst(kObjectManagerPrefix.count))
}
return substitutePath
}
private func _realpath(_ path: String) -> String {
return (try? _destinationOfSymbolicLink(atPath: path)) ?? path
}
internal func _recursiveDestinationOfSymbolicLink(atPath path: String) throws -> String {
// Throw error if path is not a symbolic link:
var previousIterationDestination = try _destinationOfSymbolicLink(atPath: path)
// Same recursion limit as in Darwin:
let symbolicLinkRecursionLimit = 32
for _ in 0..<symbolicLinkRecursionLimit {
let iterationDestination = _realpath(previousIterationDestination)
if previousIterationDestination == iterationDestination {
return iterationDestination
}
previousIterationDestination = iterationDestination
}
// As in Darwin Foundation, after the recursion limit we return the initial path without resolution.
return path
}
internal func _canonicalizedPath(toFileAtPath path: String) throws -> String {
let hFile: HANDLE = try FileManager.default._fileSystemRepresentation(withPath: path) {
// BACKUP_SEMANTICS are (confusingly) required in order to receive a
// handle to a directory
CreateFileW($0, /*dwDesiredAccess=*/DWORD(0),
DWORD(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE),
/*lpSecurityAttributes=*/nil, DWORD(OPEN_EXISTING),
DWORD(FILE_FLAG_BACKUP_SEMANTICS), /*hTemplateFile=*/nil)
}
if hFile == INVALID_HANDLE_VALUE {
return try FileManager.default._fileSystemRepresentation(withPath: path) {
var dwLength = GetFullPathNameW($0, 0, nil, nil)
var szPath = Array<WCHAR>(repeating: 0, count: Int(dwLength + 1))
dwLength = GetFullPathNameW($0, DWORD(szPath.count), &szPath, nil)
guard dwLength > 0 && dwLength <= szPath.count else {
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}
return String(decodingCString: szPath, as: UTF16.self)
}
}
defer { CloseHandle(hFile) }
let dwLength: DWORD = GetFinalPathNameByHandleW(hFile, nil, 0, DWORD(FILE_NAME_NORMALIZED))
var szPath: [WCHAR] = Array<WCHAR>(repeating: 0, count: Int(dwLength + 1))
GetFinalPathNameByHandleW(hFile, &szPath, dwLength, DWORD(FILE_NAME_NORMALIZED))
return String(decodingCString: &szPath, as: UTF16.self)
}
internal func _copyRegularFile(atPath srcPath: String, toPath dstPath: String, variant: String = "Copy") throws {
try FileManager.default._fileSystemRepresentation(withPath: srcPath, andPath: dstPath) {
if !CopyFileW($0, $1, false) {
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [srcPath, dstPath])
}
}
}
internal func _copySymlink(atPath srcPath: String, toPath dstPath: String, variant: String = "Copy") throws {
let faAttributes: WIN32_FILE_ATTRIBUTE_DATA = try windowsFileAttributes(atPath: srcPath)
guard faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_REPARSE_POINT) == DWORD(FILE_ATTRIBUTE_REPARSE_POINT) else {
throw _NSErrorWithErrno(EINVAL, reading: true, path: srcPath, extraUserInfo: extraErrorInfo(srcPath: srcPath, dstPath: dstPath, userVariant: variant))
}
let destination = try destinationOfSymbolicLink(atPath: srcPath)
let isDir = try windowsFileAttributes(atPath: srcPath).dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) == DWORD(FILE_ATTRIBUTE_DIRECTORY)
if fileExists(atPath: dstPath) {
try removeItem(atPath: dstPath)
}
try _createSymbolicLink(atPath: dstPath, withDestinationPath: destination, isDirectory: isDir)
}
internal func _copyOrLinkDirectoryHelper(atPath srcPath: String, toPath dstPath: String, variant: String = "Copy", _ body: (String, String, FileAttributeType) throws -> ()) throws {
let faAttributes = try windowsFileAttributes(atPath: srcPath)
var fileType = FileAttributeType(attributes: faAttributes, atPath: srcPath)
if fileType == .typeDirectory {
try createDirectory(atPath: dstPath, withIntermediateDirectories: false, attributes: nil)
guard let enumerator = enumerator(atPath: srcPath) else {
throw _NSErrorWithErrno(ENOENT, reading: true, path: srcPath)
}
while let item = enumerator.nextObject() as? String {
let src = joinPath(prefix: srcPath, suffix: item)
let dst = joinPath(prefix: dstPath, suffix: item)
let faAttributes = try windowsFileAttributes(atPath: src)
fileType = FileAttributeType(attributes: faAttributes, atPath: srcPath)
if fileType == .typeDirectory {
try createDirectory(atPath: dst, withIntermediateDirectories: false, attributes: nil)
} else {
try body(src, dst, fileType)
}
}
} else {
try body(srcPath, dstPath, fileType)
}
}
internal func _moveItem(atPath srcPath: String, toPath dstPath: String, isURL: Bool) throws {
guard shouldMoveItemAtPath(srcPath, toPath: dstPath, isURL: isURL) else {
return
}
guard !self.fileExists(atPath: dstPath) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteFileExists.rawValue, userInfo: [NSFilePathErrorKey : NSString(dstPath)])
}
try FileManager.default._fileSystemRepresentation(withPath: srcPath, andPath: dstPath) {
if !MoveFileExW($0, $1, DWORD(MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [srcPath, dstPath])
}
}
}
internal func _linkItem(atPath srcPath: String, toPath dstPath: String, isURL: Bool) throws {
try _copyOrLinkDirectoryHelper(atPath: srcPath, toPath: dstPath) { (srcPath, dstPath, fileType) in
guard shouldLinkItemAtPath(srcPath, toPath: dstPath, isURL: isURL) else {
return
}
do {
switch fileType {
case .typeRegular:
try FileManager.default._fileSystemRepresentation(withPath: srcPath, andPath: dstPath) {
if !CreateHardLinkW($1, $0, nil) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [srcPath, dstPath])
}
}
case .typeSymbolicLink:
try _copySymlink(atPath: srcPath, toPath: dstPath)
default:
break
}
} catch {
if !shouldProceedAfterError(error, linkingItemAtPath: srcPath, toPath: dstPath, isURL: isURL) {
throw error
}
}
}
}
internal func _removeItem(atPath path: String, isURL: Bool, alreadyConfirmed: Bool = false) throws {
guard alreadyConfirmed || shouldRemoveItemAtPath(path, isURL: isURL) else {
return
}
let faAttributes: WIN32_FILE_ATTRIBUTE_DATA
do {
faAttributes = try windowsFileAttributes(atPath: path)
} catch {
// removeItem on POSIX throws fileNoSuchFile rather than
// fileReadNoSuchFile that windowsFileAttributes will
// throw if it doesn't find the file.
if (error as NSError).code == CocoaError.fileReadNoSuchFile.rawValue {
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [path])
} else {
throw error
}
}
if faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY {
if try !FileManager.default._fileSystemRepresentation(withPath: path, {
SetFileAttributesW($0, faAttributes.dwFileAttributes & ~DWORD(FILE_ATTRIBUTE_READONLY))
}) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [path])
}
}
if faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) == 0 {
if try !FileManager.default._fileSystemRepresentation(withPath: path, DeleteFileW) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [path])
}
return
}
var dirStack = [path]
var itemPath = ""
while let currentDir = dirStack.popLast() {
do {
itemPath = currentDir
guard alreadyConfirmed || shouldRemoveItemAtPath(itemPath, isURL: isURL) else {
continue
}
if try FileManager.default._fileSystemRepresentation(withPath: itemPath, RemoveDirectoryW) {
continue
}
guard GetLastError() == ERROR_DIR_NOT_EMPTY else {
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [itemPath])
}
dirStack.append(itemPath)
var ffd: WIN32_FIND_DATAW = WIN32_FIND_DATAW()
let capacity = MemoryLayout.size(ofValue: ffd.cFileName)
let handle: HANDLE = try FileManager.default._fileSystemRepresentation(withPath: itemPath + "\\*") {
FindFirstFileW($0, &ffd)
}
if handle == INVALID_HANDLE_VALUE {
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [itemPath])
}
defer { FindClose(handle) }
repeat {
let file = withUnsafePointer(to: &ffd.cFileName) {
$0.withMemoryRebound(to: WCHAR.self, capacity: capacity) {
String(decodingCString: $0, as: UTF16.self)
}
}
itemPath = "\(currentDir)\\\(file)"
if ffd.dwFileAttributes & DWORD(FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY {
if try !FileManager.default._fileSystemRepresentation(withPath: itemPath, {
SetFileAttributesW($0, ffd.dwFileAttributes & ~DWORD(FILE_ATTRIBUTE_READONLY))
}) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [file])
}
}
if (ffd.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) != 0) {
if file != "." && file != ".." {
dirStack.append(itemPath)
}
} else {
guard alreadyConfirmed || shouldRemoveItemAtPath(itemPath, isURL: isURL) else {
continue
}
if try !FileManager.default._fileSystemRepresentation(withPath: itemPath, DeleteFileW) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [file])
}
}
} while FindNextFileW(handle, &ffd)
} catch {
if !shouldProceedAfterError(error, removingItemAtPath: itemPath, isURL: isURL) {
throw error
}
}
}
}
internal func _currentDirectoryPath() -> String {
let dwLength: DWORD = GetCurrentDirectoryW(0, nil)
var szDirectory: [WCHAR] = Array<WCHAR>(repeating: 0, count: Int(dwLength + 1))
GetCurrentDirectoryW(dwLength, &szDirectory)
return String(decodingCString: &szDirectory, as: UTF16.self).standardizingPath
}
@discardableResult
internal func _changeCurrentDirectoryPath(_ path: String) -> Bool {
return (try? FileManager.default._fileSystemRepresentation(withPath: path) {
SetCurrentDirectoryW($0)
}) ?? false
}
internal func _fileExists(atPath path: String, isDirectory: UnsafeMutablePointer<ObjCBool>?) -> Bool {
var faAttributes: WIN32_FILE_ATTRIBUTE_DATA = WIN32_FILE_ATTRIBUTE_DATA()
do { faAttributes = try windowsFileAttributes(atPath: path) } catch { return false }
if faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_REPARSE_POINT) == DWORD(FILE_ATTRIBUTE_REPARSE_POINT) {
let handle: HANDLE = (try? FileManager.default._fileSystemRepresentation(withPath: path) {
CreateFileW($0, /* dwDesiredAccess= */ DWORD(0),
DWORD(FILE_SHARE_READ), /* lpSecurityAttributes= */ nil,
DWORD(OPEN_EXISTING),
DWORD(FILE_FLAG_BACKUP_SEMANTICS), /* hTemplateFile= */ nil)
}) ?? INVALID_HANDLE_VALUE
if handle == INVALID_HANDLE_VALUE { return false }
defer { CloseHandle(handle) }
if let isDirectory = isDirectory {
var info: BY_HANDLE_FILE_INFORMATION = BY_HANDLE_FILE_INFORMATION()
GetFileInformationByHandle(handle, &info)
isDirectory.pointee = ObjCBool(info.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) == DWORD(FILE_ATTRIBUTE_DIRECTORY))
}
} else {
if let isDirectory = isDirectory {
isDirectory.pointee = ObjCBool(faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) == DWORD(FILE_ATTRIBUTE_DIRECTORY))
}
}
return true
}
internal func _isReadableFile(atPath path: String) -> Bool {
do { let _ = try windowsFileAttributes(atPath: path) } catch { return false }
return true
}
internal func _isWritableFile(atPath path: String) -> Bool {
guard let faAttributes: WIN32_FILE_ATTRIBUTE_DATA = try? windowsFileAttributes(atPath: path) else { return false }
return faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_READONLY) != DWORD(FILE_ATTRIBUTE_READONLY)
}
internal func _isExecutableFile(atPath path: String) -> Bool {
var binaryType = DWORD(0)
return path.withCString(encodedAs: UTF16.self) {
GetBinaryTypeW($0, &binaryType)
}
}
internal func _isDeletableFile(atPath path: String) -> Bool {
guard path != "" else { return true }
// Get the parent directory of supplied path
let parent = path._nsObject.deletingLastPathComponent
var faAttributes: WIN32_FILE_ATTRIBUTE_DATA = WIN32_FILE_ATTRIBUTE_DATA()
do { faAttributes = try windowsFileAttributes(atPath: parent) } catch { return false }
if faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_READONLY) == DWORD(FILE_ATTRIBUTE_READONLY) {
return false
}
do { faAttributes = try windowsFileAttributes(atPath: path) } catch { return false }
if faAttributes.dwFileAttributes & DWORD(FILE_ATTRIBUTE_READONLY) == DWORD(FILE_ATTRIBUTE_READONLY) {
return false
}
return true
}
internal func _lstatFile(atPath path: String, withFileSystemRepresentation fsRep: UnsafePointer<NativeFSRCharType>? = nil) throws -> stat {
let (stbuf, _) = try _statxFile(atPath: path, withFileSystemRepresentation: fsRep)
return stbuf
}
// FIXME(compnerd) the UInt64 should be UInt128 to uniquely identify the file across volumes
internal func _statxFile(atPath path: String, withFileSystemRepresentation fsRep: UnsafePointer<NativeFSRCharType>? = nil) throws -> (stat, UInt64) {
let _fsRep: UnsafePointer<NativeFSRCharType>
if fsRep == nil {
_fsRep = try __fileSystemRepresentation(withPath: path)
} else {
_fsRep = fsRep!
}
defer {
if fsRep == nil { _fsRep.deallocate() }
}
var statInfo = stat()
let handle =
CreateFileW(_fsRep, /*dwDesiredAccess=*/DWORD(0),
DWORD(FILE_SHARE_READ), /*lpSecurityAttributes=*/nil,
DWORD(OPEN_EXISTING),
DWORD(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS),
/*hTemplateFile=*/nil)
if handle == INVALID_HANDLE_VALUE {
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [path])
}
defer { CloseHandle(handle) }
var info: BY_HANDLE_FILE_INFORMATION = BY_HANDLE_FILE_INFORMATION()
GetFileInformationByHandle(handle, &info)
// Group id is always 0 on Windows
statInfo.st_gid = 0
statInfo.st_atime = info.ftLastAccessTime.time_t
statInfo.st_ctime = info.ftCreationTime.time_t
statInfo.st_dev = _dev_t(info.dwVolumeSerialNumber)
// The inode, and therefore st_ino, has no meaning in the FAT, HPFS, or
// NTFS file systems. -- docs.microsoft.com
statInfo.st_ino = 0
statInfo.st_rdev = _dev_t(info.dwVolumeSerialNumber)
let isReparsePoint = info.dwFileAttributes & DWORD(FILE_ATTRIBUTE_REPARSE_POINT) != 0
let isDir = info.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) != 0
let fileMode = isDir ? _S_IFDIR : _S_IFREG
// On a symlink to a directory, Windows sets both the REPARSE_POINT and
// DIRECTORY attributes. Since Windows doesn't provide S_IFLNK and we
// want unix style "symlinks to directories are not directories
// themselves, we say symlinks are regular files
statInfo.st_mode = UInt16(isReparsePoint ? _S_IFREG : fileMode)
let isReadOnly = info.dwFileAttributes & DWORD(FILE_ATTRIBUTE_READONLY) != 0
statInfo.st_mode |= UInt16(isReadOnly ? _S_IREAD : (_S_IREAD | _S_IWRITE))
statInfo.st_mode |= UInt16(_S_IEXEC)
statInfo.st_mtime = info.ftLastWriteTime.time_t
statInfo.st_nlink = Int16(info.nNumberOfLinks)
guard info.nFileSizeHigh == 0 else {
throw _NSErrorWithErrno(EOVERFLOW, reading: true, path: path)
}
statInfo.st_size = _off_t(info.nFileSizeLow)
// Uid is always 0 on Windows systems
statInfo.st_uid = 0
return (statInfo, UInt64(info.nFileIndexHigh << 32) | UInt64(info.nFileIndexLow))
}
internal func _contentsEqual(atPath path1: String, andPath path2: String) -> Bool {
let path1Handle: HANDLE = (try? FileManager.default._fileSystemRepresentation(withPath: path1) {
CreateFileW($0, GENERIC_READ,
DWORD(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE),
nil, DWORD(OPEN_EXISTING),
DWORD(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS),
nil)
}) ?? INVALID_HANDLE_VALUE
if path1Handle == INVALID_HANDLE_VALUE { return false }
defer { CloseHandle(path1Handle) }
let path2Handle: HANDLE = (try? FileManager.default._fileSystemRepresentation(withPath: path2) {
CreateFileW($0, GENERIC_READ,
DWORD(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE),
nil, DWORD(OPEN_EXISTING),
DWORD(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS),
nil)
}) ?? INVALID_HANDLE_VALUE
if path2Handle == INVALID_HANDLE_VALUE { return false }
defer { CloseHandle(path2Handle) }
let file1Type = GetFileType(path1Handle)
guard GetLastError() == NO_ERROR else {
return false
}
let file2Type = GetFileType(path2Handle)
guard GetLastError() == NO_ERROR else {
return false
}
guard file1Type == FILE_TYPE_DISK, file2Type == FILE_TYPE_DISK else {
return false
}
var path1FileInfo = BY_HANDLE_FILE_INFORMATION()
var path2FileInfo = BY_HANDLE_FILE_INFORMATION()
guard GetFileInformationByHandle(path1Handle, &path1FileInfo),
GetFileInformationByHandle(path2Handle, &path2FileInfo) else {
return false
}
// If both paths point to the same volume/filenumber or they are both zero length
// then they are considered equal
if path1FileInfo.nFileIndexHigh == path2FileInfo.nFileIndexHigh
&& path1FileInfo.nFileIndexLow == path2FileInfo.nFileIndexLow
&& path1FileInfo.dwVolumeSerialNumber == path2FileInfo.dwVolumeSerialNumber {
return true
}
let path1Attrs = path1FileInfo.dwFileAttributes
let path2Attrs = path2FileInfo.dwFileAttributes
if path1Attrs & DWORD(FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT
|| path2Attrs & DWORD(FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT {
guard path1Attrs & DWORD(FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT
&& path2Attrs & DWORD(FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT else {
return false
}
guard let pathDest1 = try? _destinationOfSymbolicLink(atPath: path1),
let pathDest2 = try? _destinationOfSymbolicLink(atPath: path2) else {
return false
}
return pathDest1 == pathDest2
} else if DWORD(FILE_ATTRIBUTE_DIRECTORY) & path1Attrs == DWORD(FILE_ATTRIBUTE_DIRECTORY)
|| DWORD(FILE_ATTRIBUTE_DIRECTORY) & path2Attrs == DWORD(FILE_ATTRIBUTE_DIRECTORY) {
guard DWORD(FILE_ATTRIBUTE_DIRECTORY) & path1Attrs == DWORD(FILE_ATTRIBUTE_DIRECTORY)
&& DWORD(FILE_ATTRIBUTE_DIRECTORY) & path2Attrs == FILE_ATTRIBUTE_DIRECTORY else {
return false
}
return _compareDirectories(atPath: path1, andPath: path2)
} else {
if path1FileInfo.nFileSizeHigh == 0 && path1FileInfo.nFileSizeLow == 0
&& path2FileInfo.nFileSizeHigh == 0 && path2FileInfo.nFileSizeLow == 0 {
return true
}
return try! FileManager.default._fileSystemRepresentation(withPath: path1, andPath: path2) {
_compareFiles(withFileSystemRepresentation: $0,
andFileSystemRepresentation: $1,
size: (Int64(path1FileInfo.nFileSizeHigh) << 32) | Int64(path1FileInfo.nFileSizeLow),
bufSize: 0x1000)
}
}
}
internal func _appendSymlinkDestination(_ dest: String, toPath: String) -> String {
if dest.isAbsolutePath { return dest }
let temp = toPath._bridgeToObjectiveC().deletingLastPathComponent
return temp._bridgeToObjectiveC().appendingPathComponent(dest)
}
internal func _updateTimes(atPath path: String,
withFileSystemRepresentation fsr: UnsafePointer<NativeFSRCharType>,
creationTime: Date? = nil,
accessTime: Date? = nil,
modificationTime: Date? = nil) throws {
let stat = try _lstatFile(atPath: path, withFileSystemRepresentation: fsr)
var atime: FILETIME =
FILETIME(from: time_t((accessTime ?? stat.lastAccessDate).timeIntervalSince1970))
var mtime: FILETIME =
FILETIME(from: time_t((modificationTime ?? stat.lastModificationDate).timeIntervalSince1970))
let hFile: HANDLE =
CreateFileW(fsr, DWORD(GENERIC_WRITE), DWORD(FILE_SHARE_WRITE),
nil, DWORD(OPEN_EXISTING), 0, nil)
if hFile == INVALID_HANDLE_VALUE {
throw _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [path])
}
defer { CloseHandle(hFile) }
if !SetFileTime(hFile, nil, &atime, &mtime) {
throw _NSErrorWithWindowsError(GetLastError(), reading: false, paths: [path])
}
}
internal class NSURLDirectoryEnumerator : DirectoryEnumerator {
var _options : FileManager.DirectoryEnumerationOptions
var _errorHandler : ((URL, Error) -> Bool)?
var _stack: [URL]
var _lastReturned: URL
var _rootDepth : Int
init(url: URL, options: FileManager.DirectoryEnumerationOptions, errorHandler: (/* @escaping */ (URL, Error) -> Bool)?) {
_options = options
_errorHandler = errorHandler
_stack = []
_rootDepth = url.pathComponents.count
_lastReturned = url
}
override func nextObject() -> Any? {
func firstValidItem() -> URL? {
while let url = _stack.popLast() {
if !FileManager.default.fileExists(atPath: url.path) {
if let handler = _errorHandler {
if !handler(url, _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [url.path])) {
return nil
}
} else {
return nil
}
}
_lastReturned = url
return _lastReturned
}
return nil
}
// If we most recently returned a directory, decend into it
guard let attrs = try? FileManager.default.windowsFileAttributes(atPath: _lastReturned.path) else {
guard let handler = _errorHandler,
handler(_lastReturned, _NSErrorWithWindowsError(GetLastError(), reading: true, paths: [_lastReturned.path]))
else { return nil }
return firstValidItem()
}
let isDir = attrs.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY) == DWORD(FILE_ATTRIBUTE_DIRECTORY) &&
attrs.dwFileAttributes & DWORD(FILE_ATTRIBUTE_REPARSE_POINT) == 0
if isDir && (level == 0 || !_options.contains(.skipsSubdirectoryDescendants)) {
var ffd = WIN32_FIND_DATAW()
let capacity = MemoryLayout.size(ofValue: ffd.cFileName)
let handle = (try? FileManager.default._fileSystemRepresentation(withPath: _lastReturned.path + "\\*") {
FindFirstFileW($0, &ffd)
}) ?? INVALID_HANDLE_VALUE
if handle == INVALID_HANDLE_VALUE { return firstValidItem() }
defer { FindClose(handle) }
repeat {
let file = withUnsafePointer(to: &ffd.cFileName) {
$0.withMemoryRebound(to: WCHAR.self, capacity: capacity) {
String(decodingCString: $0, as: UTF16.self)
}
}
if file == "." || file == ".." { continue }
if _options.contains(.skipsHiddenFiles) &&
ffd.dwFileAttributes & DWORD(FILE_ATTRIBUTE_HIDDEN) == DWORD(FILE_ATTRIBUTE_HIDDEN) {
continue
}
_stack.append(URL(fileURLWithPath: file, relativeTo: _lastReturned))
} while FindNextFileW(handle, &ffd)
}
return firstValidItem()
}
override var level: Int {
return _lastReturned.pathComponents.count - _rootDepth
}
override func skipDescendants() {
_options.insert(.skipsSubdirectoryDescendants)
}
override var directoryAttributes : [FileAttributeKey : Any]? {
return nil
}
override var fileAttributes: [FileAttributeKey : Any]? {
return nil
}
}
}
extension FileManager.NSPathDirectoryEnumerator {
internal func _nextObject() -> Any? {
guard let url = innerEnumerator.nextObject() as? URL else { return nil }
var relativePath: [WCHAR] = Array<WCHAR>(repeating: 0, count: Int(MAX_PATH))
guard baseURL._withUnsafeWideFileSystemRepresentation({ baseUrlFsr in
url._withUnsafeWideFileSystemRepresentation { urlFsr in
let fromAttrs = GetFileAttributesW(baseUrlFsr)
let toAttrs = GetFileAttributesW(urlFsr)
guard fromAttrs != INVALID_FILE_ATTRIBUTES, toAttrs != INVALID_FILE_ATTRIBUTES else {
return false
}
return PathRelativePathToW(&relativePath, baseUrlFsr, fromAttrs, urlFsr, toAttrs)
}
}) else { return nil }
let path = String(decodingCString: &relativePath, as: UTF16.self)
// Drop the leading ".\" from the path
_currentItemPath = String(path.dropFirst(2))
return _currentItemPath
}
}
#endif
| apache-2.0 | 32db57e12541593aab4a2e0ff4686688 | 45.130058 | 185 | 0.604473 | 4.972791 | false | false | false | false |
HipHipArr/PocketCheck | Cheapify 2.0/AddEntry.swift | 1 | 21192 | //
// AddEntry.swift
// Cheapify 2.0
//
// Created by Carol on 7/1/15.
// Designed by Maitreyee, Lauren on 7/1/15
// Copyright (c) 2015 Hip Hip Array[]. All rights reserved.
//
import UIKit
import CoreData
import Foundation
class AddEntry: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UINavigationControllerDelegate {
//@IBOutlet weak var textView: UITextView!
//@IBOutlet weak var findTextField: UITextField!
//@IBOutlet weak var replaceTextField: UITextField!
//@IBOutlet weak var topMarginConstraint: NSLayoutConstraint!
var activityIndicator:UIActivityIndicatorView!
var originalTopMargin:CGFloat!
@IBOutlet var txtEvent: UITextField!
@IBOutlet var txtPrice: UITextField!
@IBOutlet var txtTax: UITextField!
@IBOutlet var txtTip: UITextField!
@IBOutlet var pickerView: UIPickerView!
@IBOutlet var camerabutton: UIButton!
var viewController: ViewController!
var dataSource = ["Food", "Personal", "Travel", "Transportation", "Business", "Entertainment", "Other"]
var val: String = ""
var str: String = ""
override func viewDidLoad() {
super.viewDidLoad()
val = dataSource[0]
self.pickerView.dataSource = self;
self.pickerView.delegate = self;
self.view.backgroundColor = UIColor(red: CGFloat(255)/255, green: CGFloat(224)/255, blue: CGFloat(193)/255, alpha: 0.99);
}
@IBAction func btnAddEntry(sender : UIButton){
//add record
var todaysDate: NSDate = NSDate()
var dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "M-d-yyyy"// HH:mm"
var DateInFormat: String = dateFormatter.stringFromDate(todaysDate)
//entryMgr.addEntry(txtEvent.text, category: val, price: txtPrice.text, tax: txtTax.text, tip: txtTip.text, date: DateInFormat)
// Method created by Amanda on 7/1/15
// Copyright (c) 2015 Hip Hip Array. All rights reserved.
var startIndex = advance(txtPrice.text.startIndex, 0)
var endIndex = advance(txtPrice.text.endIndex, 0)
var range = startIndex..<endIndex
var myNewString = txtPrice.text.substringWithRange(range)
entryMgr.total = entryMgr.total + (myNewString as NSString).doubleValue
self.subTotal(false)
viewController.label.text = "Total: $"+entryMgr.total.description
//dismiss keyboard and reset fields
saveName(txtEvent.text, category: val, price: txtPrice.text, tax: txtTax.text, tip: txtTip.text, date: DateInFormat)
entryMgr.saveName()
self.view.endEditing(true)
txtEvent.text = ""
val = dataSource[0]
txtPrice.text = ""
txtTax.text = ""
txtTip.text = ""
}
func saveName(event: String, category: String, price: String, tax: String, tip: String, date: String) {
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
//2
let entity = NSEntityDescription.entityForName("Entry",
inManagedObjectContext:
managedContext)
let entry = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext:managedContext)
//3
entry.setValue(event, forKey: "event")
entry.setValue(price, forKey: "price")
entry.setValue(category, forKey: "category")
entry.setValue(tax, forKey: "tax")
entry.setValue(tip, forKey: "tip")
entry.setValue(date, forKey: "date")
//4
var error: NSError?
if !managedContext.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
//5
entryMgr.entries.append(entry)
}
func textFieldDidBeginEditing(textField: UITextField) { // became first responder
//move textfields up
let myScreenRect: CGRect = UIScreen.mainScreen().bounds
let keyboardHeight : CGFloat = 216
UIView.beginAnimations( "animateView", context: nil)
var movementDuration: NSTimeInterval = 0.35
var needToMove: CGFloat = 0
var frame : CGRect = self.view.frame
if (textField.frame.origin.y + textField.frame.size.height + /*self.navigationController.navigationBar.frame.size.height + */UIApplication.sharedApplication().statusBarFrame.size.height > (myScreenRect.size.height - keyboardHeight)) {
needToMove = (textField.frame.origin.y + textField.frame.size.height + /*self.navigationController.navigationBar.frame.size.height +*/ UIApplication.sharedApplication().statusBarFrame.size.height) - (myScreenRect.size.height - keyboardHeight) + textField.frame.size.height
}
frame.origin.y = -needToMove
self.view.frame = frame
UIView.commitAnimations()
}
func textFieldDidEndEditing(textField: UITextField) {
//move textfields back down
UIView.beginAnimations( "animateView", context: nil)
var movementDuration:NSTimeInterval = 0.35
var frame : CGRect = self.view.frame
frame.origin.y = 0
self.view.frame = frame
UIView.commitAnimations()
}
func DismissKeyboard(){
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dataSource.count;
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return dataSource[row]
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent!){
self.view.endEditing(true)
}
// sFunction written by Mira
// Copyright (c) 2015 Hip Hip Array. All rights reserved.
func textFieldShouldReturn(textField: UITextField) -> Bool{
if (textField === txtEvent)
{
txtEvent.resignFirstResponder()
pickerView.becomeFirstResponder()
}
if (textField === txtPrice)
{
txtPrice.resignFirstResponder()
txtTax.becomeFirstResponder()
}
if (textField === txtTax)
{
txtTax.resignFirstResponder()
txtTip.becomeFirstResponder()
}
if (textField === txtTip)
{
txtTip.resignFirstResponder()
}
return true
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
// Designed by Maitreyee, Lauren on 7/1/15
// Copyright (c) 2015 Hip Hip Array[]. All rights reserved.
if(row == 0)
{
self.view.backgroundColor = UIColor(red: CGFloat(255)/255, green: CGFloat(224)/255, blue: CGFloat(193)/255, alpha: 0.99999999999999);
}
else if(row == 1)
{
self.view.backgroundColor = UIColor(red: CGFloat(193)/255, green: CGFloat(224)/255, blue: CGFloat(255)/255, alpha: 0.99999999999999);
}
else if(row == 2)
{
self.view.backgroundColor = UIColor(red: CGFloat(193)/255, green: CGFloat(255)/255, blue: CGFloat(193)/255, alpha: 0.99999999999999);
}
else if(row == 3)
{
self.view.backgroundColor = UIColor(red: CGFloat(224)/255, green: CGFloat(193)/255, blue: CGFloat(255)/255, alpha: 0.99999999999999);
}
else if(row == 4)
{
self.view.backgroundColor = UIColor(red: CGFloat(193)/255, green: CGFloat(255)/255, blue: CGFloat(255)/255, alpha: 0.99999999999999);
}
else if(row == 5)
{
self.view.backgroundColor = UIColor(red: CGFloat(255)/255, green: CGFloat(127)/255, blue: CGFloat(127)/255, alpha: 0.99999999999999);
}
else if(row == 6)
{
self.view.backgroundColor = UIColor(red: CGFloat(254)/255, green: CGFloat(254)/255, blue: CGFloat(199)/255, alpha: 0.99999999999999);
}
val = dataSource[row]
}
func subTotal(subtract: Bool){
var startIndex = advance(txtPrice.text.startIndex, 0)
var endIndex = advance(txtPrice.text.endIndex, 0)
var range = startIndex..<endIndex
var myNewString = txtPrice.text.substringWithRange(range)
var subtractVal = (myNewString as NSString).doubleValue
if(subtract){
subtractVal = 0-subtractVal;
}
if(val == "Food"){
entryMgr.tFood = entryMgr.tFood + subtractVal
}
if(val == "Transportation"){
entryMgr.tTran = entryMgr.tTran + subtractVal
}
if(val == "Other"){
entryMgr.tOthe = entryMgr.tOthe + subtractVal
}
if(val == "Business"){
entryMgr.tBusi = entryMgr.tBusi + subtractVal
}
if(val == "Personal"){
entryMgr.tPers = entryMgr.tPers + subtractVal
}
if(val == "Entertainment"){
entryMgr.tEnte = entryMgr.tEnte + subtractVal
}
if(val == "Travel"){
entryMgr.tTrav = entryMgr.tTrav + subtractVal
}
}
@IBAction func takePhoto(sender: AnyObject) {
// 1
view.endEditing(true)
moveViewDown()
// 2
let imagePickerActionSheet = UIAlertController(title: "Snap/Upload Photo",
message: nil, preferredStyle: .ActionSheet)
// 3
if UIImagePickerController.isSourceTypeAvailable(.Camera) {
let cameraButton = UIAlertAction(title: "Take Photo",
style: .Default) { (alert) -> Void in
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera
self.presentViewController(imagePicker,
animated: true,
completion: nil)
}
imagePickerActionSheet.addAction(cameraButton)
}
// 4
let libraryButton = UIAlertAction(title: "Choose Existing",
style: .Default) { (alert) -> Void in
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .PhotoLibrary
self.presentViewController(imagePicker,
animated: true,
completion: nil)
}
imagePickerActionSheet.addAction(libraryButton)
// 5
let cancelButton = UIAlertAction(title: "Cancel",
style: .Cancel) { (alert) -> Void in
}
imagePickerActionSheet.addAction(cancelButton)
// 6
presentViewController(imagePickerActionSheet, animated: true,
completion: nil)
}
@IBAction func swapText(sender: AnyObject) {
// 1
//if textView.text.isEmpty {
//return
//}
// 2
/*textView.text =
textView.text.stringByReplacingOccurrencesOfString(findTextField.text,
withString: replaceTextField.text, options: nil, range: nil)
// 3
findTextField.text = nil
replaceTextField.text = nil*/
// 4
view.endEditing(true)
moveViewDown()
}
@IBAction func sharePoem(sender: AnyObject) {
// 1
//if textView.text.isEmpty {
//return
//}
// 2
//let activityViewController = UIActivityViewController(activityItems:
//[textView.text], applicationActivities: nil)
// 3
let excludeActivities = [
UIActivityTypeAssignToContact,
UIActivityTypeSaveToCameraRoll,
UIActivityTypeAddToReadingList,
UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo]
//activityViewController.excludedActivityTypes = excludeActivities
// 4
//presentViewController(activityViewController, animated: true,
//completion: nil)
}
func scaleImage(image: UIImage, maxDimension: CGFloat) -> UIImage {
//do image contrast and filtering here
var scaledSize = CGSizeMake(maxDimension, maxDimension)
var scaleFactor:CGFloat
if image.size.width > image.size.height {
scaleFactor = image.size.height / image.size.width
scaledSize.width = maxDimension
scaledSize.height = scaledSize.width * scaleFactor
} else {
scaleFactor = image.size.width / image.size.height
scaledSize.height = maxDimension
scaledSize.width = scaledSize.height * scaleFactor
}
UIGraphicsBeginImageContext(scaledSize)
image.drawInRect(CGRectMake(0, 0, scaledSize.width, scaledSize.height))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
// Activity Indicator methods
func addActivityIndicator() {
activityIndicator = UIActivityIndicatorView(frame: view.bounds)
activityIndicator.activityIndicatorViewStyle = .WhiteLarge
activityIndicator.backgroundColor = UIColor(white: 0, alpha: 0.25)
activityIndicator.startAnimating()
view.addSubview(activityIndicator)
}
func removeActivityIndicator() {
activityIndicator.removeFromSuperview()
activityIndicator = nil
}
// The remaining methods handle the keyboard resignation/
// move the view so that the first responders aren't hidden
func moveViewUp() {
/* if topMarginConstraint.constant != originalTopMargin {
return
}
topMarginConstraint.constant -= 135
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
})*/
}
func moveViewDown() {
/*if topMarginConstraint.constant == originalTopMargin {
return
}
topMarginConstraint.constant = originalTopMargin
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
})*/
}
@IBAction func backgroundTapped(sender: AnyObject) {
view.endEditing(true)
moveViewDown()
}
func performImageRecognition(image: UIImage) {
// 1
let tesseract = G8Tesseract()
// 2
tesseract.language = "eng+fra"
// 3
tesseract.engineMode = .TesseractCubeCombined
// 4
tesseract.pageSegmentationMode = .Auto
// 5
tesseract.maximumRecognitionTime = 60.0
// 6
tesseract.image = image.g8_blackAndWhite()
tesseract.recognize()
// 7
//textView.text = tesseract.recognizedText
//textView.editable = true
str = tesseract.recognizedText
processText()
// 8
removeActivityIndicator()
}
func processText(){
if(!str.isEmpty){
var name: String = ""
var ind: Int = 0
while ind<count(str) && str[ind] == "\n" || str[ind] == " " {
ind = ind+1
}
while ind<count(str) && str[ind] != "\n" {
name = name+str[ind]
ind = ind+1
}
txtEvent.text = name
if((str.lowercaseString as NSString).containsString("total")){
var range = str.lowercaseString.rangeOfString("total", options: .BackwardsSearch)
var index: Int = distance(str.startIndex, range!.startIndex)
var price: String = ""
var found: Bool = false
let myArrayFromString = Array(str)
while index<count(str) && !found {
var num = str[index].toInt()
if num != nil {
found = true
}
else{
index = index+1
}
}
while index<count(str) {
var num = str[index].toInt()
if str[index]=="." || num != nil {
price = price+str[index]
}
else{
break
}
index = index + 1
}
txtPrice.text = price
if price=="" {
txtPrice.text = "0.00"
}
}
else{
txtPrice.text = "0.00"
}
if((str.lowercaseString as NSString).containsString("tip")){
var range = str.lowercaseString.rangeOfString("tip", options: .BackwardsSearch)
var index: Int = distance(str.startIndex, range!.startIndex)
var price: String = ""
var found: Bool = false
let myArrayFromString = Array(str)
while index<count(str) && !found {
var num = str[index].toInt()
if num != nil {
found = true
}
else{
index = index+1
}
}
while index<count(str) {
var num = str[index].toInt()
if str[index]=="." || num != nil {
price.append(myArrayFromString[index])
}
else{
break
}
index = index + 1
}
txtTip.text = price
if price=="" {
txtTip.text = "0.00"
}
}
else{
txtTip.text = "0.00"
}
if((str.lowercaseString as NSString).containsString("tax")){
var range = str.lowercaseString.rangeOfString("tax", options: .BackwardsSearch)
var index: Int = distance(str.startIndex, range!.startIndex)
var price: String = ""
var found: Bool = false
let myArrayFromString = Array(str)
while index<count(str) && !found {
var num = str[index].toInt()
if num != nil {
found = true
}
else{
index = index+1
}
}
var number: Bool = false
while index<count(str) {
var num = str[index].toInt()
if str[index]=="." || num != nil {
price.append(myArrayFromString[index])
}
else{
break
}
index = index + 1
}
txtTax.text = price
if price=="" {
txtTax.text = "0.00"
}
}
else{
txtTax.text = "0.00"
}
}
else{
txtPrice.text = "0.00"
txtTax.text = "0.00"
txtTip.text = "0.00"
}
}
}
extension AddEntry: UITextFieldDelegate {
/*func textFieldDidBeginEditing(textField: UITextField) {
moveViewUp()
}*/
@IBAction func textFieldEndEditing(sender: AnyObject) {
view.endEditing(true)
moveViewDown()
}
func textViewDidBeginEditing(textView: UITextView) {
moveViewDown()
}
}
extension AddEntry: UIImagePickerControllerDelegate {
func imagePickerController(picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let selectedPhoto = info[UIImagePickerControllerOriginalImage] as! UIImage
let scaledImage = scaleImage(selectedPhoto, maxDimension: 640)
addActivityIndicator()
dismissViewControllerAnimated(true, completion: {
self.performImageRecognition(scaledImage)
})
}
}
extension String {
subscript (i: Int) -> Character {
return self[advance(self.startIndex, i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
subscript (r: Range<Int>) -> String {
return substringWithRange(Range(start: advance(startIndex, r.startIndex), end: advance(startIndex, r.endIndex)))
}
}
| mit | 589a5b57fee60555863d89ba3780d1eb | 33.740984 | 284 | 0.553322 | 5.200491 | false | false | false | false |
roambotics/swift | test/Constraints/casts_swift6.swift | 4 | 6012 | // RUN: %target-typecheck-verify-swift -enable-objc-interop -swift-version 6
// -swift-version 6 is currently asserts-only
// REQUIRES: asserts
func id<T>(_ x: T) -> T { x }
func ohno<T>(_ x: T) -> T? { nil }
// Swift 6 version of the test in casts.swift
func test_compatibility_coercions(_ arr: [Int], _ optArr: [Int]?, _ dict: [String: Int], _ set: Set<Int>, _ i: Int, _ stringAnyDict: [String: Any]) {
// These have always been fine.
_ = arr as [Any]?
_ = dict as [String: Int]?
_ = set as Set<Int>
// These have always been errors.
_ = arr as [String] // expected-error {{cannot convert value of type '[Int]' to type '[String]' in coercion}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}}
_ = dict as [String: String] // expected-error {{cannot convert value of type '[String : Int]' to type '[String : String]' in coercion}}
// expected-note@-1 {{arguments to generic parameter 'Value' ('Int' and 'String') are expected to be equal}}
_ = dict as [String: String]? // expected-error {{'[String : Int]' is not convertible to '[String : String]?'}}
// expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{12-14=as!}}
_ = (dict as [String: Int]?) as [String: Int] // expected-error {{value of optional type '[String : Int]?' must be unwrapped to a value of type '[String : 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'}}
_ = set as Set<String> // expected-error {{cannot convert value of type 'Set<Int>' to type 'Set<String>' in coercion}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}}
// Make sure we error on the following in Swift 6 mode.
_ = id(arr) as [String] // expected-error {{conflicting arguments to generic parameter 'T' ('[Int]' vs. '[String]')}}
_ = (arr ?? []) as [String] // expected-error {{conflicting arguments to generic parameter 'T' ('[String]' vs. '[Int]')}}
_ = (arr ?? [] ?? []) as [String] // expected-error {{conflicting arguments to generic parameter 'T' ('[String]' vs. '[Int]')}}
// expected-error@-1{{conflicting arguments to generic parameter 'T' ('[String]' vs. '[Int]')}}
_ = (optArr ?? []) as [String] // expected-error {{conflicting arguments to generic parameter 'T' ('[Int]' vs. '[String]'}}
_ = (arr ?? []) as [String]? // expected-error {{'[Int]' is not convertible to '[String]?'}}
// expected-note@-1 {{did you mean to use 'as!' to force downcast?}}
_ = (arr ?? []) as [String?]? // expected-error {{'[Int]' is not convertible to '[String?]?'}}
// expected-note@-1 {{did you mean to use 'as!' to force downcast?}}
_ = (arr ?? []) as [String??]?? // expected-error {{'[Int]' is not convertible to '[String??]??'}}
// expected-note@-1 {{did you mean to use 'as!' to force downcast?}}
_ = (dict ?? [:]) as [String: String?]? // expected-error {{'[String : Int]' is not convertible to '[String : String?]?'}}
// expected-note@-1 {{did you mean to use 'as!' to force downcast?}}
_ = (set ?? []) as Set<String>?? // expected-error {{'Set<Int>' is not convertible to 'Set<String>??'}}
// expected-note@-1 {{did you mean to use 'as!' to force downcast?}}
_ = ohno(ohno(ohno(arr))) as [String] // expected-error {{cannot convert value of type '[Int]???' to type '[String]' in coercion}}
_ = ohno(ohno(ohno(arr))) as [Int] // expected-error {{cannot convert value of type '[Int]???' to type '[Int]' in coercion}}
_ = ohno(ohno(ohno(Set<Int>()))) as Set<String> // expected-error {{cannot convert value of type 'Set<Int>???' to type 'Set<String>' in coercion}}
_ = ohno(ohno(ohno(["": ""]))) as [Int: String] // expected-error {{cannot convert value of type '[String : String]???' to type '[Int : String]' in coercion}}
_ = ohno(ohno(ohno(dict))) as [String: Int] // expected-error {{cannot convert value of type '[String : Int]???' to type '[String : Int]' in coercion}}
// In this case the array literal can be inferred to be [String], so totally
// valid.
_ = ([] ?? []) as [String] // expected-warning {{left side of nil coalescing operator '??' has non-optional type '[String]', so the right side is never used}}
_ = (([] as Optional) ?? []) as [String]
// The array can also be inferred to be [Any].
_ = ([] ?? []) as Array // expected-warning {{left side of nil coalescing operator '??' has non-optional type '[Any]', so the right side is never used}}
// expected-warning@-1 {{empty collection literal requires an explicit type}}
// Cases from rdar://88334481
typealias Magic<T> = T
_ = [i] as [String] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
_ = [i] as Magic as [String] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
_ = ([i]) as Magic as [String] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
_ = [i: i] as [String: Any] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
_ = ([i: i]) as [String: Any] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
_ = [i: stringAnyDict] as [String: Any] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
_ = [i].self as Magic as [String] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
_ = (try [i]) as Magic as [String] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
// expected-warning@-1 {{no calls to throwing functions occur within 'try' expression}}
// These are wrong, but make sure we don't warn about the value cast always succeeding.
_ = [i: i] as! [String: Any]
_ = [i: stringAnyDict] as! [String: Any]
}
| apache-2.0 | 9a8493c6cf42cd98ffd80e95e0147f5e | 76.076923 | 164 | 0.638224 | 3.686082 | false | false | false | false |
silt-lang/silt | Sources/InnerCore/IRGenTuple.swift | 1 | 8186 | /// IRGenTuple.swift
///
/// Copyright 2019, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
import Seismography
import LLVM
/// Provides type information for a tuple of loadable values.
///
/// A tuple of loadable values is itself loadable. All operations delegate
/// to the underlying loadable fields, and adjust member offsets accordingly.
final class LoadableTupleTypeInfo: TupleTypeInfo, LoadableTypeInfo {
let llvmType: IRType
let fixedSize: Size
let fixedAlignment: Alignment
var isKnownEmpty: Bool {
return self.fixedSize == .zero
}
let fields: [RecordField]
let staticExplosionSize: Int
init(_ fields: [RecordField], _ explosionSize: Int,
_ storageStype: IRType, _ size: Size, _ align: Alignment) {
self.fields = fields
self.staticExplosionSize = explosionSize
self.llvmType = storageStype
self.fixedSize = size
self.fixedAlignment = align
}
func explosionSize() -> Int {
return self.staticExplosionSize
}
func copy(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) {
for field in self.fields {
guard let layout = field.layout.typeInfo as? LoadableTypeInfo else {
fatalError()
}
layout.copy(IGF, src, dest)
}
}
func consume(_ IGF: IRGenFunction, _ explosion: Explosion) {
for field in self.fields {
guard let layout = field.layout.typeInfo as? LoadableTypeInfo else {
fatalError()
}
layout.consume(IGF, explosion)
}
}
func packIntoPayload(_ IGF: IRGenFunction, _ payload: Payload,
_ source: Explosion, _ startOffset: Size) {
for field in self.fields {
guard !field.isEmpty else {
continue
}
let offset = field.fixedByteOffset + startOffset
guard let layout = field.layout.typeInfo as? LoadableTypeInfo else {
fatalError()
}
layout.packIntoPayload(IGF, payload, source, offset)
}
}
func unpackFromPayload(_ IGF: IRGenFunction, _ payload: Payload,
_ destination: Explosion, _ startOffset: Size) {
for field in self.fields {
guard !field.isEmpty else {
continue
}
let offset = field.fixedByteOffset + startOffset
guard let layout = field.layout.typeInfo as? LoadableTypeInfo else {
fatalError()
}
layout.unpackFromPayload(IGF, payload, destination, offset)
}
}
func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) {
return IGF.GR.emitDestroyCall(type, addr)
}
func assignWithCopy(_ IGF: IRGenFunction,
_ dest: Address, _ src: Address, _ type: GIRType) {
return IGF.GR.emitAssignWithCopyCall(type, dest, src)
}
func buildAggregateLowering(_ IGM: IRGenModule,
_ builder: AggregateLowering.Builder,
_ offset: Size) {
for field in self.fields {
let fieldOffset = offset + field.fixedByteOffset
guard let layout = field.layout.typeInfo as? LoadableTypeInfo else {
fatalError()
}
layout.buildAggregateLowering(IGM, builder, fieldOffset)
}
}
func reexplode(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Explosion) {
for field in fields {
guard let layout = field.layout.typeInfo as? LoadableTypeInfo else {
fatalError()
}
layout.reexplode(IGF, src, dest)
}
}
func initialize(_ IGF: IRGenFunction, _ from: Explosion, _ addr: Address) {
for field in fields {
guard !field.isEmpty else {
continue
}
let fieldAddr = field.projectAddress(IGF, addr)
guard let layout = field.layout.typeInfo as? LoadableTypeInfo else {
fatalError()
}
layout.initialize(IGF, from, fieldAddr)
}
}
func assign(_ IGF: IRGenFunction, _ src: Explosion, _ dest: Address) {
for field in fields {
guard !field.isEmpty else {
continue
}
guard let layout = field.layout.typeInfo as? LoadableTypeInfo else {
fatalError()
}
layout.assign(IGF, src, dest)
}
}
func loadAsCopy(_ IGF: IRGenFunction, _ addr: Address, _ out: Explosion) {
for field in fields {
guard !field.isEmpty else {
continue
}
let fieldAddr = field.projectAddress(IGF, addr)
guard let layout = field.layout.typeInfo as? LoadableTypeInfo else {
fatalError()
}
layout.loadAsCopy(IGF, fieldAddr, out)
}
}
func loadAsTake(_ IGF: IRGenFunction, _ addr: Address, _ out: Explosion) {
for field in fields {
guard !field.isEmpty else {
continue
}
let fieldAddr = field.projectAddress(IGF, addr)
guard let layout = field.layout.typeInfo as? LoadableTypeInfo else {
fatalError()
}
layout.loadAsTake(IGF, fieldAddr, out)
}
}
func buildExplosionSchema(_ schema: Explosion.Schema.Builder) {
for field in fields {
field.layout.typeInfo.buildExplosionSchema(schema)
}
}
}
/// Provides type information for a tuple of fixed-size values.
///
/// A tuple of fixed-size values is itself a fixed-size value.
final class FixedTupleTypeInfo: TupleTypeInfo, FixedTypeInfo, IndirectTypeInfo {
let llvmType: IRType
let fixedSize: Size
let fixedAlignment: Alignment
let fields: [RecordField]
var isKnownEmpty: Bool {
return self.fixedSize == .zero
}
init(_ fields: [RecordField], _ storageStype: IRType,
_ size: Size, _ align: Alignment) {
self.fields = fields
self.llvmType = storageStype
self.fixedAlignment = align
self.fixedSize = size
}
func destroy(_ IGF: IRGenFunction, _ addr: Address, _ type: GIRType) {
guard let tupleTy = type as? TupleType else {
fatalError()
}
for (idx, field) in self.fields.enumerated() {
guard !field.isPOD else {
continue
}
field.layout.typeInfo.destroy(IGF, field.projectAddress(IGF, addr),
tupleTy.elements[idx])
}
}
func assignWithCopy(_ IGF: IRGenFunction,
_ dest: Address, _ src: Address, _ type: GIRType) {
guard let tupleTy = type as? TupleType else {
fatalError()
}
for (idx, field) in self.fields.enumerated() {
guard !field.isEmpty else {
continue
}
let destField = field.projectAddress(IGF, dest)
let srcField = field.projectAddress(IGF, src)
field.layout.typeInfo.assignWithCopy(IGF, destField, srcField,
tupleTy.elements[idx])
}
}
}
/// Provides type information for a tuple of runtime-sized values.
final class NonFixedTupleTypeInfo: TupleTypeInfo, WitnessSizedTypeInfo {
let llvmType: IRType
let alignment: Alignment
let fields: [RecordField]
init(_ fields: [RecordField], _ storageStype: IRType, _ align: Alignment) {
self.fields = fields
self.llvmType = storageStype
self.alignment = align
}
func dynamicOffsets(_ IGF: IRGenFunction, _ T: GIRType) -> DynamicOffsets? {
struct TupleNonFixedOffsets: DynamicOffsets {
let type: GIRType
func offsetForIndex(_ IGF: IRGenFunction, _ index: Int) -> IRValue {
let metadata = IGF.emitTypeMetadataRefForLayout(self.type)
let asTuple = IGF.B.buildBitCast(metadata,
type: IGF.IGM.tupleTypeMetadataPtrTy)
let slot = IGF.B.buildInBoundsGEP(asTuple,
type: IGF.IGM.tupleTypeMetadataTy,
indices: [
IGF.IGM.getSize(.zero), // (*tupleType)
IntType.int32.constant(3), // .Elements
IGF.IGM.getSize(Size(index)), // [index]
IntType.int32.constant(1), // .Offset
])
return IGF.B.buildLoad(slot,
type: IGF.IGM.tupleTypeMetadataTy,
alignment: IGF.IGM.getPointerAlignment(),
name: metadata.name + ".\(index).offset")
}
}
return TupleNonFixedOffsets(type: T)
}
}
| mit | 61b574f646f4d633fd1ad72196754149 | 29.544776 | 80 | 0.623015 | 4.417701 | false | false | false | false |
material-motion/motion-transitioning-objc | examples/FadeExample.swift | 2 | 2525 | /*
Copyright 2017-present The Material Motion Authors. All Rights Reserved.
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 MotionTransitioning
// This example demonstrates the minimal path to using a custom transition in Swift. See
// FadeTransition.swift for the custom transition implementation.
class FadeExampleViewController: ExampleViewController {
@objc func didTap() {
let modalViewController = ModalViewController()
// The transition controller is an associated object on all UIViewController instances that
// allows you to customize the way the view controller is presented. The primary API on the
// controller that you'll make use of is the `transition` property. Setting this property will
// dictate how the view controller is presented. For this example we've built a custom
// FadeTransition, so we'll make use of that now:
modalViewController.mdm_transitionController.transition = FadeTransition(target: .foreView)
// Note that once we assign the transition object to the view controller, the transition will
// govern all subsequent presentations and dismissals of that view controller instance. If we
// want to use a different transition (e.g. to use an edge-swipe-to-dismiss transition) then we
// can simply change the transition object before initiating the transition.
present(modalViewController, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: view.bounds)
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.textColor = .white
label.textAlignment = .center
label.text = "Tap to start the transition"
view.addSubview(label)
let tap = UITapGestureRecognizer(target: self, action: #selector(didTap))
view.addGestureRecognizer(tap)
}
override func exampleInformation() -> ExampleInfo {
return .init(title: type(of: self).catalogBreadcrumbs().last!,
instructions: "Tap to present a modal transition.")
}
}
| apache-2.0 | cbdab8ae2fc71d44e0f6569bd36cd4ac | 40.393443 | 99 | 0.752871 | 4.883946 | false | false | false | false |
DrGo/LearningSwift | PLAYGROUNDS/LSB_001_Intro.playground/section-2.swift | 2 | 766 | import UIKit
/*---------------------/
Basics
/---------------------*/
// This is a comment.
println("hello") // Another comment
/* A bigger
...
comment. */
/* Another
big
/* comment
here */
*/
// You can also import just submodules and features.
// Features can be var, func, class, struct, enum, protocol, or typealias
//import UIKit
import var Foundation.NSTimeIntervalSince1970
/*---------------------/
// Types
/---------------------*/
let word = "hello" // This is a String
let anotherWord : String = "hi"
let doubleNum = 3.14
let floatNum : Float = 3.14
typealias MyByte = UInt8
/*--------------------------/
// Bin and Hex, and Numbers
/--------------------------*/
let binary = 0b01010
let hex = 0xAB
let oct = 0o12
let someNumber = 42_012_123
| gpl-3.0 | 6dfd6ffb0a86a59335d2a2fe203101a1 | 15.297872 | 73 | 0.550914 | 3.754902 | false | false | false | false |
takev/DimensionsCAM | DimensionsCAM/double4x4_extra.swift | 1 | 2941 | // DimensionsCAM - A multi-axis tool path generator for a milling machine
// Copyright (C) 2015 Take Vos
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import simd
extension double4x4 {
static var identity: double4x4 {
return double4x4(rows:[
double4(1.0, 0.0, 0.0, 0.0),
double4(0.0, 1.0, 0.0, 0.0),
double4(0.0, 0.0, 1.0, 0.0),
double4(0.0, 0.0, 0.0, 1.0)
])
}
init(translate: double4) {
self.init(rows:[
double4(1.0, 0.0, 0.0, translate.x),
double4(0.0, 1.0, 0.0, translate.y),
double4(0.0, 0.0, 1.0, translate.z),
double4(0.0, 0.0, 0.0, translate.w)
])
}
public var description: String {
return String(sep:"",
"((\(self[0][0]), \(self[1][0]), \(self[2][0]), \(self[3][0])),",
" (\(self[0][1]), \(self[1][1]), \(self[2][1]), \(self[3][1])),",
" (\(self[0][2]), \(self[1][2]), \(self[2][2]), \(self[3][2])),",
" (\(self[0][3]), \(self[1][3]), \(self[2][3]), \(self[3][3])))"
)
}
}
func ×(lhs: double4x4, rhs: double4x4) -> double4x4 {
return lhs * rhs
}
func ×(lhs: double4x4, rhs: double4) -> double4 {
return lhs * rhs
}
func ×(lhs: double4x4, rhs: interval4) -> interval4 {
// double4x4 is in column-major order. So the first index selects which column, second index selects row.
let x0 = lhs[0][0] * rhs.x
let x1 = lhs[1][0] * rhs.y
let x2 = lhs[2][0] * rhs.z
let x3 = lhs[3][0] * rhs.w
let x = x0 + x1 + x2 + x3
let y0 = lhs[0][1] * rhs.x
let y1 = lhs[1][1] * rhs.y
let y2 = lhs[2][1] * rhs.z
let y3 = lhs[3][1] * rhs.w
let y = y0 + y1 + y2 + y3
let z0 = lhs[0][2] * rhs.x
let z1 = lhs[1][2] * rhs.y
let z2 = lhs[2][2] * rhs.z
let z3 = lhs[3][2] * rhs.w
let z = z0 + z1 + z2 + z3
let w0 = lhs[0][3] * rhs.x
let w1 = lhs[1][3] * rhs.y
let w2 = lhs[2][3] * rhs.z
let w3 = lhs[3][3] * rhs.w
let w = w0 + w1 + w2 + w3
return interval4(x, y, z, w)
}
public func ==(lhs: double4x4, rhs: double4x4) -> Bool {
for r in 0 ..< 4 {
if lhs[r] != rhs[r] {
return false
}
}
return true
}
public func !=(lhs: double4x4, rhs: double4x4) -> Bool {
return !(lhs == rhs)
}
| gpl-3.0 | a43e6fe8eb5a371213083acbdf344fe4 | 29.28866 | 109 | 0.541525 | 2.803435 | false | false | false | false |
gdelarosa/Safe-Reach | Safe Reach/CategoriesHomeVC.swift | 1 | 679 | //
// CategoriesHomeVC.swift
// Safe Reach
//
// Created by Gina De La Rosa on 1/8/17.
// Copyright © 2017 Gina De La Rosa. All rights reserved.
//
import UIKit
class CategoriesHomeVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Navigation Controller UI
let imageView = UIImageView(image: UIImage(named: "Triangle"))
imageView.contentMode = UIViewContentMode.scaleAspectFit
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
imageView.frame = titleView.bounds
titleView.addSubview(imageView)
self.navigationItem.titleView = titleView
}
}
| mit | 52aaaff5fe1f0f9b7cf689f5fc40f9a9 | 25.076923 | 80 | 0.660767 | 4.346154 | false | false | false | false |
bm842/TradingLibrary | Sources/PlaybackAccount.swift | 2 | 3377 | /*
The MIT License (MIT)
Copyright (c) 2016 Bertrand Marlier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
*/
import Foundation
public class PlaybackAccount: GenericAccount, Account
{
weak open var broker: Broker?
//var testBroker: PlaybackBroker! { return broker as? PlaybackBroker }
open var description: String
//let initBalance: Amount
open var currency: Currency
open var balance: Amount
//public var realizedProfitLoss: Amount = 0
//public var unrealizedProfitLoss: Amount = 0
//public var marginUsed: Amount = 0
//public var marginAvailable: Amount
open var marginRate: Double = 0.02
open var instruments: [Instrument]
open var openOrders: [Order] { return internalOpenOrders }
open var openTrades: [Trade] { return internalOpenTrades }
init(description: String, balance: Amount, currency: Currency)
{
self.broker = nil
self.description = description
//self.initBalance = balance
self.balance = balance
self.currency = currency
//self.marginAvailable = balance
self.instruments = [ ]
}
/*public func reset()
{
balance = initBalance
marginAvailable = initBalance
openTrades.removeAll()
//closedTrades.removeAll()
}*/
open func addInstrument(_ instrument: PlaybackInstrument)
{
instruments.append(instrument)
instrument.account = self
}
/*public func addInstrument(instrument: String,
displayName: String,
pip: Amount,
minTradeUnits: UInt32,
maxTradeUnits: UInt32,
precision: Amount,
base: Currency?,
quote: Currency) -> PlaybackInstrument
{
let instrument = PlaybackInstrument(instrument: instrument,
displayName: displayName,
pip: pip,
minTradeUnits: minTradeUnits,
maxTradeUnits: maxTradeUnits,
precision: precision,
base: base,
quote: quote)
instruments.append(instrument)
instrument.account = self
return instrument
}*/
open func refreshAccount(_ completion: @escaping (RequestStatus) -> ())
{
completion(PlaybackStatus.success)
}
open func refreshInstruments(_ completion: @escaping (RequestStatus) -> ())
{
completion(PlaybackStatus.success)
}
}
| mit | 450469f169624be5a6e0901275d664ce | 29.7 | 79 | 0.687296 | 4.852011 | false | false | false | false |
brentsimmons/Evergreen | Account/Sources/Account/Feed.swift | 1 | 787 | //
// Feed.swift
// Account
//
// Created by Maurice Parker on 11/15/19.
// Copyright © 2019 Ranchero Software, LLC. All rights reserved.
//
import Foundation
import RSCore
public enum ReadFilterType {
case read
case none
case alwaysRead
}
public protocol Feed: FeedIdentifiable, ArticleFetcher, DisplayNameProvider, UnreadCountProvider {
var account: Account? { get }
var defaultReadFilterType: ReadFilterType { get }
}
public extension Feed {
func readFiltered(readFilterEnabledTable: [FeedIdentifier: Bool]) -> Bool {
guard defaultReadFilterType != .alwaysRead else {
return true
}
if let feedID = feedID, let readFilterEnabled = readFilterEnabledTable[feedID] {
return readFilterEnabled
} else {
return defaultReadFilterType == .read
}
}
}
| mit | f1a460ee215953ab172dc58b07fe1fb6 | 19.153846 | 98 | 0.732824 | 3.742857 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/Views.swift | 1 | 7491 | //
// Views.swift
// Telegram
//
// Created by keepcoder on 07/06/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
class RestrictionWrappedView : Control {
let textView: TextView = TextView()
let text:String
required init(frame frameRect: NSRect) {
fatalError("init(coder:) has not been implemented")
}
init(_ text:String) {
self.text = text
super.init()
addSubview(textView)
textView.userInteractionEnabled = false
updateLocalizationAndTheme(theme: theme)
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
self.backgroundColor = theme.colors.background
let layout = TextViewLayout(.initialize(string: text, color: theme.colors.grayText, font: .normal(.text)), alignment: .center)
textView.update(layout)
textView.backgroundColor = theme.colors.background
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layout() {
super.layout()
textView.resize(frame.width - 40)
textView.center()
}
}
class VideoDurationView : View {
private var textNode:(TextNodeLayout, TextNode)
init(_ textNode:(TextNodeLayout, TextNode)) {
self.textNode = textNode
super.init()
self.backgroundColor = .clear
}
func updateNode(_ textNode:(TextNodeLayout, TextNode)) {
self.textNode = textNode
needsDisplay = true
}
override func setFrameSize(_ newSize: NSSize) {
super.setFrameSize(newSize)
}
func sizeToFit() {
setFrameSize(textNode.0.size.width + 10, textNode.0.size.height + 6)
needsDisplay = true
}
override func draw(_ layer: CALayer, in ctx: CGContext) {
super.draw(layer, in: ctx)
ctx.setFillColor(NSColor(0x000000, 0.8).cgColor)
ctx.round(frame.size, 4)
ctx.fill(bounds)
let f = focus(textNode.0.size)
textNode.1.draw(f, in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: backgroundColor)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
}
class CornerView : View {
var positionFlags: LayoutPositionFlags? {
didSet {
needsLayout = true
}
}
var didChangeSuperview: (()->Void)? = nil
override func viewDidMoveToSuperview() {
didChangeSuperview?()
}
override var backgroundColor: NSColor {
didSet {
layer?.backgroundColor = .clear
}
}
override func draw(_ layer: CALayer, in ctx: CGContext) {
if let positionFlags = positionFlags {
ctx.round(frame.size, positionFlags.isEmpty ? 0 : .cornerRadius, positionFlags: positionFlags)
}
ctx.setFillColor(backgroundColor.cgColor)
ctx.fill(bounds)
// if let positionFlags = positionFlags {
//
// let minx:CGFloat = 0, midx = frame.width/2.0, maxx = frame.width
// let miny:CGFloat = 0, midy = frame.height/2.0, maxy = frame.height
//
// ctx.move(to: NSMakePoint(minx, midy))
//
// var topLeftRadius: CGFloat = .cornerRadius
// var bottomLeftRadius: CGFloat = .cornerRadius
// var topRightRadius: CGFloat = .cornerRadius
// var bottomRightRadius: CGFloat = .cornerRadius
//
//
// if positionFlags.contains(.top) && positionFlags.contains(.left) {
// topLeftRadius = topLeftRadius * 3 + 2
// }
// if positionFlags.contains(.top) && positionFlags.contains(.right) {
// topRightRadius = topRightRadius * 3 + 2
// }
// if positionFlags.contains(.bottom) && positionFlags.contains(.left) {
// bottomLeftRadius = bottomLeftRadius * 3 + 2
// }
// if positionFlags.contains(.bottom) && positionFlags.contains(.right) {
// bottomRightRadius = bottomRightRadius * 3 + 2
// }
//
// ctx.addArc(tangent1End: NSMakePoint(minx, miny), tangent2End: NSMakePoint(midx, miny), radius: bottomLeftRadius)
// ctx.addArc(tangent1End: NSMakePoint(maxx, miny), tangent2End: NSMakePoint(maxx, midy), radius: bottomRightRadius)
// ctx.addArc(tangent1End: NSMakePoint(maxx, maxy), tangent2End: NSMakePoint(midx, maxy), radius: topLeftRadius)
// ctx.addArc(tangent1End: NSMakePoint(minx, maxy), tangent2End: NSMakePoint(minx, midy), radius: topRightRadius)
//
// ctx.closePath()
// ctx.clip()
// }
//
// ctx.setFillColor(backgroundColor.cgColor)
// ctx.fill(bounds)
//
}
}
class SearchTitleBarView : TitledBarView {
private let search:ImageButton = ImageButton()
private let calendar:ImageButton = ImageButton()
init(controller: ViewController, title:NSAttributedString, handler:@escaping() ->Void, calendarClick:(() ->Void)? = nil) {
super.init(controller: controller, title)
search.set(handler: { _ in
handler()
}, for: .Click)
addSubview(search)
addSubview(calendar)
calendar.autohighlight = false
calendar.scaleOnClick = true
calendar.set(handler: { _ in
calendarClick?()
}, for: .Click)
calendar.isHidden = calendarClick == nil
updateLocalizationAndTheme(theme: theme)
}
func updateSearchVisibility(_ searchVisible: Bool, calendarVisible: Bool = false, animated: Bool = true) {
if searchVisible {
self.search.isHidden = false
}
search.change(opacity: searchVisible ? 1 : 0, animated: animated, completion: { [weak self] _ in
self?.search.isHidden = !searchVisible
})
if calendarVisible {
self.calendar.isHidden = false
}
calendar.change(opacity: calendarVisible ? 1 : 0, animated: animated, completion: { [weak self] _ in
self?.calendar.isHidden = !calendarVisible
})
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
let theme = (theme as! TelegramPresentationTheme)
search.set(image: theme.icons.chatSearch, for: .Normal)
search.set(image: theme.icons.chatSearchActive, for: .Highlight)
_ = search.sizeToFit()
calendar.set(image: theme.icons.chatSearchCalendar, for: .Normal)
_ = calendar.sizeToFit()
backgroundColor = theme.colors.background
needsLayout = true
}
override func layout() {
super.layout()
search.centerY(x: frame.width - search.frame.width)
if search.isHidden {
calendar.centerY(x: frame.width - calendar.frame.width)
} else {
calendar.centerY(x: frame.width - search.frame.width - 10 - calendar.frame.width)
}
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-2.0 | 67d7a9beec2ce6d28308a35b5d443caa | 31.565217 | 134 | 0.606943 | 4.520217 | false | false | false | false |
BurntCaramel/Lantern | Lantern/BrowserPreferences.swift | 1 | 2177 | //
// BrowserState.swift
// Hoverlytics
//
// Created by Patrick Smith on 11/05/2015.
// Copyright (c) 2015 Burnt Caramel. All rights reserved.
//
import Foundation
import BurntFoundation
enum BrowserWidthChoice : Int {
case slimMobile = 1
case mediumMobile
case mediumTabletPortrait
case mediumTabletLandscape
case fullWidth
var value: CGFloat? {
switch self {
case .slimMobile:
return 320.0
case .mediumMobile:
return 480.0
case .mediumTabletPortrait:
return 768.0
case .mediumTabletLandscape:
return 1024.0
case .fullWidth:
return nil
}
}
var title: String {
switch self {
case .slimMobile:
return "320"
case .mediumMobile:
return "375"
case .mediumTabletPortrait:
return "768"
case .mediumTabletLandscape:
return "1024"
case .fullWidth:
return "Fluid"
}
/*switch self {
case .slimMobile:
return "Slim Mobile (iPhone 4)"
case .mediumMobile:
return "Medium Mobile (iPhone 6)"
case .mediumTabletPortrait:
return "Medium Tablet Portrait (iPad)"
case .mediumTabletLandscape:
return "Medium Tablet Landscape (iPad)"
case .fullWidth:
return "Full Width"
}(*/
}
}
extension BrowserWidthChoice : UserDefaultsChoiceRepresentable {
static var identifier = "browserPreferences.widthChoice"
static var defaultValue: BrowserWidthChoice = .fullWidth
}
private var ud = UserDefaults.standard
class BrowserPreferences {
enum Notification: String {
case widthChoiceDidChange = "BrowserPreferences.WidthChoiceDidChange"
var name : Foundation.Notification.Name {
return Foundation.Notification.Name(rawValue: rawValue)
}
}
private func notify(_ identifier: Notification, userInfo: [String:AnyObject]? = nil) {
let nc = NotificationCenter.default
nc.post(name: Notification.widthChoiceDidChange.name, object: self, userInfo: userInfo)
}
var widthChoice: BrowserWidthChoice = .fullWidth {
didSet {
ud.setChoice(widthChoice)
notify(.widthChoiceDidChange)
}
}
func updateFromDefaults() {
widthChoice = ud.choice(BrowserWidthChoice.self)
}
init() {
updateFromDefaults()
}
static var sharedBrowserPreferences = BrowserPreferences()
}
| apache-2.0 | c3fd9f1f146ce85447a22a996178543b | 20.135922 | 89 | 0.728525 | 3.652685 | false | false | false | false |
SnowdogApps/Project-Needs-Partner | CooperationFinder/Controllers/SDNewProjectTableViewController.swift | 1 | 8689 | //
// SDNewFileTableViewController.swift
// CooperationFinder
//
// Created by Rafal Kwiatkowski on 26.02.2015.
// Copyright (c) 2015 Snowdog. All rights reserved.
//
import UIKit
class SDNewProjectTableViewController: UITableViewController, UITextFieldDelegate, UITextViewDelegate, SDAddPositionViewControllerDelegate {
var project : Project = Project()
var onceToken : dispatch_once_t = 0
var sizingCell : SDPositionCell?
override func viewDidLoad() {
super.viewDidLoad()
self.project.commercial = false
let user : User = User()
let userId = Defaults["user_id"].string
user.id = userId
self.project.author = user
self.project.positions = []
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 4
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 0) {
return 1
} else if (section == 1) {
return 1
} else if (section == 2) {
return 1
} else if (section == 3) {
var counter = 1
if let kPos = self.project.positions {
counter += kPos.count
}
return counter
} else {
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : UITableViewCell = UITableViewCell()
if (indexPath.section == 0) {
let textfieldCell = tableView.dequeueReusableCellWithIdentifier("SDTextFieldCell", forIndexPath: indexPath) as! SDTextFieldCell
textfieldCell.textField?.text = self.project.name
textfieldCell.textField?.placeholder = "Project name"
textfieldCell.textField?.addTarget(self, action: "tfValueChanged:", forControlEvents: UIControlEvents.EditingChanged)
cell = textfieldCell
} else if (indexPath.section == 1) {
let textViewCell = tableView.dequeueReusableCellWithIdentifier("SDTextViewCell", forIndexPath: indexPath) as! SDTextViewCell
textViewCell.textView.delegate = self
textViewCell.textView.text = self.project.desc
cell = textViewCell
} else if (indexPath.section == 2) {
let switchCell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath: indexPath) as! SwitchCell
switchCell.titleLabel.text = "Commercial"
switchCell.switchView.setOn(self.project.commercial == true, animated: false)
switchCell.switchView.addTarget(self, action: "switchDidChange:", forControlEvents: UIControlEvents.ValueChanged)
cell = switchCell
} else if (indexPath.section == 3) {
var counter = 1
if let kPos = self.project.positions {
counter += kPos.count
}
if (indexPath.row == (counter - 1)) {
cell = tableView.dequeueReusableCellWithIdentifier("StandardCell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = "Add job offer"
} else {
let position = self.project.positions![indexPath.row]
var positionCell = tableView.dequeueReusableCellWithIdentifier("SDPositionCell", forIndexPath: indexPath) as! SDPositionCell
self.configurePositionCell(positionCell, position: position)
cell = positionCell
}
}
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if (section == 1) {
return "Description"
}
return nil
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var height : CGFloat = 44.0
var counter = 1
if let kPos = self.project.positions {
counter += kPos.count
}
if (indexPath.section == 1) {
height = 200.0
} else if (indexPath.section == 3 && indexPath.row < counter - 1) {
dispatch_once(&onceToken, { () -> Void in
self.sizingCell = tableView.dequeueReusableCellWithIdentifier("SDPositionCell") as? SDPositionCell
})
let position = self.project.positions![indexPath.row]
self.configurePositionCell(self.sizingCell!, position: position)
self.sizingCell?.bounds = CGRectMake(0.0, 0.0, tableView.bounds.size.width, 0.0)
self.sizingCell?.setNeedsLayout()
self.sizingCell?.layoutIfNeeded()
self.sizingCell?.titleLabel?.preferredMaxLayoutWidth = self.sizingCell!.titleLabel!.bounds.size.width
let size = self.sizingCell?.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
height = size!.height
}
return CGFloat(height)
}
func configurePositionCell(cell: SDPositionCell, position: Position) {
cell.titleLabel?.text = position.name
if let tags = position.tags {
cell.tagCloudView?.tags = tags
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var counter = 1
if let kPos = self.project.positions {
counter += kPos.count
}
if (indexPath.section == 3 && indexPath.row == counter - 1) {
self.performSegueWithIdentifier("AddPositionSegue", sender: self)
}
}
// 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?) {
if (segue.identifier == "AddPositionSegue") {
var destController = segue.destinationViewController as! SDAddPositionViewController
destController.delegate = self
}
}
func tfValueChanged(sender : UITextField) {
self.project.name = sender.text
}
func textViewDidChange(textView: UITextView) {
self.project.desc = textView.text
}
func switchDidChange(sender: UISwitch) {
self.project.commercial = sender.on
}
@IBAction func saveButtonTapped(sender: AnyObject) {
let validateResult = self.validateProject()
if (validateResult.error) {
let alert = UIAlertView(title: NSLocalizedString("Oops", comment:""), message: validateResult.errorText, delegate: nil, cancelButtonTitle: "OK")
alert.show()
} else {
Project.saveProject(self.project, completion: { (success) -> Void in
if (!success) {
let alertView = UIAlertView(title: "Oops", message: "Failed to create a project", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
} else {
self.dismissViewControllerAnimated(true, completion: nil)
}
})
}
}
@IBAction func cancelButtonTapped(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func unwindToNewProject(segue:UIStoryboardSegue) {
}
// MARK: SDAddPositionViewControllerDelegate
func setPosition(position: Position) {
self.project.positions?.append(position)
self.tableView.reloadData()
}
// MARK: Validation
func validateProject() -> (error: Bool, errorText: String?) {
var errorText = ""
var error = false
var nameEmpty = NSLocalizedString("Project name cannot be empty", comment: "")
if let name = self.project.name {
if (count(name) == 0) {
errorText += (nameEmpty + "\n")
error = true
}
} else {
errorText += (nameEmpty + "\n")
error = true
}
if (project.positions?.count == 0) {
errorText += NSLocalizedString("Add at least one job offer to the project", comment: "")
error = true
}
return (error, errorText)
}
}
| apache-2.0 | 69b7429619e83795305b9b6fad821016 | 34.904959 | 156 | 0.600299 | 5.373531 | false | false | false | false |
superk589/DereGuide | DereGuide/Card/Controller/SpreadImageViewController.swift | 2 | 2830 | //
// SpreadImageViewController.swift
// DereGuide
//
// Created by zzk on 2017/3/7.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
class SpreadImageViewController: UIViewController {
var imageView = SpreadImageView(frame: CGRect.zero)
var imageURL: URL!
private var statusBarHidden = false
override var prefersStatusBarHidden: Bool {
return statusBarHidden
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return .landscapeRight
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
statusBarHidden = true
setNeedsStatusBarAppearanceUpdate()
}
fileprivate var customPresentAnimator: SpreadImageViewAnimator = SpreadImageViewAnimator()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clear
// transitioningDelegate = self
view.addSubview(imageView)
imageView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
imageView.backgroundColor = UIColor.clear
let tap = UITapGestureRecognizer.init(target: self, action: #selector(handleTapGesture(_:)))
imageView.addGestureRecognizer(tap)
imageView.isUserInteractionEnabled = true
imageView.contentMode = .scaleAspectFit
imageView.setImage(with: imageURL, shouldShowIndicator: false)
let longPress = UILongPressGestureRecognizer.init(target: self, action: #selector(handleLongPressGesture(_:)))
imageView.addGestureRecognizer(longPress)
}
@objc func handleTapGesture(_ tap: UITapGestureRecognizer) {
if tap.state == .ended {
dismiss(animated: true, completion: nil)
}
}
@objc func handleLongPressGesture(_ longPress: UILongPressGestureRecognizer) {
if longPress.state == .began {
if let image = imageView.image {
// 作为被分享的内容 不能是可选类型 否则分享项不显示
let urlArray = [image]
let location = longPress.location(in: imageView)
let activityVC = UIActivityViewController.init(activityItems: urlArray, applicationActivities: nil)
let excludeActivitys:[UIActivity.ActivityType] = []
activityVC.excludedActivityTypes = excludeActivitys
activityVC.popoverPresentationController?.sourceView = imageView
activityVC.popoverPresentationController?.sourceRect = CGRect(x: location.x, y: location.y, width: 0, height: 0)
// 呈现分享界面
self.present(activityVC, animated: true, completion: nil)
}
}
}
}
| mit | df04216a2fe24ebb3274099d92064d1b | 34.987013 | 128 | 0.653916 | 5.713402 | false | false | false | false |
headione/criticalmaps-ios | CriticalMapsKit/Sources/Styleguide/EmptyStateView.swift | 1 | 2117 | import L10n
import SwiftUI
import SwiftUIHelpers
public struct EmptyState: Equatable {
public let icon: UIImage
public let text: String
public var message: NSAttributedString?
public init(
icon: UIImage,
text: String,
message: NSAttributedString? = nil
) {
self.icon = icon
self.text = text
self.message = message
}
}
public struct EmptyStateView: View {
public init(
emptyState: EmptyState,
buttonAction: (() -> Void)? = nil,
buttonText: String? = nil
) {
self.emptyState = emptyState
self.buttonAction = buttonAction
self.buttonText = buttonText
}
public let emptyState: EmptyState
public var buttonAction: (() -> Void)?
public var buttonText: String?
public var body: some View {
ZStack {
Color(.backgroundPrimary)
.ignoresSafeArea()
VStack(spacing: .grid(5)) {
Image(uiImage: emptyState.icon)
.imageScale(.large)
.accessibilityHidden(true)
VStack(spacing: .grid(2)) {
Text(emptyState.text)
.font(.titleOne)
if let message = emptyState.message {
Text(message)
.multilineTextAlignment(.center)
.font(.bodyOne)
.foregroundColor(Color(.textSecondary))
}
if buttonAction != nil {
Button(
action: buttonAction ?? {},
label: { Text(buttonText ?? "") }
)
.buttonStyle(CMButtonStyle())
.padding(.top, .grid(4))
.accessibilitySortPriority(1)
}
}
.padding(.horizontal, .grid(4))
}
.accessibilityElement(children: .contain)
.frame(maxHeight: .infinity, alignment: .center)
.foregroundColor(Color(.textPrimary))
}
}
}
struct EmptyStateView_Previews: PreviewProvider {
static var previews: some View {
Preview {
EmptyStateView(
emptyState: .init(
icon: Asset.twitterEmpty.image,
text: "No tweets atm",
message: .init(string: "")
)
)
}
}
}
| mit | 21219d96289106653743a38a0b72963e | 23.616279 | 54 | 0.575342 | 4.683628 | false | false | false | false |
headione/criticalmaps-ios | CriticalMapsKit/Sources/MapFeature/MapOverlayView.swift | 1 | 4163 | import ComposableArchitecture
import Foundation
import Styleguide
import SwiftUI
/// A view to overlay the map and indicate the next ride
public struct MapOverlayView<Content>: View where Content: View {
public struct ViewState: Equatable {
let isVisible: Bool
let isExpanded: Bool
public init(isVisible: Bool, isExpanded: Bool) {
self.isVisible = isVisible
self.isExpanded = isExpanded
}
}
@Environment(\.accessibilityReduceTransparency) var reduceTransparency
@Environment(\.accessibilityReduceMotion) var reduceMotion
let store: Store<ViewState, Never>
@ObservedObject var viewStore: ViewStore<ViewState, Never>
@State var isExpanded = false
@State var isVisible = false
let action: () -> Void
let content: () -> Content
public init(
store: Store<ViewState, Never>,
action: @escaping () -> Void,
@ViewBuilder content: @escaping () -> Content
) {
self.store = store
self.viewStore = ViewStore(store)
self.action = action
self.content = content
}
public var body: some View {
Button(
action: { action() },
label: {
HStack {
Image(uiImage: Asset.cm.image)
if isExpanded {
content()
.transition(
.asymmetric(
insertion: .opacity.animation(reduceMotion ? nil : .easeInOut(duration: 0.1).delay(0.2)),
removal: .opacity.animation(reduceMotion ? nil : .easeOut(duration: 0.15))
)
)
}
}
.padding(.horizontal, isExpanded ? 8 : 0)
}
)
.frame(minWidth: 50, minHeight: 50)
.foregroundColor(reduceTransparency ? .white : Color(.textPrimary))
.background(
Group {
if reduceTransparency {
RoundedRectangle(
cornerRadius: 12,
style: .circular
)
.fill(Color(.backgroundPrimary))
} else {
Blur()
.cornerRadius(12)
}
}
)
.transition(.scale.animation(reduceMotion ? nil : .easeOut(duration: 0.2)))
.onChange(of: viewStore.isExpanded, perform: { newValue in
let updateAction: () -> Void = { self.isExpanded = newValue }
reduceMotion ? updateAction() : withAnimation { updateAction() }
})
.onChange(of: viewStore.isVisible, perform: { newValue in
let updateAction: () -> Void = { self.isVisible = newValue }
reduceMotion ? updateAction() : withAnimation { updateAction() }
})
}
}
// MARK: Preview
struct MapOverlayView_Previews: PreviewProvider {
static var previews: some View {
Group {
MapOverlayView(
store: Store<MapFeatureState, Never>(
initialState: .init(riders: [], userTrackingMode: .init(userTrackingMode: .follow)),
reducer: .empty,
environment: ())
.actionless
.scope(state: { _ in
MapOverlayView.ViewState(isVisible: true, isExpanded: true)
}
),
action: {},
content: {
VStack {
Text("Next Ride")
Text("FRIDAY")
}
}
)
MapOverlayView(
store: Store<MapFeatureState, Never>(
initialState: .init(riders: [], userTrackingMode: .init(userTrackingMode: .follow)),
reducer: .empty,
environment: ())
.actionless
.scope(state: { _ in
MapOverlayView.ViewState(isVisible: true, isExpanded: true)
}
),
action: {},
content: {
VStack {
Text("Next Ride")
Text("FRIDAY")
}
}
)
MapOverlayView(
store: Store<MapFeatureState, Never>(
initialState: .init(riders: [], userTrackingMode: .init(userTrackingMode: .follow)),
reducer: .empty,
environment: ())
.actionless
.scope(state: { _ in
MapOverlayView.ViewState(isVisible: true, isExpanded: false)
}
),
action: {},
content: {}
)
}
}
}
| mit | b6cabf6d1b58244fadc76562006b5252 | 27.710345 | 107 | 0.558251 | 4.812717 | false | false | false | false |
Arcovv/CleanArchitectureRxSwift | RealmPlatform/Utility/RxUnits/RunLoopThreadScheduler.swift | 1 | 1755 | import Foundation
import RxSwift
final class RunLoopThreadScheduler: ImmediateSchedulerType {
private let thread: Thread
private let target: ThreadTarget
init(threadName: String) {
self.target = ThreadTarget()
self.thread = Thread(target: target,
selector: #selector(ThreadTarget.threadEntryPoint),
object: nil)
self.thread.name = threadName
self.thread.start()
}
func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
let disposable = SingleAssignmentDisposable()
var action: Action? = Action {
if disposable.isDisposed {
return
}
disposable.setDisposable(action(state))
}
action?.perform(#selector(Action.performAction),
on: thread,
with: nil,
waitUntilDone: false,
modes: [RunLoopMode.defaultRunLoopMode.rawValue])
let actionDisposable = Disposables.create {
action = nil
}
return Disposables.create(disposable, actionDisposable)
}
deinit {
thread.cancel()
}
}
private final class ThreadTarget: NSObject {
@objc fileprivate func threadEntryPoint() {
let runLoop = RunLoop.current
runLoop.add(NSMachPort(), forMode: RunLoopMode.defaultRunLoopMode)
runLoop.run()
}
}
private final class Action: NSObject {
private let action: () -> ()
init(action: @escaping () -> ()) {
self.action = action
}
@objc func performAction() {
action()
}
}
| mit | 04de37227d44255b155f7fe5dac79cb0 | 26.857143 | 109 | 0.565242 | 5.4 | false | false | false | false |
kickstarter/ios-ksapi | KsApi/models/Comment.swift | 1 | 1082 | import Argo
import Curry
import Runes
public struct Comment {
public let author: User
public let body: String
public let createdAt: TimeInterval
public let deletedAt: TimeInterval?
public let id: Int
}
extension Comment: Decodable {
public static func decode(_ json: JSON) -> Decoded<Comment> {
let create = curry(Comment.init)
let tmp = create
<^> json <| "author"
<*> json <| "body"
<*> json <| "created_at"
return tmp
<*> (json <|? "deleted_at" >>- decodePositiveTimeInterval)
<*> json <| "id"
}
}
extension Comment: Equatable {
}
public func == (lhs: Comment, rhs: Comment) -> Bool {
return lhs.id == rhs.id
}
// Decode a time interval so that non-positive values are coalesced to `nil`. We do this because the API
// sends back `0` when the comment hasn't been deleted, and we'd rather handle that value as `nil`.
private func decodePositiveTimeInterval(_ interval: TimeInterval?) -> Decoded<TimeInterval?> {
if let interval = interval, interval > 0.0 {
return .success(interval)
}
return .success(nil)
}
| apache-2.0 | 42e42853a7a260b3bbd672c6141bc0d7 | 26.74359 | 104 | 0.670055 | 3.96337 | false | false | false | false |
RobinChao/PageMenu | Demos/Demo 5/PageMenuDemoSegmentedControl/PageMenuDemoSegmentedControl/TestTableViewController.swift | 28 | 2904 | //
// TestTableViewController.swift
// NFTopMenuController
//
// Created by Niklas Fahl on 12/17/14.
// Copyright (c) 2014 Niklas Fahl. All rights reserved.
//
import UIKit
class TestTableViewController: UITableViewController {
var parentNavigationController : UINavigationController?
var namesArray : [String] = ["David Fletcher", "Charles Gray", "Timothy Jones", "Marie Turner", "Kim White"]
var photoNameArray : [String] = ["man8.jpg", "man2.jpg", "man3.jpg", "woman4.jpg", "woman1.jpg"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerNib(UINib(nibName: "FriendTableViewCell", bundle: nil), forCellReuseIdentifier: "FriendTableViewCell")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
println("\(self.title) page: viewWillAppear")
}
override func viewDidAppear(animated: Bool) {
self.tableView.showsVerticalScrollIndicator = false
super.viewDidAppear(animated)
self.tableView.showsVerticalScrollIndicator = true
println("favorites page: viewDidAppear")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return namesArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : FriendTableViewCell = tableView.dequeueReusableCellWithIdentifier("FriendTableViewCell") as! FriendTableViewCell
// Configure the cell...
cell.nameLabel.text = namesArray[indexPath.row]
cell.photoImageView.image = UIImage(named: photoNameArray[indexPath.row])
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 94.0
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.001
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var newVC : UIViewController = UIViewController()
newVC.view.backgroundColor = UIColor.purpleColor()
newVC.title = "Favorites"
parentNavigationController!.pushViewController(newVC, animated: true)
}
} | bsd-3-clause | 94371b187e76570ea5e9e5cfc1ee4e72 | 34 | 133 | 0.686639 | 5.357934 | false | false | false | false |
biohazardlover/i3rd | MaChérie/Core/PushAnimator.swift | 1 | 1384 | //
// PushAnimator.swift
// MaChérie
//
// Created by Leon Li on 2018/6/15.
// Copyright © 2018 Leon & Vane. All rights reserved.
//
import UIKit
class PushAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromView = transitionContext.view(forKey: .from) else { return }
guard let toView = transitionContext.view(forKey: .to) else { return }
transitionContext.containerView.addSubview(toView)
toView.frame = fromView.frame
toView.frame.origin.x += fromView.frame.width
// toView.alpha = 0
UIView.animate(
withDuration: transitionDuration(using: transitionContext),
delay: 0,
options: .curveEaseOut,
animations: {
toView.frame = fromView.frame
// toView.alpha = 1
fromView.frame.origin.x -= fromView.frame.width
// fromView.alpha = 0
},
completion: { finished in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
)
}
}
| mit | ccbb6d5d3b59de99771fee5a0ebad8bf | 31.904762 | 109 | 0.614327 | 5.335907 | false | false | false | false |
mozilla-mobile/firefox-ios | Storage/Cursor.swift | 2 | 2849 | // 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
/**
* Status results for a Cursor
*/
public enum CursorStatus {
case success
case failure
case closed
}
public protocol TypedCursor: Sequence {
associatedtype T
var count: Int { get }
var status: CursorStatus { get }
var statusMessage: String { get }
subscript(index: Int) -> T? { get }
func asArray() -> [T]
}
/**
* Provides a generic method of returning some data and status information about a request.
*/
open class Cursor<T>: TypedCursor {
open var count: Int { return 0 }
// Extra status information
open var status: CursorStatus
public var statusMessage: String
init(err: NSError) {
self.status = .failure
self.statusMessage = err.description
}
public init(status: CursorStatus = .success, msg: String = "") {
self.statusMessage = msg
self.status = status
}
// Collection iteration and access functions
open subscript(index: Int) -> T? { return nil }
open func asArray() -> [T] {
var acc = [T]()
acc.reserveCapacity(self.count)
for row in self {
// Shouldn't ever be nil -- that's to allow the generator or subscript to be
// out of range.
if let row = row {
acc.append(row)
}
}
return acc
}
open func makeIterator() -> AnyIterator<T?> {
var nextIndex = 0
return AnyIterator {
if nextIndex >= self.count || self.status != CursorStatus.success {
return nil
}
defer { nextIndex += 1 }
return self[nextIndex]
}
}
open func close() {
status = .closed
statusMessage = "Closed"
}
deinit {
if status != CursorStatus.closed {
close()
}
}
}
/*
* A cursor implementation that wraps an array.
*/
open class ArrayCursor<T>: Cursor<T> {
fileprivate var data: [T]
open override var count: Int {
if status != .success {
return 0
}
return data.count
}
public init(data: [T], status: CursorStatus, statusMessage: String) {
self.data = data
super.init(status: status, msg: statusMessage)
}
public convenience init(data: [T]) {
self.init(data: data, status: CursorStatus.success, statusMessage: "Success")
}
open override subscript(index: Int) -> T? {
if index >= data.count || index < 0 || status != .success { return nil }
return data[index]
}
override open func close() {
data = [T]()
super.close()
}
}
| mpl-2.0 | f5e9f380131757671215d03c93cc20c8 | 23.560345 | 91 | 0.576343 | 4.336377 | false | false | false | false |
JohnEstropia/RxCoreStore | Sources/RxDataStack+Setup.swift | 1 | 9101 | //
// RxDataStack+Setup.swift
// RxCoreStore
//
// Copyright © 2017 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import CoreStore
import RxCocoa
import RxSwift
// MARK: - Reactive
extension Reactive where Base == DataStack {
// MARK: -
/**
Reactive extension for `CoreStore.DataStack`'s `addStorage(...)` API. Asynchronously adds a `StorageInterface` to the stack.
```
dataStack.rx
.addStorage(InMemoryStore(configuration: "Config1"))
.subscribe(
onError: { (error) in
// ...
},
onSuccess: { (dataStack, storage) in
// ...
}
)
.disposed(by: disposeBag)
```
- parameter storage: the storage
- returns: An `Observable<RxStorageProgressType>` type. Note that the `StorageInterface` element of the observable may not always be the same instance as the parameter argument if a previous `StorageInterface` was already added at the same URL and with the same configuration.
*/
public func addStorage<T: StorageInterface>(_ storage: T) -> Observable<DataStack.RxStorageProgress<T>> {
return Observable<DataStack.RxStorageProgress<T>>.create(
{ (observable) -> Disposable in
self.base.addStorage(
storage,
completion: { (result) in
switch result {
case .success(let storage):
observable.onNext(DataStack.RxStorageProgress(storage: storage, progress: nil, isCompleted: true))
observable.onCompleted()
case .failure(let error):
observable.onError(error)
}
}
)
return Disposables.create()
}
)
}
/**
Reactive extension for `CoreStore.DataStack`'s `addStorage(...)` API. Asynchronously adds a `LocalStorage` to the stack. Migrations are also initiated by default. The observable element will be the `Progress` for migrations will be reported to the `onNext` element.
```
dataStack.rx
.addStorage(
SQLiteStore(
fileName: "core_data.sqlite",
configuration: "Config1"
)
)
.subscribe(
onNext: { (progress) in
print("\(round(progress.fractionCompleted * 100)) %") // 0.0 ~ 1.0
},
onError: { (error) in
// ...
},
onCompleted: {
// ...
}
)
.disposed(by: disposeBag)
```
- parameter storage: the local storage
- returns: An `Observable<RxStorageProgressType>` type. Note that the `LocalStorage` associated to the `RxStorageProgressType` may not always be the same instance as the parameter argument if a previous `LocalStorage` was already added at the same URL and with the same configuration.
*/
public func addStorage<T: LocalStorage>(_ storage: T) -> Observable<DataStack.RxStorageProgress<T>> {
return Observable<DataStack.RxStorageProgress<T>>.create(
{ (observable) in
var progress: Progress?
progress = self.base.addStorage(
storage,
completion: { (result) in
switch result {
case .success(let storage):
observable.onNext(DataStack.RxStorageProgress(storage: storage, progress: progress, isCompleted: true))
observable.onCompleted()
case .failure(let error):
observable.onError(error)
}
}
)
if let progress = progress {
let disposable = progress.rx
.observeWeakly(Double.self, #keyPath(Progress.fractionCompleted))
.subscribe(
onNext: { _ in
observable.onNext(DataStack.RxStorageProgress(storage: storage, progress: progress))
}
)
return Disposables.create([disposable])
}
else {
return Disposables.create()
}
}
)
}
}
// MARK: - RxStorageProgressType
/**
An `RxStorageProgressType` contains info on a `StorageInterface`'s setup progress.
- SeeAlso: DataStack.rx.addStorage(_:)
*/
public protocol RxStorageProgressType {
/**
The `StorageInterface` concrete type
*/
associatedtype StorageType: StorageInterface
/**
The `StorageInterface` instance
*/
var storage: StorageType { get }
/**
The `Progress` instance associated with a migration. Returns `nil` if no migration is needed.
*/
var progressObject: Progress? { get }
/**
Returns `true` if the storage was successfully added to the stack, `false` otherwise.
*/
var isCompleted: Bool { get }
/**
The fraction of the overall work completed by the migration. Returns a value between 0.0 and 1.0.
*/
var fractionCompleted: Double { get }
}
// MARK: - DataStack
extension DataStack {
// MARK: - RxStorageProgress
/**
An `RxStorageProgress` contains info on a `StorageInterface`'s setup progress.
- SeeAlso: DataStack.rx.addStorage(_:)
*/
public struct RxStorageProgress<T: StorageInterface>: RxStorageProgressType {
// MARK: RxStorageProgressType
public typealias StorageType = T
public let storage: T
public let progressObject: Progress?
public let isCompleted: Bool
public var fractionCompleted: Double {
return self.isCompleted
? 1
: (self.progressObject?.fractionCompleted ?? 0.0)
}
// MARK: Internal
internal init(storage: T, progress: Progress?, isCompleted: Bool = false) {
self.storage = storage
self.progressObject = progress
self.isCompleted = isCompleted
}
}
}
// MARK: - ObservableType where Element: RxStorageProgressType, Element.StorageType: LocalStorage
extension ObservableType where Element: RxStorageProgressType, Element.StorageType: LocalStorage {
/**
Filters an `Observable<RxStorageProgressType>` to send events only for `Progress` elements, which is sent only when a migration is required. This observable will not fire `onNext` events if no migration is required.
*/
public func filterMigrationProgress() -> Observable<Progress> {
return self.flatMap { (progress) -> Observable<Progress> in
if let progressObject = progress.progressObject {
return .just(progressObject)
}
return .empty()
}
}
/**
Filters an `Observable<RxStorageProgressType>` to fire only when the storage setup is complete.
*/
public func filterIsCompleted() -> Observable<Void> {
return self.filter({ $0.isCompleted }).map({ _ in })
}
/**
Maps an `Observable<RxStorageProgressType>` to an `Observable` with its `fractionCompleted` value.
*/
public func mapFractionCompleted() -> Observable<Double> {
return self.map({ $0.fractionCompleted })
}
}
| mit | dbf47c4f74b30e1709ed2545631ee5a2 | 33.8659 | 289 | 0.561319 | 5.606901 | false | false | false | false |
gregomni/swift | benchmark/utils/ArgParse.swift | 9 | 8901 | //===--- ArgParse.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
//
//===----------------------------------------------------------------------===//
#if os(Linux)
import Glibc
#elseif os(Windows)
import MSVCRT
#else
import Darwin
#endif
enum ArgumentError: Error {
case missingValue(String)
case invalidType(value: String, type: String, argument: String?)
case unsupportedArgument(String)
}
extension ArgumentError: CustomStringConvertible {
public var description: String {
switch self {
case let .missingValue(key):
return "missing value for '\(key)'"
case let .invalidType(value, type, argument):
return (argument == nil)
? "'\(value)' is not a valid '\(type)'"
: "'\(value)' is not a valid '\(type)' for '\(argument!)'"
case let .unsupportedArgument(argument):
return "unsupported argument '\(argument)'"
}
}
}
/// Type-checked parsing of the argument value.
///
/// - Returns: Typed value of the argument converted using the `parse` function.
///
/// - Throws: `ArgumentError.invalidType` when the conversion fails.
func checked<T>(
_ parse: (String) throws -> T?,
_ value: String,
argument: String? = nil
) throws -> T {
if let t = try parse(value) { return t }
var type = "\(T.self)"
if type.starts(with: "Optional<") {
let s = type.index(after: type.firstIndex(of: "<")!)
let e = type.index(before: type.endIndex) // ">"
type = String(type[s ..< e]) // strip Optional< >
}
throw ArgumentError.invalidType(
value: value, type: type, argument: argument)
}
/// Parser that converts the program's command line arguments to typed values
/// according to the parser's configuration, storing them in the provided
/// instance of a value-holding type.
class ArgumentParser<U> {
private var result: U
private var validOptions: [String] {
return arguments.compactMap { $0.name }
}
private var arguments: [Argument] = []
private let programName: String = {
// Strip full path from the program name.
let r = CommandLine.arguments[0].reversed()
let ss = r[r.startIndex ..< (r.firstIndex(of: "/") ?? r.endIndex)]
return String(ss.reversed())
}()
private var positionalArgs = [String]()
private var optionalArgsMap = [String : String]()
/// Argument holds the name of the command line parameter, its help
/// description and a rule that's applied to process it.
///
/// The the rule is typically a value processing closure used to convert it
/// into given type and storing it in the parsing result.
///
/// See also: addArgument, parseArgument
struct Argument {
let name: String?
let help: String?
let apply: () throws -> ()
}
/// ArgumentParser is initialized with an instance of a type that holds
/// the results of the parsing of the individual command line arguments.
init(into result: U) {
self.result = result
self.arguments += [
Argument(name: "--help", help: "show this help message and exit",
apply: printUsage)
]
}
private func printUsage() {
guard let _ = optionalArgsMap["--help"] else { return }
let space = " "
let maxLength = arguments.compactMap({ $0.name?.count }).max()!
let padded = { (s: String) in
" \(s)\(String(repeating:space, count: maxLength - s.count)) " }
let f: (String, String) -> String = {
"\(padded($0))\($1)"
.split(separator: "\n")
.joined(separator: "\n" + padded(""))
}
let positional = f("TEST", "name or number of the benchmark to measure;\n"
+ "use +/- prefix to filter by substring match")
let optional = arguments.filter { $0.name != nil }
.map { f($0.name!, $0.help ?? "") }
.joined(separator: "\n")
print(
"""
usage: \(programName) [--argument=VALUE] [TEST [TEST ...]]
positional arguments:
\(positional)
optional arguments:
\(optional)
""")
exit(0)
}
/// Parses the command line arguments, returning the result filled with
/// specified argument values or report errors and exit the program if
/// the parsing fails.
public func parse() -> U {
do {
try parseArgs() // parse the argument syntax
try arguments.forEach { try $0.apply() } // type-check and store values
return result
} catch let error as ArgumentError {
fputs("error: \(error)\n", stderr)
exit(1)
} catch {
fflush(stdout)
fatalError("\(error)")
}
}
/// Using CommandLine.arguments, parses the structure of optional and
/// positional arguments of this program.
///
/// We assume that optional switch args are of the form:
///
/// --opt-name[=opt-value]
///
/// with `opt-name` and `opt-value` not containing any '=' signs. Any
/// other option passed in is assumed to be a positional argument.
///
/// - Throws: `ArgumentError.unsupportedArgument` on failure to parse
/// the supported argument syntax.
private func parseArgs() throws {
// For each argument we are passed...
for arg in CommandLine.arguments[1..<CommandLine.arguments.count] {
// If the argument doesn't match the optional argument pattern. Add
// it to the positional argument list and continue...
if !arg.starts(with: "--") {
positionalArgs.append(arg)
continue
}
// Attempt to split it into two components separated by an equals sign.
let components = arg.split(separator: "=")
let optionName = String(components[0])
guard validOptions.contains(optionName) else {
throw ArgumentError.unsupportedArgument(arg)
}
var optionVal : String
switch components.count {
case 1: optionVal = ""
case 2: optionVal = String(components[1])
default:
// If we do not have two components at this point, we can not have
// an option switch. This is an invalid argument. Bail!
throw ArgumentError.unsupportedArgument(arg)
}
optionalArgsMap[optionName] = optionVal
}
}
/// Add a rule for parsing the specified argument.
///
/// Stores the type-erased invocation of the `parseArgument` in `Argument`.
///
/// Parameters:
/// - name: Name of the command line argument. E.g.: `--opt-arg`.
/// `nil` denotes positional arguments.
/// - property: Property on the `result`, to store the value into.
/// - defaultValue: Value used when the command line argument doesn't
/// provide one.
/// - help: Argument's description used when printing usage with `--help`.
/// - parser: Function that converts the argument value to given type `T`.
public func addArgument<T>(
_ name: String?,
_ property: WritableKeyPath<U, T>,
defaultValue: T? = nil,
help: String? = nil,
parser: @escaping (String) throws -> T? = { _ in nil }
) {
arguments.append(Argument(name: name, help: help)
{ try self.parseArgument(name, property, defaultValue, parser) })
}
/// Process the specified command line argument.
///
/// For optional arguments that have a value we attempt to convert it into
/// given type using the supplied parser, performing the type-checking with
/// the `checked` function.
/// If the value is empty the `defaultValue` is used instead.
/// The typed value is finally stored in the `result` into the specified
/// `property`.
///
/// For the optional positional arguments, the [String] is simply assigned
/// to the specified property without any conversion.
///
/// See `addArgument` for detailed parameter descriptions.
private func parseArgument<T>(
_ name: String?,
_ property: WritableKeyPath<U, T>,
_ defaultValue: T?,
_ parse: (String) throws -> T?
) throws {
if let name = name, let value = optionalArgsMap[name] {
guard !value.isEmpty || defaultValue != nil
else { throw ArgumentError.missingValue(name) }
result[keyPath: property] = (value.isEmpty)
? defaultValue!
: try checked(parse, value, argument: name)
} else if name == nil {
result[keyPath: property] = positionalArgs as! T
}
}
}
| apache-2.0 | 8b0c188cb2de645319e2db3adccbad7b | 35.479508 | 80 | 0.604651 | 4.459419 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio | uoregon-cis-399/assignment5/Assignment5/Source/Service/CatService.swift | 1 | 3092 | //
// CatService.swift
// Assignment5
//
import CoreData
class CatService {
// MARK: Data Access
func catCategories() -> NSFetchedResultsController<Category> {
let fetchRequest: NSFetchRequest<Category> = Category.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)]
return fetchedResultsController(for: fetchRequest)
}
func images(for category: Category) -> NSFetchedResultsController<Image> {
let fetchRequest: NSFetchRequest<Image> = Image.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "category == %@", category)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "orderIndex", ascending: true)]
return fetchedResultsController(for: fetchRequest)
}
// MARK: Private
func fetchedResultsController<T>(for fetchRequest: NSFetchRequest<T>) -> NSFetchedResultsController<T> {
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)
do {
try fetchedResultsController.performFetch()
}
catch let error {
fatalError("Could not perform fetch for fetched results controller: \(error)")
}
return fetchedResultsController
}
// MARK: Initialization
private init() {
persistentContainer = NSPersistentContainer(name: "Model")
persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in
let context = self.persistentContainer.viewContext
context.perform {
let categoryFetchRequest: NSFetchRequest<Category> = Category.fetchRequest()
let count = try! context.count(for: categoryFetchRequest)
guard count == 0 else {
return
}
let catDataPath = Bundle.main.path(forResource: "CatData", ofType: "plist")!
let catData = NSArray(contentsOfFile: catDataPath) as! Array<Dictionary<String, AnyObject>>
for catValues in catData {
let category = Category(context: context)
let title = catValues["CategoryTitle"] as! String
category.title = title
let imageValues = catValues["ImageNames"] as! Array<String>
for enumImageValues in imageValues.enumerated() {
let image = Image(context: context)
image.name = enumImageValues.element
image.orderIndex = Int32(enumImageValues.offset)
image.category = category
}
}
try! context.save()
}
})
}
// MARK: Private
private let persistentContainer: NSPersistentContainer
// MARK: Properties (Static)
static let shared = CatService()
}
| gpl-3.0 | 6947a6b74d2ce709939239f307a78acb | 37.65 | 189 | 0.608991 | 5.801126 | false | false | false | false |
ttlock/iOS_TTLock_Demo | Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/DFUServiceInitiator.swift | 2 | 22019 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CoreBluetooth
/**
The DFUServiceInitiator object should be used to send a firmware update to a remote BLE target compatible
with the Nordic Semiconductor's DFU (Device Firmware Update).
A `delegate`, `progressDelegate` and `logger` may be specified in order to receive status information.
*/
@objc public class DFUServiceInitiator : NSObject {
//MARK: - Internal variables
internal let centralManager : CBCentralManager
internal var target : CBPeripheral!
internal var file : DFUFirmware?
internal var queue : DispatchQueue
internal var delegateQueue : DispatchQueue
internal var progressDelegateQueue : DispatchQueue
internal var loggerQueue : DispatchQueue
//MARK: - Public variables
/**
The service delegate is an object that will be notified about state changes of the DFU Service.
Setting it is optional but recommended.
*/
@objc public weak var delegate: DFUServiceDelegate?
/**
An optional progress delegate will be called only during upload. It notifies about current upload
percentage and speed.
*/
@objc public weak var progressDelegate: DFUProgressDelegate?
/**
The logger is an object that should print given messages to the user. It is optional.
*/
@objc public weak var logger: LoggerDelegate?
/**
The selector object is used when the device needs to disconnect and start advertising with a different address
to avodi caching problems, for example after switching to the Bootloader mode, or during sending a firmware
containing a Softdevice (or Softdevice and Bootloader) and the Application.
After flashing the first part (containing the Softdevice), the device restarts in the
DFU Bootloader mode and may (since SDK 8.0.0) start advertising with an address incremented by 1.
The peripheral specified in the `init` may no longer be used as there is no device advertising with its address.
The DFU Service will scan for a new device and connect to the first device returned by the selector.
The default selecter returns the first device with the required DFU Service UUID in the advertising packet
(Secure or Legacy DFU Service UUID).
Ignore this property if not updating Softdevice and Application from one ZIP file or your
*/
@objc public var peripheralSelector: DFUPeripheralSelectorDelegate
/**
The number of packets of firmware data to be received by the DFU target before sending
a new Packet Receipt Notification.
If this value is 0, the packet receipt notification will be disabled by the DFU target.
Default value is 12.
PRNs are no longer required on iOS 11 and MacOS 10.13 or newer, but make sure
your device is able to be updated without. Old SDKs, before SDK 7 had very slow
memory management and could not handle packets that fast. If your device
is based on such SDK it is recommended to leave the default value.
Disabling PRNs on iPhone 8 with iOS 11.1.2 increased the speed from 1.7 KB/s to 2.7 KB/s
on DFU from SDK 14.1 where packet size is 20 bytes (higher MTU not supported yet).
On older versions, higher values of PRN (~20+), or disabling it, may speed up
the upload process, but also cause a buffer overflow and hang the Bluetooth adapter.
Maximum verified values were 29 for iPhone 6 Plus or 22 for iPhone 7, both iOS 10.1.
*/
@objc public var packetReceiptNotificationParameter: UInt16 = 12
/**
**Legacy DFU only.**
Setting this property to true will prevent from jumping to the DFU Bootloader
mode in case there is no DFU Version characteristic. Use it if the DFU operation can be handled by your
device running in the application mode. If the DFU Version characteristic exists, the
information whether to begin DFU operation, or jump to bootloader, is taken from the
characteristic's value. The value returned equal to 0x0100 (read as: minor=1, major=0, or version 0.1)
means that the device is in the application mode and buttonless jump to DFU Bootloader is supported.
Currently, the following values of the DFU Version characteristic are supported:
**No DFU Version characteristic** - one of the first implementations of DFU Service. The device
may support only Application update (version from SDK 4.3.0), may support Soft Device, Bootloader
and Application update but without buttonless jump to bootloader (SDK 6.0.0) or with
buttonless jump (SDK 6.1.0).
The DFU Library determines whether the device is in application mode or in DFU Bootloader mode
by counting number of services: if no DFU Service found - device is in app mode and does not support
buttonless jump, if the DFU Service is the only service found (except General Access and General Attribute
services) - it assumes it is in DFU Bootloader mode and may start DFU immediately, if there is
at least one service except DFU Service - the device is in application mode and supports buttonless
jump. In the lase case, you want to perform DFU operation without jumping - call the setForceDfu(force:Bool)
method with parameter equal to true.
**0.1** - Device is in a mode that supports buttonless jump to the DFU Bootloader
**0.5** - Device can handle DFU operation. Extended Init packet is required. Bond information is lost
in the bootloader mode and after updating an app. Released in SDK 7.0.0.
**0.6** - Bond information is kept in bootloader mode and may be kept after updating application
(DFU Bootloader must be configured to preserve the bond information).
**0.7** - The SHA-256 firmware hash is used in the Extended Init Packet instead of CRC-16.
This feature is transparent for the DFU Service.
**0.8** - The Extended Init Packet is signed using the private key. The bootloader, using the public key,
is able to verify the content. Released in SDK 9.0.0 as experimental feature.
Caution! The firmware type (Application, Bootloader, SoftDevice or SoftDevice+Bootloader) is not
encrypted as it is not a part of the Extended Init Packet. A change in the protocol will be required
to fix this issue.
By default the DFU Library will try to switch the device to the DFU Bootloader mode if it finds
more services then one (DFU Service). It assumes it is already in the bootloader mode
if the only service found is the DFU Service. Setting the forceDfu to true (YES) will prevent from
jumping in these both cases.
*/
@objc public var forceDfu = false
/**
In SDK 14.0.0 a new feature was added to the Buttonless DFU for non-bonded devices which allows to send a unique name
to the device before it is switched to bootloader mode. After jump, the bootloader will advertise with this name
as the Complete Local Name making it easy to select proper device. In this case you don't have to override the default
peripheral selector.
Read more: http://infocenter.nordicsemi.com/topic/com.nordic.infocenter.sdk5.v14.0.0/service_dfu.html
Setting this flag to false you will disable this feature. iOS DFU Library will not send the 0x02-[len]-[new name]
command prior jumping and will rely on the DfuPeripheralSelectorDelegate just like it used to in previous SDK.
This flag is ignored in Legacy DFU.
**It is recommended to keep this flag set to true unless necessary.**
For more information read: https://github.com/NordicSemiconductor/IOS-nRF-Connect/issues/16
*/
@objc public var alternativeAdvertisingNameEnabled = true
/**
Set this flag to true to enable experimental buttonless feature in Secure DFU. When the
experimental Buttonless DFU Service is found on a device, the service will use it to
switch the device to the bootloader mode, connect to it in that mode and proceed with DFU.
**Please, read the information below before setting it to true.**
In the SDK 12.x the Buttonless DFU feature for Secure DFU was experimental.
It is NOT recommended to use it: it was not properly tested, had implementation bugs
(e.g. https://devzone.nordicsemi.com/question/100609/sdk-12-bootloader-erased-after-programming/) and
does not required encryption and therefore may lead to DOS attack (anyone can use it to switch the device
to bootloader mode). However, as there is no other way to trigger bootloader mode on devices
without a button, this DFU Library supports this service, but the feature must be explicitly enabled here.
Be aware, that setting this flag to false will no protect your devices from this kind of attacks, as
an attacker may use another app for that purpose. To be sure your device is secure remove this
experimental service from your device.
Spec:
Buttonless DFU Service UUID: 8E400001-F315-4F60-9FB8-838830DAEA50
Buttonless DFU characteristic UUID: 8E400001-F315-4F60-9FB8-838830DAEA50 (the same)
Enter Bootloader Op Code: 0x01
Correct return value: 0x20-01-01 , where:
0x20 - Response Op Code
0x01 - Request Code
0x01 - Success
The device should disconnect and restart in DFU mode after sending the notification.
In SDK 13 this issue will be fixed by a proper implementation (bonding required,
passing bond information to the bootloader, encryption, well tested). It is recommended to use this
new service when SDK 13 (or later) is out. TODO: fix the docs when SDK 13 is out.
*/
@objc public var enableUnsafeExperimentalButtonlessServiceInSecureDfu = false
/**
UUIDs used during the DFU Process.
This allows you to pass in Custom UUIDs for the DFU Service/Characteristics.
*/
@objc public var uuidHelper: DFUUuidHelper
/**
Disable the ability for the DFU process to resume from where it was.
*/
@objc public var disableResume: Bool = false
//MARK: - Public API
/**
Creates the DFUServiceInitializer that will allow to send an update to the given peripheral.
This constructor takes control over the central manager and peripheral objects.
Their delegates will be set to internal library objects and will NOT be reverted to
original objects, instead they will be set to nil when DFU is complete, aborted or
has failed with an error. An app should restore the delegates (if needed) after
receiving .completed or .aborted DFUState, or receiving an error.
- important: This constructor has been deprecated in favor of `init(target: CBPeripheral)`,
which does not take control over the give peripheral, and is using a copy instead.
- parameter centralManager: Manager that will be used to connect to the peripheral
- parameter target: The DFU target peripheral.
- returns: The initiator instance.
- seeAlso: peripheralSelector property - a selector used when scanning for a device in DFU Bootloader mode
in case you want to update a Softdevice and Application from a single ZIP Distribution Packet.
*/
@available(*, deprecated, message: "Use init(queue: DispatchQueue?) instead.")
@objc public init(centralManager: CBCentralManager, target: CBPeripheral) {
self.centralManager = centralManager
// Just to be sure that manager is not scanning
self.centralManager.stopScan()
self.target = target
// Default peripheral selector will choose the service UUID as a filter
self.peripheralSelector = DFUPeripheralSelector()
// Default UUID helper with standard set of UUIDs
self.uuidHelper = DFUUuidHelper()
self.queue = DispatchQueue.main
self.delegateQueue = DispatchQueue.main
self.progressDelegateQueue = DispatchQueue.main
self.loggerQueue = DispatchQueue.main
super.init()
}
/**
Creates the DFUServiceInitializer that will allow to send an update to peripherals.
- parameter queue: The dispatch queue to run BLE operations on.
- parameter callbackQueue: The dispatch queue to invoke all delegate callbacks on.
- parameter progressQueue: The dispatch queue to invoke all progress delegate callbacks on.
- parameter loggerQueue: The dispatch queue to invoke all logger events on.
- returns: The initiator instance.
- version: Added in version 4.2 of the iOS DFU Library. Extended in 4.3 to allow setting delegate queues.
- seeAlso: peripheralSelector property - a selector used when scanning for a device in DFU Bootloader mode
in case you want to update a Softdevice and Application from a single ZIP Distribution Packet.
*/
@objc public init(queue: DispatchQueue? = nil,
delegateQueue: DispatchQueue = DispatchQueue.main,
progressQueue: DispatchQueue = DispatchQueue.main,
loggerQueue: DispatchQueue = DispatchQueue.main) {
// Create a new instance of CBCentralManager
self.centralManager = CBCentralManager(delegate: nil, queue: queue)
// Default peripheral selector will choose the service UUID as a filter
self.peripheralSelector = DFUPeripheralSelector()
// Default UUID helper with standard set of UUIDs
self.uuidHelper = DFUUuidHelper()
self.queue = queue ?? DispatchQueue.main
self.delegateQueue = delegateQueue
self.progressDelegateQueue = progressQueue
self.loggerQueue = loggerQueue
super.init()
}
/**
Sets the file with the firmware. The file must be specified before calling
`start(...)` method.
- parameter file: The firmware wrapper object.
- returns: The initiator instance to allow chain use.
*/
@objc public func with(firmware file: DFUFirmware) -> DFUServiceInitiator {
self.file = file
return self
}
/**
Starts sending the specified firmware to the DFU target specified in `init(centralManager:target)`.
When started, the service will automatically connect to the target, switch to DFU Bootloader mode
(if necessary), and send all the content of the specified firmware file in one or two connections.
Two connections will be used if a ZIP file contains a Soft Device and/or Bootloader and an Application.
First the Soft Device and/or Bootloader will be transferred, then the service will disconnect, reconnect
to the (new) Bootloader again and send the Application (unless the target supports receiving all files
in a single connection). The peripheral will NOT be reconnected after the DFU is completed, aborted
or has failed.
The current version of the DFU Bootloader, due to memory limitations, may receive together only
a Softdevice and Bootloader.
- important: Use `start(target: CBPeripheral)` instead.
- returns: A DFUServiceController object that can be used to control the DFU operation,
or nil, if the file was not set, or the target peripheral was not set.
*/
@available(*, deprecated, message: "Use start(target: CBPeripheral) instead.")
@objc public func start() -> DFUServiceController? {
// The firmware file must be specified before calling `start()`.
if file == nil {
delegate?.dfuError(.fileNotSpecified, didOccurWithMessage: "Firmware not specified")
return nil
}
// Make sure the target was set by the deprecated init.
guard let _ = target else {
delegate?.dfuError(.failedToConnect, didOccurWithMessage: "Target not specified: use start(target) instead")
return nil
}
let controller = DFUServiceController()
let selector = DFUServiceSelector(initiator: self, controller: controller)
controller.executor = selector
selector.start()
return controller
}
/**
Starts sending the specified firmware to the given DFU target.
When started, the service will automatically connect to the target, switch to DFU Bootloader mode
(if necessary), and send all the content of the specified firmware file in one or two connections.
Two connections will be used if a ZIP file contains a Soft Device and/or Bootloader and an Application.
First the Soft Device and/or Bootloader will be transferred, then the service will disconnect, reconnect
to the (new) Bootloader again and send the Application (unless the target supports receiving all files
in a single connection). The peripheral will NOT be reconnected after the DFU is completed, aborted
or has failed.
This method does not take control over the peripheral.
A new central manager is used, from which a copy of the peripheral is retrieved. Be warned,
that the original peripheral delegate may receive a lot of calls, and it will restart during
the process. The app should not send any data to DFU characteristics when DFU is in progress.
The current version of the DFU Bootloader, due to memory limitations, may receive together only
a Softdevice and Bootloader.
- parameter target: The DFU target peripheral.
- returns: A DFUServiceController object that can be used to control the DFU operation,
or nil, if the file was not set, or the peripheral instance could not be retrieved.
*/
@objc public func start(target: CBPeripheral) -> DFUServiceController? {
return start(targetWithIdentifier: target.identifier)
}
/**
Starts sending the specified firmware to the DFU target with given identifier.
When started, the service will automatically connect to the target, switch to DFU Bootloader mode
(if necessary), and send all the content of the specified firmware file in one or two connections.
Two connections will be used if a ZIP file contains a Soft Device and/or Bootloader and an Application.
First the Soft Device and/or Bootloader will be transferred, then the service will disconnect, reconnect
to the (new) Bootloader again and send the Application (unless the target supports receiving all files
in a single connection). The peripheral will NOT be reconnected after the DFU is completed, aborted
or has failed.
This method does not take control over the peripheral.
A new central manager is used, from which a copy of the peripheral is retrieved. Be warned,
that the original peripheral delegate may receive a lot of calls, and it will restart during
the process. The app should not send any data to DFU characteristics when DFU is in progress.
The current version of the DFU Bootloader, due to memory limitations, may receive together only
a Softdevice and Bootloader.
- parameter uuid: The UUID associated with the peer.
- returns: A DFUServiceController object that can be used to control the DFU operation,
or nil, if the file was not set, or the peripheral instance could not be retrieved.
*/
@objc public func start(targetWithIdentifier uuid: UUID) -> DFUServiceController? {
// The firmware file must be specified before calling `start(...)`.
if file == nil {
delegate?.dfuError(.fileNotSpecified, didOccurWithMessage: "Firmware not specified")
return nil
}
// As the given peripheral was obtained using a different central manager,
// its new instance must be obtained from the new manager.
guard let peripheral = self.centralManager.retrievePeripherals(withIdentifiers: [uuid]).first else {
delegate?.dfuError(.bluetoothDisabled, didOccurWithMessage: "Could not obtain peripheral instance")
return nil
}
target = peripheral
let controller = DFUServiceController()
let selector = DFUServiceSelector(initiator: self, controller: controller)
controller.executor = selector
selector.start()
return controller
}
}
| mit | 009e9013307fa6bbe2cc264e1b0678cf | 52.574209 | 145 | 0.714474 | 5.123081 | false | false | false | false |
1oo1/SwiftV2ray | SwiftV2ray/ProxySetting.swift | 1 | 6089 | //
// ProxySetting.swift
// SwiftV2ray
//
// Created by zc on 2017/8/1.
// Copyright © 2017年 zc. All rights reserved.
//
import Foundation
import Security
import SystemConfiguration
enum ProxyType {
case global(Bool, String, Int)
case auto(Bool, String)
case none
var enabled: Bool {
switch self {
case let .global(enable, _, _):
return enable
case let .auto(enable, _):
return enable
default:
return false
}
}
}
enum ProxyError: Error {
case error(String)
}
class ProxySetting {
private(set) var currentType: ProxyType = .none
private var authRef: AuthorizationRef?
private var lastSettings: [String: Any]?
// MARK: Private methods
func set(_ type: ProxyType, success:() -> Void, failed:((ProxyError) -> Void)? = nil) {
do {
try setProxy(type: type)
currentType = type
success()
} catch {
if let failed = failed {
failed(error as! ProxyError)
}
}
}
// MARK: Private methods
private func auth(_ authRefPointer: UnsafeMutablePointer<AuthorizationRef?>) throws {
guard authRefPointer.pointee == nil else {
return
}
let authFlags: AuthorizationFlags = [.interactionAllowed, .extendRights, .preAuthorize]
let status = AuthorizationCreate(nil, nil, authFlags, authRefPointer)
guard status == errAuthorizationSuccess else {
throw ProxyError.error("AuthorizationCreate failed.")
}
}
private func setProxy(type: ProxyType) throws {
try auth(&authRef)
guard let myAuthRef = authRef else {
return
}
let preference = SCPreferencesCreateWithAuthorization(nil, kAppIdentifier as CFString, nil, myAuthRef)!
// https://developer.apple.com/library/content/documentation/Networking/Conceptual/SystemConfigFrameworks/SC_UnderstandSchema/SC_UnderstandSchema.html#//apple_ref/doc/uid/TP40001065-CH203-CHDFBDCB
let dynamicStore = SCDynamicStoreCreate(nil, kAppIdentifier as CFString, nil, nil)
let primaryService = SCDynamicStoreCopyValue(dynamicStore, "State:/Network/Global/IPv4" as CFString)?.value(forKey: kSCDynamicStorePropNetPrimaryService as String)
guard let primaryServiceName = primaryService as? String else {
throw ProxyError.error("SCDynamicStoreCopyValue failed")
}
if lastSettings == nil {
let settings = SCPreferencesGetValue(preference, kSCPrefNetworkServices) as? [String: [String: Any]]
let interfaceService = settings?[primaryServiceName]
lastSettings = interfaceService?[kSCEntNetProxies as String] as? [String: Any]
}
// Disable all proxies
var newProxies: [String: Any] = [kCFNetworkProxiesExceptionsList as String : ["0.0.0.0/8",
"10.0.0.0/8",
"100.64.0.0/10",
"127.0.0.0/8",
"169.254.0.0/16",
"172.16.0.0/12",
"192.0.0.0/24",
"192.0.2.0/24",
"192.100.1.0/24",
"192.168.0.0/16",
"198.18.0.0/15",
"198.51.100.0/24",
"203.0.113.0/24",
"::1/128",
"fc00::/7",
"fe80::/10"]]
// 不能用 Bool 代替 Int,否则即使 UI 上显示已启用 proxy 仍然无法使用
switch type {
case let .global(enabled, proxy, port):
newProxies[kCFNetworkProxiesSOCKSEnable as String] = enabled ? 1 : 0
newProxies[kCFNetworkProxiesSOCKSProxy as String] = proxy
newProxies[kCFNetworkProxiesSOCKSPort as String] = port
case let .auto(enabled, pacUrl):
newProxies[kCFNetworkProxiesProxyAutoConfigEnable as String] = enabled ? 1 : 0
newProxies[kCFNetworkProxiesProxyAutoConfigURLString as String] = pacUrl
default:
newProxies = lastSettings ?? [:]
}
let key = "/\(kSCPrefNetworkServices as String)" +
"/\(primaryServiceName)" +
"/\(kSCEntNetProxies as CFString)" as CFString
var trueSet: Set<Bool> = []
trueSet.insert(SCPreferencesLock(preference, true))
trueSet.insert(SCPreferencesPathSetValue(preference,
key,
newProxies as CFDictionary))
trueSet.insert(SCPreferencesCommitChanges(preference))
trueSet.insert(SCPreferencesApplyChanges(preference))
SCPreferencesSynchronize(preference)
trueSet.insert(SCPreferencesUnlock(preference))
guard trueSet.count == 1 else {
throw ProxyError.error("SCPreferences Lock | PathSetValue | CommitChanges | ApplyChanges | Unlock failed.")
}
}
}
| mit | 8eeba31ed5fd3a14f65dd168254197f4 | 43.10219 | 204 | 0.484608 | 5.532967 | false | false | false | false |
devtak/Xcode-File-Templates | UI Class.xctemplate/UITableViewCell/___FILEBASENAME___.swift | 1 | 1640 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
//
import UIKit
import CommonUtils
final class ___FILEBASENAMEASIDENTIFIER___: UITableViewCell {
private var titleLabel: UILabel!
private var separatorView: UIView!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupSubviews()
setupBindings()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - override
extension ___FILEBASENAMEASIDENTIFIER___ {
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.layouts {
$0.left = 15
$0.verticalCenter()
}
separatorView.layouts {
$0.width = frame.width
$0.marginBottom = 0
}
}
override func prepareForReuse() {
super.prepareForReuse()
titleLabel.text = nil
}
}
// MARK: - public
extension ___FILEBASENAMEASIDENTIFIER___ {
func configureCell(_ item: <#name#>) {
titleLabel.text = "item"
titleLabel.sizeToFit()
}
}
// MARK: - private
private extension ___FILEBASENAMEASIDENTIFIER___ {
func setupSubviews() {
titleLabel = contentView.addLabel()
separatorView = contentView.addChildview(type: UIView.self) {
$0.layout.height = 0.5
$0.backgroundColor = UIColor.separatorViewColor
}
}
func setupBindings() {
}
}
| mit | 5de4df6ae02d72cd9f7d65483433fcf1 | 20.025641 | 79 | 0.582927 | 4.866469 | false | false | false | false |
zitao0322/ShopCar | Shoping_Car/Pods/RxCocoa/RxCocoa/Common/CocoaUnits/Driver/Driver+Subscription.swift | 9 | 4784 | //
// Driver+Subscription.swift
// Rx
//
// Created by Krunoslav Zaher on 9/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
private let driverErrorMessage = "`drive*` family of methods can be only called from `MainThread`.\n" +
"This is required to ensure that the last replayed `Driver` element is delivered on `MainThread`.\n"
extension DriverConvertibleType {
/**
Creates new subscription and sends elements to observer.
This method can be only called from `MainThread`.
In this form it's equivalent to `subscribe` method, but it communicates intent better.
- parameter observer: Observer that receives events.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func drive<O: ObserverType where O.E == E>(observer: O) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(driverErrorMessage)
return self.asObservable().subscribe(observer)
}
/**
Creates new subscription and sends elements to variable.
This method can be only called from `MainThread`.
- parameter variable: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer from the variable.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func drive(variable: Variable<E>) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(driverErrorMessage)
return drive(onNext: { e in
variable.value = e
})
}
/**
Subscribes to observable sequence using custom binder function.
This method can be only called from `MainThread`.
- parameter with: Function used to bind elements from `self`.
- returns: Object representing subscription.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func drive<R>(transformation: Observable<E> -> R) -> R {
MainScheduler.ensureExecutingOnScheduler(driverErrorMessage)
return transformation(self.asObservable())
}
/**
Subscribes to observable sequence using custom binder function and final parameter passed to binder function
after `self` is passed.
public func drive<R1, R2>(with: Self -> R1 -> R2, curriedArgument: R1) -> R2 {
return with(self)(curriedArgument)
}
This method can be only called from `MainThread`.
- parameter with: Function used to bind elements from `self`.
- parameter curriedArgument: Final argument passed to `binder` to finish binding process.
- returns: Object representing subscription.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func drive<R1, R2>(with: Observable<E> -> R1 -> R2, curriedArgument: R1) -> R2 {
MainScheduler.ensureExecutingOnScheduler(driverErrorMessage)
return with(self.asObservable())(curriedArgument)
}
/**
Subscribes an element handler, a completion handler and disposed handler to an observable sequence.
This method can be only called from `MainThread`.
Error callback is not exposed because `Driver` can't error out.
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
gracefully completed, errored, or if the generation is cancelled by disposing subscription)
- parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is cancelled by disposing subscription)
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func drive(onNext onNext: ((E) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(driverErrorMessage)
return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed)
}
/**
Subscribes an element handler to an observable sequence.
This method can be only called from `MainThread`.
- parameter onNext: Action to invoke for each element in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func driveNext(onNext: E -> Void) -> Disposable {
MainScheduler.ensureExecutingOnScheduler(driverErrorMessage)
return self.asObservable().subscribeNext(onNext)
}
}
| mit | 3d8e83dda3501b9646d8a820ee14bdfc | 40.95614 | 141 | 0.706669 | 4.787788 | false | false | false | false |
VWAS/Polaris | FontDefaults.swift | 1 | 1232 | //
// FontDefaults.swift
// Codinator
//
// Created by Vladimir Danila on 14/06/16.
// Copyright © 2016 Vladimir Danila. All rights reserved.
//
import UIKit
let fontsKey = "[P]CustomFontsKey"
let fontKeyName = "[Polaris]CustomFontKeyFontName"
let fontKeySize = "[Polaris]CustomFontKeyFontSize"
extension UserDefaults {
func font(key: String) -> UIFont? {
let fonts = self.dictionary(forKey: fontsKey)
let fontComponent = fonts?[key] as? [String : AnyObject]
guard let fontName = fontComponent?[fontKeyName] as? String,
let fontSize = fontComponent?[fontKeySize] as? CGFloat else {
return nil
}
return UIFont(name: fontName, size: fontSize)
}
func set(font: UIFont, key: String) {
var fonts = self.object(forKey: fontsKey) as? [String : AnyObject]
if fonts == nil {
fonts = [String : AnyObject]()
}
let fontComponents = [
fontKeyName : font.fontName,
fontKeySize : font.pointSize
]
fonts![key] = fontComponents
self.setValue(fonts, forKey: fontsKey)
}
}
| mit | 3d2ef139a7f6e14e2988c445a9da6743 | 23.137255 | 74 | 0.573517 | 4.380783 | false | false | false | false |
zhihuitang/Apollo | Pods/SwiftMagic/SwiftMagic/Classes/Extensions/Extension+UIColor.swift | 1 | 4183 | //
// LoggerViewController.swift
// SwiftMagic
//
// Created by Zhihui Tang on 2018-01-10.
//
import Foundation
import UIKit
extension UIColor {
// MARK: - hex (0x000000) -> UIColor
///
/// - Parameter hex (0x000000)
/// - Returns: UIColor
class func hex(hex: Int) -> UIColor {
return UIColor.hex(hex: hex, alpha: 1.0)
}
///
/// - Parameters:
/// - Returns: UIColor
class func hex(hex: Int, alpha: CGFloat) -> UIColor {
return UIColor(red: CGFloat((hex >> 16) & 0xFF)/255.0, green: CGFloat((hex >> 8) & 0xFF)/255.0, blue: CGFloat(hex & 0xFF)/255.0, alpha: alpha)
}
///
/*
class func hex(hex: String) -> UIColor {
var alpha, red, blue, green: CGFloat
let colorString = hex.replacingOccurrences(of: "#", with: "")
switch colorString.count {
case 3: // #RGB
alpha = 1.0
red = colorComponent(hex: colorString, start: 0, length: 1)
green = colorComponent(hex: colorString, start: 1, length: 1)
blue = colorComponent(hex: colorString, start: 2, length: 1)
case 4: // #ARGB
alpha = colorComponent(hex: colorString, start: 0, length: 1)
red = colorComponent(hex: colorString, start: 1, length: 1)
green = colorComponent(hex: colorString, start: 2, length: 1)
blue = colorComponent(hex: colorString, start: 3, length: 1)
case 6: // #RRGGBB
alpha = 1.0
red = colorComponent(hex: colorString, start: 0, length: 2)
green = colorComponent(hex: colorString, start: 2, length: 2)
blue = colorComponent(hex: colorString, start: 4, length: 2)
case 8: // #AARRGGBB
alpha = colorComponent(hex: colorString, start: 0, length: 2)
red = colorComponent(hex: colorString, start: 2, length: 2)
green = colorComponent(hex: colorString, start: 4, length: 2)
blue = colorComponent(hex: colorString, start: 6, length: 2)
default:
alpha = 0
red = 0
green = 0
blue = 0
}
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}*/
private class func colorComponent(hex: String, start: Int, length: Int) -> CGFloat {
let subString = hex.sliceString(start..<(start + length))
let fullHex = length == 2 ? subString : (subString + subString)
var val: CUnsignedInt = 0
Scanner(string: fullHex).scanHexInt32(&val)
return CGFloat(val) / 255.0
}
var hex: String {
var color = self
if color.cgColor.numberOfComponents < 4 {
let components = color.cgColor.components
color = UIColor(red: components![0], green: components![0], blue: components![0], alpha: components![1])
}
if color.cgColor.colorSpace?.model != CGColorSpaceModel.rgb {
return "#FFFFFF"
}
return String(format: "#%02X%02X%02X", Int(color.cgColor.components![0]*255.0), Int(color.cgColor.components![1]*255.0), Int(color.cgColor.components![2]*255.0))
}
// MARK: - RGB -> UIColor
class func rgba(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor {
return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: alpha)
}
// MARK: - RGBA -> UIColor
class func rgb(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor {
return rgba(red: red, green: green, blue: blue, alpha: 1.0)
}
var rgba: [Int] {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return [Int(red*255.0), Int(green*255.0), Int(blue*255.0), Int(alpha)]
}
class func randomColor() -> UIColor {
let red = CGFloat(arc4random()%255)
let green = CGFloat(arc4random()%255)
let blue = CGFloat(arc4random()%255)
let color = UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: 1.0)
return color
}
}
| apache-2.0 | 5e1c9d6f8e8afabf82a633df7cbc48bc | 37.027273 | 169 | 0.573751 | 3.85175 | false | false | false | false |
KordianKL/SongGenius | Song Genius/PastelView.swift | 1 | 4751 | //
// PastelView.swift
// Song Genius
//
// Created by Kordian Ledzion on 16.06.2017.
// Copyright © 2017 KordianLedzion. All rights reserved.
//
import UIKit
open class PastelView: UIView {
private struct Animation {
static let keyPath = "colors"
static let key = "ColorChange"
}
@objc
public enum PastelPoint: Int {
case left
case top
case right
case bottom
case topLeft
case topRight
case bottomLeft
case bottomRight
var point: CGPoint {
switch self {
case .left: return CGPoint(x: 0.0, y: 0.5)
case .top: return CGPoint(x: 0.5, y: 0.0)
case .right: return CGPoint(x: 1.0, y: 0.5)
case .bottom: return CGPoint(x: 0.5, y: 1.0)
case .topLeft: return CGPoint(x: 0.0, y: 0.0)
case .topRight: return CGPoint(x: 1.0, y: 0.0)
case .bottomLeft: return CGPoint(x: 0.0, y: 1.0)
case .bottomRight: return CGPoint(x: 1.0, y: 1.0)
}
}
}
// Custom Direction
open var startPoint: CGPoint = PastelPoint.topRight.point
open var endPoint: CGPoint = PastelPoint.bottomLeft.point
open var startPastelPoint = PastelPoint.topRight {
didSet {
startPoint = startPastelPoint.point
}
}
open var endPastelPoint = PastelPoint.bottomLeft {
didSet {
endPoint = endPastelPoint.point
}
}
// Custom Duration
open var animationDuration: TimeInterval = 5.0
fileprivate let gradient = CAGradientLayer()
private var currentGradient: Int = 0
private var colors: [UIColor] = [UIColor(red: 156/255, green: 39/255, blue: 176/255, alpha: 1.0),
UIColor(red: 255/255, green: 64/255, blue: 129/255, alpha: 1.0),
UIColor(red: 123/255, green: 31/255, blue: 162/255, alpha: 1.0),
UIColor(red: 32/255, green: 76/255, blue: 255/255, alpha: 1.0),
UIColor(red: 32/255, green: 158/255, blue: 255/255, alpha: 1.0),
UIColor(red: 90/255, green: 120/255, blue: 127/255, alpha: 1.0),
UIColor(red: 58/255, green: 255/255, blue: 217/255, alpha: 1.0)]
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
}
open override func layoutSubviews() {
super.layoutSubviews()
gradient.frame = bounds
}
public func startAnimation() {
gradient.removeAllAnimations()
setup()
animateGradient()
}
fileprivate func setup() {
gradient.frame = bounds
gradient.colors = currentGradientSet()
gradient.startPoint = startPoint
gradient.endPoint = endPoint
gradient.drawsAsynchronously = true
layer.insertSublayer(gradient, at: 0)
}
fileprivate func currentGradientSet() -> [CGColor] {
guard colors.count > 0 else { return [] }
return [colors[currentGradient % colors.count].cgColor,
colors[(currentGradient + 1) % colors.count].cgColor]
}
public func setColors(_ colors: [UIColor]) {
guard colors.count > 0 else { return }
self.colors = colors
}
public func addcolor(_ color: UIColor) {
self.colors.append(color)
}
func animateGradient() {
currentGradient += 1
let animation = CABasicAnimation(keyPath: Animation.keyPath)
animation.duration = animationDuration
animation.toValue = currentGradientSet()
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
animation.delegate = self
gradient.add(animation, forKey: Animation.key)
}
open override func removeFromSuperview() {
super.removeFromSuperview()
gradient.removeAllAnimations()
gradient.removeFromSuperlayer()
}
}
extension PastelView: CAAnimationDelegate {
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag {
gradient.colors = currentGradientSet()
animateGradient()
}
}
}
| mit | 7b7cc640807ebda10b3940a41786df78 | 30.25 | 101 | 0.574526 | 4.536772 | false | false | false | false |
UncleJoke/ios-charts | Charts/Classes/Data/BubbleChartDataSet.swift | 3 | 2821 | //
// BubbleChartDataSet.swift
// Charts
//
// Bubble chart implementation:
// Copyright 2015 Pierre-Marc Airoldi
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics;
public class BubbleChartDataSet: BarLineScatterCandleChartDataSet
{
internal var _xMax = Float(0.0)
internal var _xMin = Float(0.0)
internal var _maxSize = CGFloat(0.0)
public var xMin: Float { return _xMin }
public var xMax: Float { return _xMax }
public var maxSize: CGFloat { return _maxSize }
public func setColor(color: UIColor, alpha: CGFloat)
{
super.setColor(color.colorWithAlphaComponent(alpha))
}
internal override func calcMinMax(#start: Int, end: Int)
{
if (yVals.count == 0)
{
return;
}
let entries = yVals as! [BubbleChartDataEntry];
// need chart width to guess this properly
var endValue : Int;
if end == 0
{
endValue = entries.count - 1;
}
else
{
endValue = end;
}
_lastStart = start;
_lastEnd = end;
_yMin = yMin(entries[start]);
_yMax = yMax(entries[start]);
for (var i = start; i <= endValue; i++)
{
let entry = entries[i];
let ymin = yMin(entry)
let ymax = yMax(entry)
if (ymin < _yMin)
{
_yMin = ymin
}
if (ymax > _yMax)
{
_yMax = ymax;
}
let xmin = xMin(entry)
let xmax = xMax(entry)
if (xmin < _xMin)
{
_xMin = xmin;
}
if (xmax > _xMax)
{
_xMax = xmax;
}
let size = largestSize(entry)
if (size > _maxSize)
{
_maxSize = size
}
}
}
/// Sets/gets the width of the circle that surrounds the bubble when highlighted
public var highlightCircleWidth: CGFloat = 2.5;
private func yMin(entry: BubbleChartDataEntry) -> Float
{
return entry.value
}
private func yMax(entry: BubbleChartDataEntry) -> Float
{
return entry.value
}
private func xMin(entry: BubbleChartDataEntry) -> Float
{
return Float(entry.xIndex)
}
private func xMax(entry: BubbleChartDataEntry) -> Float
{
return Float(entry.xIndex)
}
private func largestSize(entry: BubbleChartDataEntry) -> CGFloat
{
return entry.size
}
}
| apache-2.0 | d27cc90c1d9e86b220dbb3aa71834844 | 21.75 | 84 | 0.493797 | 4.813993 | false | false | false | false |
v2panda/DaysofSwift | swift2.3/My-Spotlt/My-Spotlt/DetailViewController.swift | 1 | 1936 | //
// DetailViewController.swift
// My-Spotlt
//
// Created by Panda on 16/3/20.
// Copyright © 2016年 v2panda. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var imgMovieImage: UIImageView!
@IBOutlet weak var IblTitle: UILabel!
@IBOutlet weak var IbCategory: UILabel!
@IBOutlet weak var IbDesctiption: UILabel!
@IBOutlet weak var IbDirector: UILabel!
@IBOutlet weak var IbStars: UILabel!
@IBOutlet weak var IbRating: UILabel!
var movieInfo: [String: String]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
IbRating.layer.cornerRadius = IbRating.frame.size.width / 2
IbRating.layer.masksToBounds = true
if movieInfo != nil {
populateMovieInfo()
}
}
func populateMovieInfo() {
IblTitle.text = movieInfo["Title"]!
IbCategory.text = movieInfo["Category"]!
IbDesctiption.text = movieInfo["Description"]!
IbDirector.text = movieInfo["Director"]!
IbStars.text = movieInfo["Stars"]!
IbRating.text = movieInfo["Rating"]!
imgMovieImage.image = UIImage(named: movieInfo["Image"]!)
}
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.
}
*/
}
| mit | 9d523a2c6e43df9bdf0692daebe7354d | 27.426471 | 106 | 0.648215 | 4.761084 | false | false | false | false |
iWeslie/Ant | Ant/Ant/LunTan/Public/Category/ViewController.swift | 1 | 5423 | //
// ViewController.swift
// CascadeListDemo
//
// Created by Weslie on 2017/7/31.
// Copyright © 2017年 Weslie. All rights reserved.
//
import UIKit
let width = UIScreen.main.bounds.width
let tableViewHeight = UIScreen.main.bounds.height / 2
class ViewController: UIViewController {
var category = CategoryVC()
var categoryDetial = CategoryDetialVC()
let btnWidth = (UIScreen.main.bounds.width - 2) / 3
let button1 = UIButton(frame: CGRect(x: 0, y: 0, width: (UIScreen.main.bounds.width - 2) / 3, height: 30))
var cascadeViewDidShow: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
//loadListView()
self.navigationController?.navigationBar.isTranslucent = false
}
}
extension ViewController {
func addCascadeList() {
self.loadRotationImg(sender: button1.imageView!)
category.categoryDelegate = categoryDetial
if cascadeViewDidShow == true {
UIView.animate(withDuration: 0.2, animations: {
self.category.view.frame.size.height = 0
self.category.tableView.frame.size.height = 0
self.categoryDetial.view.frame.size.height = 0
self.categoryDetial.tableView.frame.size.height = 0
}, completion: { (_) in
self.category.view.isHidden = true
self.categoryDetial.view.isHidden = true
self.category.tableView.isHidden = true
self.categoryDetial.tableView.isHidden = true
})
cascadeViewDidShow = !cascadeViewDidShow
} else {
cascadeViewDidShow = !cascadeViewDidShow
self.category.view.frame.size.height = tableViewHeight
self.category.tableView.frame.size.height = tableViewHeight
self.categoryDetial.view.frame.size.height = tableViewHeight
self.categoryDetial.tableView.frame.size.height = tableViewHeight
self.category.view.isHidden = false
self.categoryDetial.view.isHidden = false
self.category.tableView.isHidden = false
self.categoryDetial.tableView.isHidden = false
}
}
fileprivate func loadListView() {
let view: UIView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40))
button1.setTitleColor(UIColor.black, for: .normal)
button1.setTitle("区域", for: .normal)
button1.setImage(#imageLiteral(resourceName: "triangle"), for: .normal)
button1.contentMode = .left
button1.titleEdgeInsets = UIEdgeInsets(top: 0, left: -(button1.imageView?.frame.width)! * 2, bottom: 0, right: 0)
// button1.titleLabel?.font = UIFont.systemFont(ofSize: 10)
button1.imageEdgeInsets = UIEdgeInsets(top: 0, left: -((button1.titleLabel?.frame.width)!), bottom: 0, right: -(button1.titleLabel?.frame.width)! * 2 - 10)
button1.addTarget(self, action: #selector(addCascadeList), for: .touchUpInside)
let button2 = UIButton(frame: CGRect(x: btnWidth + 1, y: 0, width: btnWidth, height: 40))
button2.setTitle("户型", for: .normal)
button2.titleLabel?.font = UIFont.systemFont(ofSize: 10)
button2.setTitleColor(UIColor.black, for: .normal)
let button3 = UIButton(frame: CGRect(x: btnWidth * 2 + 2, y: 0, width: btnWidth, height: 40))
button3.setTitle("按租金排序", for: .normal)
button3.setTitleColor(UIColor.black, for: .normal)
let lineView1: UIView = UIView(frame: CGRect(x: btnWidth, y: 8, width: 1, height: 24))
lineView1.backgroundColor = UIColor.lightGray
let lineView2: UIView = UIView(frame: CGRect(x: btnWidth * 2 + 1, y: 8, width: 1, height: 24))
lineView2.backgroundColor = UIColor.lightGray
view.addSubview(button1)
view.addSubview(button2)
view.addSubview(button3)
view.addSubview(lineView1)
view.addSubview(lineView2)
self.view.addSubview(view)
category.categoryDelegate = categoryDetial
category.view.frame = CGRect(x: 0, y: 40, width: width * 0.4, height: tableViewHeight)
self.view.addSubview(category.view)
addChildViewController(category)
categoryDetial.view.frame = CGRect(x: width * 0.4, y: 0, width: width * 0.6, height: tableViewHeight)
self.view.addSubview(categoryDetial.view)
addChildViewController(categoryDetial)
self.category.view.isHidden = true
self.categoryDetial.view.isHidden = true
}
func loadRotationImg(sender: UIImageView) {
// 1.创建动画
let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")
// 2.设置动画的属性
if cascadeViewDidShow == false {
rotationAnim.fromValue = 0
rotationAnim.toValue = Double.pi
} else {
rotationAnim.fromValue = Double.pi
rotationAnim.toValue = 0
}
rotationAnim.duration = 0.2
rotationAnim.isRemovedOnCompletion = false
rotationAnim.fillMode = kCAFillModeForwards
// 3.将动画添加到layer中
sender.layer.add(rotationAnim, forKey: nil)
}
}
| apache-2.0 | a1dad3aa13f231ada93e8f579939faee | 32.5375 | 163 | 0.621878 | 4.456811 | false | false | false | false |
ivngar/TDD-TodoList | TDD-TodoList/APIClient.swift | 1 | 1754 | //
// APIClient.swift
// TDD-TodoList
//
// Created by Ivan Garcia on 28/6/17.
// Copyright © 2017 Ivan Garcia. All rights reserved.
//
import Foundation
enum WebServiceError: Error {
case DataEmptyError
case ResponseError
}
class APIClient {
lazy var session: SessionProtocol = URLSession.shared
func loginUser(withName username: String, password: String, completion: @escaping (Token?, Error?) -> Void) {
guard let url = URL(string: "https://awesometodos.com/login") else { fatalError() }
var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)
let queryUsername = URLQueryItem(name: "username", value: username)
let queryPassword = URLQueryItem(name: "password", value: password)
urlComponents?.queryItems = [queryUsername, queryPassword]
guard let loginURL = urlComponents?.url else { fatalError() }
session.dataTask(with: loginURL) { (data, response, error) in
guard error == nil else {
completion(nil, WebServiceError.ResponseError)
return
}
guard let data = data else {
completion(nil, WebServiceError.DataEmptyError)
return
}
do {
let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String:String]
let token: Token?
if let tokenString = dict?["token"] {
token = Token(id: tokenString)
} else {
token = nil
}
completion(token, nil)
} catch {
completion(nil, error)
}
}.resume()
}
}
protocol SessionProtocol {
func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
}
extension URLSession: SessionProtocol {
}
| mit | 5d830e27d42ca33f523831cda6bd88a3 | 27.737705 | 120 | 0.650314 | 4.426768 | false | false | false | false |
zhixingxi/JJA_Swift | JJA_Swift/Pods/TimedSilver/Sources/Foundation/Data+TSExtension.swift | 1 | 1720 | //
// Data+TSExtension.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 11/25/15.
// Copyright © 2015 Hilen. All rights reserved.
//
import UIKit
import Foundation
public extension Data {
/// Convert the iOS deviceToken to String
var ts_tokenString: String {
let characterSet: CharacterSet = CharacterSet(charactersIn:"<>")
let deviceTokenString: String = (self.description as NSString).trimmingCharacters(in: characterSet).replacingOccurrences(of: " ", with:"") as String
return deviceTokenString
}
/**
Create NSData from JSON file
- parameter fileName: name
- returns: NSData
*/
static func ts_dataFromJSONFile(_ fileName: String) -> Data? {
if let path = Bundle.main.path(forResource: fileName, ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions.mappedIfSafe)
return data
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
} else {
print("Invalid filename/path.")
return nil
}
}
/// Convert NSData to MD5 String
var ts_md5String: String {
let MD5Calculator = TS_MD5(Array(UnsafeBufferPointer(start: (self as NSData).bytes.bindMemory(to: UInt8.self, capacity: self.count), count: self.count)))
let MD5Data = MD5Calculator.calculate()
let MD5String = NSMutableString()
for c in MD5Data {
MD5String.appendFormat("%02x", c)
}
return MD5String as String
}
}
| mit | 4b46b5ede8fa81101ff5caa1d3e40348 | 30.254545 | 161 | 0.610239 | 4.547619 | false | false | false | false |
algoliareadmebot/algoliasearch-client-swift | Source/Request.swift | 1 | 8884 | //
// Copyright (c) 2015-2016 Algolia
// http://www.algolia.com/
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// An API request.
///
/// This class encapsulates a sequence of normally one (nominal case), potentially many (in case of retry) network
/// calls into a high-level operation. This operation can be cancelled by the user.
///
internal class Request: AsyncOperationWithCompletion {
/// The client to which this request is related.
let client: AbstractClient
/// Request method.
let method: HTTPMethod
/// Hosts to which the request will be sent.
let hosts: [String]
/// Index of the first host that will be tried.
let firstHostIndex: Int
/// Index of the next host to be tried.
var nextHostIndex: Int
/// The URL path (actually everything after the host, so including the query string).
let path: String
/// Optional HTTP headers.
let headers: [String: String]?
/// Optional body, in JSON format.
let jsonBody: JSONObject?
/// Timeout for individual network queries.
let timeout: TimeInterval
/// Timeout to be used for the next query.
var nextTimeout: TimeInterval
/// The current network task.
var task: URLSessionTask?
// MARK: - Initialization
init(client: AbstractClient, method: HTTPMethod, hosts: [String], firstHostIndex: Int, path: String, headers: [String: String]?, jsonBody: JSONObject?, timeout: TimeInterval, completion: CompletionHandler?) {
self.client = client
self.method = method
self.hosts = client.upOrUnknownHosts(hosts)
assert(!hosts.isEmpty)
self.firstHostIndex = firstHostIndex
self.nextHostIndex = firstHostIndex
assert(firstHostIndex < hosts.count)
self.path = path
// IMPORTANT: Enforce the `User-Agent` header on all requests.
var patchedHeaders = headers ?? [:]
patchedHeaders["User-Agent"] = AbstractClient.userAgentHeader
self.headers = patchedHeaders
self.jsonBody = jsonBody
assert(jsonBody == nil || (method == .POST || method == .PUT))
self.timeout = timeout
self.nextTimeout = timeout
super.init(completionHandler: completion)
// Assign a descriptive name, but let the caller may change it afterwards (in contrast to getter override).
if #available(iOS 8.0, *) {
self.name = "Request{\(method) /\(path)}"
}
}
// MARK: - Debug
override var description: String {
get {
if #available(iOS 8.0, *) {
return name ?? super.description
} else {
return super.description
}
}
}
// MARK: - Request logic
/// Create a URL request for the specified host index.
private func createRequest(_ hostIndex: Int) -> URLRequest {
let url = URL(string: "https://\(hosts[hostIndex])/\(path)")
var request = URLRequest(url: url!)
request.httpMethod = method.rawValue
request.timeoutInterval = nextTimeout
if headers != nil {
for (key, value) in headers! {
request.addValue(value, forHTTPHeaderField: key)
}
}
if jsonBody != nil {
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if let payload = try? JSONSerialization.data(withJSONObject: jsonBody!, options: JSONSerialization.WritingOptions(rawValue: 0)) {
request.httpBody = payload
} else {
// The JSON we try to send should always be well-formed.
assert(false, "Trying to send a request with invalid JSON")
}
}
return request
}
private func startNext() {
// Shortcut when cancelled.
if _cancelled {
return
}
// If there is no network reachability, don't even attempt to perform the request.
#if !os(watchOS)
if !client.shouldMakeNetworkCall() {
self.callCompletion(content: nil, error: NSError(domain: NSURLErrorDomain, code: NSURLErrorNotConnectedToInternet, userInfo: nil))
return
}
#endif // !os(watchOS)
let currentHostIndex = nextHostIndex
let request = createRequest(currentHostIndex)
nextHostIndex = (nextHostIndex + 1) % hosts.count
task = client.session.dataTask(with: request) {
(data: Data?, response: URLResponse?, error: Error?) in
var json: JSONObject?
var finalError: Error? = error
// Shortcut in case of cancellation.
if self.isCancelled {
return
}
if (finalError == nil) {
assert(data != nil)
assert(response != nil)
// Parse JSON response.
// NOTE: We parse JSON even in case of failure to get the error message.
do {
json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? JSONObject
if json == nil {
finalError = InvalidJSONError(description: "Server response not a JSON object")
}
} catch let jsonError {
finalError = jsonError
}
// Handle HTTP status code.
let httpResponse = response! as! HTTPURLResponse
if (finalError == nil && !StatusCode.isSuccess(httpResponse.statusCode)) {
// Get the error message from JSON if available.
let errorMessage = json?["message"] as? String
finalError = HTTPError(statusCode: httpResponse.statusCode, message: errorMessage)
}
}
assert(json != nil || finalError != nil)
// Update host status.
let down = finalError != nil && finalError!.isTransient()
self.client.updateHostStatus(host: self.hosts[currentHostIndex], up: !down)
// Success: call completion block.
if finalError == nil {
self.callCompletion(content: json, error: nil)
}
// Transient error and host array not exhausted: retry.
else if finalError!.isTransient() && self.nextHostIndex != self.firstHostIndex {
self.nextTimeout += self.timeout // raise the timeout
self.startNext()
}
// Non-transient error, or no more hosts to retry: report the error.
else {
self.callCompletion(content: nil, error: finalError)
}
}
task!.resume()
}
// ----------------------------------------------------------------------
// MARK: - Operation interface
// ----------------------------------------------------------------------
/// Start this request.
override func start() {
super.start()
startNext()
}
/// Cancel this request.
/// The completion block (if any was provided) will not be called after a request has been cancelled.
///
/// WARNING: Cancelling a request may or may not cancel the underlying network call, depending how late the
/// cancellation happens. In other words, a cancelled request may have already been executed by the server. In any
/// case, cancelling never carries "undo" semantics.
///
override func cancel() {
task?.cancel()
task = nil
super.cancel()
}
override func finish() {
task = nil
super.finish()
}
}
| mit | c73359f2230dcf3f35a5cdfe42add846 | 38.136564 | 212 | 0.587798 | 5.111623 | false | false | false | false |
lsmaker/iOS | LsMaker/Bluetooth/BTService.swift | 1 | 4743 | //
// BTService.swift
// LsMaker
//
// Created by Ramon Pans on 15/03/17.
// Copyright © 2017 LaSalle. All rights reserved.
//
import Foundation
import CoreBluetooth
/* Services & Characteristics UUIDs */
let uartServiceUUIDString = CBUUID(string: "6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
let uartTXCharacteristicUUIDString = CBUUID(string: "6E400003-B5A3-F393-E0A9-E50E24DCCA9E")
let uartRXCharacteristicUUIDString = CBUUID(string: "6E400002-B5A3-F393-E0A9-E50E24DCCA9E")
let BLEServiceChangedStatusNotification = "kBLEServiceChangedStatusNotification"
class BTService: NSObject, CBPeripheralDelegate {
var peripheral: CBPeripheral?
var recieverCharacteristic: CBCharacteristic?
var transmitterCharacteristic: CBCharacteristic?
var positionCharacteristic: CBCharacteristic?
init(initWithPeripheral peripheral: CBPeripheral) {
super.init()
self.peripheral = peripheral
self.peripheral?.delegate = self
}
deinit {
self.reset()
}
func startDiscoveringServices() {
self.peripheral?.discoverServices([uartServiceUUIDString])
}
func reset() {
if peripheral != nil {
peripheral = nil
}
// Deallocating therefore send notification
self.sendBTServiceNotificationWithIsBluetoothConnected(false)
}
// Mark: - CBPeripheralDelegate
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
let uuidsForBTService: [CBUUID] = [uartTXCharacteristicUUIDString, uartRXCharacteristicUUIDString]
if (peripheral != self.peripheral) {
// Wrong Peripheral
return
}
if (error != nil) {
return
}
if ((peripheral.services == nil) || (peripheral.services!.count == 0)) {
// No Services
return
}
for service in peripheral.services! {
if service.uuid == uartServiceUUIDString {
print("We found the UART service")
peripheral.discoverCharacteristics(uuidsForBTService, for: service)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if (peripheral != self.peripheral) {
// Wrong Peripheral
return
}
if (error != nil) {
return
}
if let characteristics = service.characteristics {
for characteristic in characteristics {
if characteristic.uuid == uartRXCharacteristicUUIDString {
print("Found reciever characteristic")
self.recieverCharacteristic = (characteristic)
peripheral.setNotifyValue(true, for: characteristic)
} else if characteristic.uuid == uartTXCharacteristicUUIDString {
print("Found transmitter characteristic")
self.transmitterCharacteristic = (characteristic)
peripheral.setNotifyValue(true, for: characteristic)
}
if self.recieverCharacteristic != nil && self.transmitterCharacteristic != nil {
// Send notification that Bluetooth is connected and all required characteristics are discovered
print("Fully connected")
GlobalState.connectedLsMakerService = self
self.sendBTServiceNotificationWithIsBluetoothConnected(true)
}
}
}
}
func writeMessage(message: [UInt8]) {
if let rx = recieverCharacteristic {
self.peripheral?.writeValue(Data(message), for: rx, type: .withoutResponse)
//print(Data(message))
//print(message.asData())
}
}
func sendBTServiceNotificationWithIsBluetoothConnected(_ isBluetoothConnected: Bool) {
var connectionDetails = ["isConnected": isBluetoothConnected] as [String : Any]
if isBluetoothConnected {
connectionDetails["peripheral"] = self.peripheral!
}
NotificationCenter.default.post(name: Notification.Name(rawValue: BLEServiceChangedStatusNotification), object: self, userInfo: connectionDetails)
}
}
extension Array {
func asData() -> NSData {
return self.withUnsafeBufferPointer({
NSData(bytes: $0.baseAddress, length: count * MemoryLayout<Element>.stride)
})
}
}
| mit | 4c809b1045d936f92821e13631852161 | 32.160839 | 154 | 0.601012 | 5.450575 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 1.playgroundbook/Contents/Chapters/Document1.playgroundchapter/Pages/Challenge3.playgroundpage/Sources/Assessments.swift | 1 | 2497 | //
// Assessments.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
let solution: String? = nil
import PlaygroundSupport
public func assessmentPoint() -> AssessmentResults {
let checker = ContentsChecker(contents: PlaygroundPage.current.text)
var success = "### Amazing job! \nYou just completed Simple Commands. Now it's time to learn about Functions. \n\n[Introduction to Functions](Functions/Introduction)"
var hints = [
"Look at the puzzle world and find the route to the gem that requires the fewest commands.",
"Use the portals to shorten your route.",
"This puzzle is a **Challenge** and has no provided solution. Strengthen your coding skills by creating your own approach to solve it."
]
if checker.numberOfStatements < 9 {
success = "### Incredible Work! \nYou found a solution that almost no one else discovers! \nNow it's time to learn about Functions. \n\n[**Introduction to Functions**](Functions/Introduction)"
} else if checker.numberOfStatements == 9 {
success = "### You found the shortest route! \nCongratulations on finding one of the most efficient solutions to this level!\n\nNow that you've completed Simple Commands, it's time to learn about Functions. \n\n[**Introduction to Functions**](Functions/Introduction)"
} else if checker.numberOfStatements > 9 && checker.numberOfStatements <= 13 {
success = "### Nice job! \nYou found the second shortest solution. You can move on to learn about Functions, but as an added challenge, can you find an even shorter way to solve this puzzle? \n\n[**Introduction to Functions**](Functions/Introduction)"
hints[0] = "You're on the right track, but there might be a shorter way to solve the puzzle. The portals are color-coded: blue goes to blue and green goes to green. Try again using the green portals for your solution."
} else if checker.numberOfStatements > 13 {
success = "### Good work! \nYou've used your new skills to solve the puzzle. You may move on to learn about Functions, but as an added challenge, can you find an even shorter solution? \n\n[**Introduction to Functions**](Functions/Introduction)"
hints[0] = "There might be an even shorter route available. Think about how you could use the portals to reduce the number of commands you use."
}
return updateAssessment(successMessage: success, failureHints: hints, solution: solution)
}
| mit | 1cc5c1d7308725224a2fca374227b4b0 | 59.902439 | 275 | 0.712455 | 4.615527 | false | false | false | false |
etiennemartin/jugglez | Jugglez/GameOverScene.swift | 1 | 3892 | //
// GameOverScene.swift
// Jugglez
//
// Created by Etienne Martin on 2015-01-18.
// Copyright (c) 2015 Etienne Martin. All rights reserved.
//
import Foundation
import SpriteKit
class GameOverScene: SKScene {
internal var mode: GameMode
internal var score: Int64
internal var foregroundColor: SKColor = SKColor.themeLightBackgroundColor()
private var _homeButton: SKSpriteNode?
private var _retryButton: SKSpriteNode?
private var _highScoreButton: SKSpriteNode?
private var _buttonTapSoundAction = SKAction.playSoundFileNamed("BallTap.wav", waitForCompletion: false)
init(size: CGSize, finalScore: Int64, gameMode: GameMode) {
score = finalScore
mode = gameMode
super.init(size: size)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToView(view: SKView) {
let message = "Game Over!"
// Main Message
let label = SKLabelNode()
label.text = message
label.fontName = SKLabelNode.defaultFontName()
label.fontSize = 60
label.fontColor = foregroundColor
label.position = CGPoint(x: size.width/2, y: (size.height/2) + label.fontSize)
addChild(label)
let oldScore = GameScores.sharedInstance.getScoreForMode(mode)
// Score
let scoreLabel = SKLabelNode()
if oldScore < score {
scoreLabel.text = "New High Score! \(score)"
} else {
scoreLabel.text = "Score: \(score)"
}
scoreLabel.fontName = SKLabelNode.defaultFontName()
scoreLabel.fontSize = 30
scoreLabel.fontColor = foregroundColor
scoreLabel.position = label.position
scoreLabel.position.y -= 60
addChild(scoreLabel)
let buttonWidth = self.size.width / 6
let buttonYOffset = self.size.height / 3
let buttonSize = CGSize(width: 34, height:34)
// Retry Button
_homeButton = SKSpriteNode(imageNamed: "home")
_homeButton?.position = CGPoint(x: buttonWidth * 1.5, y: buttonYOffset)
_homeButton?.size = buttonSize
addChild(_homeButton!)
// Main Menu Button
_retryButton = SKSpriteNode(imageNamed: "retry")
_retryButton?.position = CGPoint(x: buttonWidth * 3, y: buttonYOffset)
_retryButton?.size = buttonSize
addChild(_retryButton!)
// High scores
_highScoreButton = SKSpriteNode(imageNamed: "highscore")
_highScoreButton?.position = CGPoint(x: buttonWidth * 4.5, y: buttonYOffset)
_highScoreButton?.size = buttonSize
addChild(_highScoreButton!)
// Save score
GameScores.sharedInstance.setScoreForMode(mode, score: score)
GameScores.sharedInstance.save()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first!
let location = touch.locationInNode(self)
var scene: SKScene? = nil
let homeButtonRect = _homeButton!.frame
if (CGRectContainsPoint(homeButtonRect, location)) {
scene = IntroScene(size: self.size)
}
let retryButtonRect = _retryButton!.frame
if (CGRectContainsPoint(retryButtonRect, location)) {
scene = GamePlayScene(size: self.size, mode:mode)
}
let highScoreButtonRect = _highScoreButton!.frame
if (CGRectContainsPoint(highScoreButtonRect, location)) {
scene = HighScoreScene(size: self.size)
}
if scene != nil {
self.runAction(_buttonTapSoundAction)
runAction(SKAction.runBlock() {
let reveal = SKTransition.fadeWithColor(self.backgroundColor, duration: 0.75)
self.view?.presentScene(scene!, transition:reveal)
})
}
}
}
| mit | 02753d31267309a5458e97123240b596 | 31.705882 | 108 | 0.636948 | 4.804938 | false | false | false | false |
lifesum/configsum | sdk/ios/Configsum/CodableExtensions/Initialization.swift | 1 | 2560 | //
// Initialization.swift
// Configsum
//
// Created by Michel Tabari on 2017-10-17.
// From https://github.com/zoul/generic-json-swift
import Foundation
extension Metadata {
/// Create a Metadata value from anything. Argument has to be a valid Metadata structure:
/// A `Float`, `Int`, `String`, `Bool`, an `Array` of those types or a `Dictionary`
/// of those types.
public init(_ value: Any) throws {
switch value {
case let num as Float:
self = .number(num)
case let num as Int:
self = .number(Float(num))
case let str as String:
self = .string(str)
case let bool as Bool:
self = .bool(bool)
case let array as [Any]:
self = .array(try array.map(Metadata.init))
case let dict as [String:Any]:
self = .object(try dict.mapValues(Metadata.init))
default:
throw JSONError.decodingError
}
}
}
extension Metadata {
/// Create a Metadata value from a `Codable`. This will give you access to the “raw”
/// encoded Metadata value the `Codable` is serialized into. And hopefully, you could
/// encode the resulting Metadata value and decode the original `Codable` back.
public init<T: Codable>(codable: T) throws {
let encoded = try JSONEncoder().encode(codable)
self = try JSONDecoder().decode(Metadata.self, from: encoded)
}
}
extension Metadata: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = .bool(value)
}
}
extension Metadata: ExpressibleByNilLiteral {
public init(nilLiteral: ()) {
self = .null
}
}
extension Metadata: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Metadata...) {
self = .array(elements)
}
}
extension Metadata: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, Metadata)...) {
var object: [String:Metadata] = [:]
for (k, v) in elements {
object[k] = v
}
self = .object(object)
}
}
extension Metadata: ExpressibleByFloatLiteral {
public init(floatLiteral value: Float) {
self = .number(value)
}
}
extension Metadata: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self = .number(Float(value))
}
}
extension Metadata: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self = .string(value)
}
}
| mit | 9a2211877508ec0bb447cc636d5bce8c | 25.350515 | 93 | 0.616588 | 4.376712 | false | false | false | false |
ilyathewhite/Euler | EulerSketch/EulerSketch/Renderer.swift | 1 | 7952 | //
// Renderer.swift
// Euler
//
// Created by Ilya Belenkiy on 7/1/15.
// Copyright © 2015 Ilya Belenkiy. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import AppKit
#endif
#if os(iOS)
extension CGColorRef {
static func clearColor() -> CGColorRef { return UIColor.clearColor().CGColor }
static func blackColor() -> CGColorRef { return UIColor.blackColor().CGColor }
static func whiteColor() -> CGColorRef { return UIColor.whiteColor().CGColor }
}
#else
extension CGColor {
static func clearColor() -> CGColor { return NSColor.clear.cgColor }
static func blackColor() -> CGColor { return NSColor.black.cgColor }
static func whiteColor() -> CGColor { return NSColor.white.cgColor }
}
#endif
#if os(iOS)
typealias Font = UIFont
extension Font {
static func defaultFontOfSize(pointSize: Double) -> Font {
return Font.systemFontOfSize(CGFloat(pointSize))
}
}
#else
typealias Font = NSFont
extension Font {
static func defaultFontOfSize(_ pointSize: Double) -> Font {
return Font.systemFont(ofSize: CGFloat(pointSize))
}
}
#endif
/// The drawing style for a given figure. It's a class because it is
/// indented to be shared across many figures. Changes in the style need to
/// be applied to all figures that use it.
open class DrawingStyle {
/// The style name.
var name: String!
var fillColor = CGColor.clearColor()
var strokeColor = CGColor.blackColor()
var strokeWidth = 1.0
var useDash = false
var font = Font.defaultFontOfSize(14)
var subscriptFont = Font.defaultFontOfSize(10)
/// The default style for all figures.
public static let regular = DrawingStyle()
/// The default style for points. It's different from `defaultStyle` because
/// otherwise points on figures would not be visible. A typical rendering of
/// a geometric point is a tiny circle.
public static let pointRegular = DrawingStyle.makePointStyle()
/// The emphasized style. Used to draw attention to a partciular part of the sketch.
/// The most common represention is thick black paths.
public static let emphasized = DrawingStyle.makeEmphasizedStyle()
/// The extra style. Used to show additional constructions that are necessary to
/// prove or illustrate the main result. The parts of the sketch that use this style
/// are typically not necessary to describe the problem being solved. The most common
/// represention is dashed gray paths.
public static let extra = DrawingStyle.makeExtraStyle()
fileprivate static func makePointStyle() -> DrawingStyle {
let res = DrawingStyle()
res.name = "PointStyle"
res.fillColor = CGColor.whiteColor()
return res
}
fileprivate static func makeEmphasizedStyle() -> DrawingStyle {
let res = DrawingStyle()
res.name = "Emphasized"
res.strokeWidth *= 2.0
return res
}
fileprivate static func makeExtraStyle() -> DrawingStyle {
let res = DrawingStyle()
res.name = "Extra"
res.useDash = true
return res
}
}
// Convenience functions that connect `Point` to CoreGraphics.
extension Point {
var x_CG: CGFloat { return CGFloat(x) }
var y_CG: CGFloat { return CGFloat(y) }
}
public extension CGPoint {
internal init(_ point: Point) {
self.init(x: point.x, y: point.y)
}
var X: Double { return Double(x) }
var Y: Double { return Double(y) }
}
extension HSPoint {
init(_ point: CGPoint, kind: PointKind = .regular) {
self = HSPoint(Double(point.x), Double(point.y))
self.kind = kind
}
}
/// The renderer protocol that abstracts how the sketch is actually drawn.
protocol Renderer {
/// The pixel to point scale.
var nativeScale: Double { get set }
/// Sets the style for all subsecuent drawing calls until its changed to another style.
func setStyle(_ style: DrawingStyle?)
/// Draws `point` using the current style.
func drawPoint(_ point: Point)
/// Draws the segment paths specified by `points` using the current style.
/// `closed` specifies whether the path is closed or open.
func drawSegmentPath(_ points: [Point], closed: Bool)
/// Draws the segment from `point1` to `point2` using the current style.
func drawSegment(point1: Point, point2: Point)
/// Draws text specified by `str` at a given pointa s origin using the current style.
func drawText(_ str: NSAttributedString, atPoint pnt: Point)
/// Draws an arc with a given center, start point, and a counter-clockwise angle
/// using the current style.
func drawArc(center: Point, startPoint: Point, angle: Double)
/// Draws a full circle with a given center and radius.
func fillCircle(center: Point, radius: Double)
}
extension Renderer {
/// Draws the circle using the arc API.
func drawCircle(center: Point, radius: Double) {
drawArc(center: center, startPoint: HSPoint(center.x + radius, center.y), angle: .pi * 2)
}
/// Draws the segment using the segment path API.
func drawSegment(point1: Point, point2: Point) {
drawSegmentPath([point1, point2], closed: false)
}
}
/// The renderer implementation using CoreGraphics.
struct CGRenderer: Renderer {
var context: CGContext
var nativeScale: Double = 1.0
init(context: CGContext) {
self.context = context
#if os(iOS)
nativeScale = Double(UIScreen.mainScreen().nativeScale)
#else
nativeScale = Double(NSScreen.main!.backingScaleFactor)
#endif
}
func drawPoint(_ point: Point) {
let radius = 3.0
fillCircle(center: point, radius: radius)
drawCircle(center: point, radius: radius)
}
func setStyle(_ drawingStyle: DrawingStyle?) {
let style = drawingStyle ?? .regular
context.setFillColor(style.fillColor)
context.setStrokeColor(style.strokeColor)
context.setLineWidth(CGFloat(style.strokeWidth / nativeScale))
if (style.useDash) {
context.setLineDash(phase: 0, lengths: [6 / CGFloat(nativeScale), 2 / CGFloat(nativeScale)])
}
else {
context.setLineDash(phase: 0, lengths: [])
}
}
func drawSegmentPath(_ points: [Point], closed: Bool) {
guard points.count > 0 else { return }
context.move(to: CGPoint(x: points[0].x_CG, y: points[0].y_CG))
for ii in 1..<points.count {
context.addLine(to: CGPoint(x: points[ii].x_CG, y: points[ii].y_CG))
}
if (closed) {
context.closePath()
}
context.strokePath()
}
func drawText(_ str: NSAttributedString, atPoint pnt: Point) {
let font = str.attribute(.font, at: 0, effectiveRange: nil) as! Font
context.saveGState()
#if os(iOS)
CGContextTranslateCTM(context, pnt.x_CG, pnt.y_CG + font.lineHeight)
CGContextScaleCTM(context, 1.0, -1.0)
#else
let maxHeight = abs(2 * font.descender) + font.ascender + font.leading
context.translateBy(x: pnt.x_CG, y: pnt.y_CG + maxHeight - str.size().height)
#endif
str.draw(at: CGPoint(x: 0, y: 0))
context.restoreGState()
}
func drawArc(center: Point, startPoint: Point, angle: Double) {
context.move(to: CGPoint(x: startPoint.x_CG, y: startPoint.y_CG))
let dx = startPoint.x - center.x
let dy = startPoint.y - center.y
let radius = sqrt(dx * dx + dy * dy)
let startAngle = (dy >= 0.0) ? acos(dx / radius) : 2 * .pi - acos(dx / radius)
context.addArc(center: CGPoint(center), radius: CGFloat(radius), startAngle: CGFloat(startAngle), endAngle: CGFloat(startAngle + angle), clockwise: false)
context.strokePath()
}
func fillCircle(center: Point, radius: Double) {
context.move(to: CGPoint(x: CGFloat(center.x + radius), y: CGFloat(center.y)))
context.addArc(center: CGPoint(center), radius: CGFloat(radius), startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: false)
context.fillPath()
}
}
| mit | 408bf68a716162abdb2c8b492496846f | 32.267782 | 160 | 0.670356 | 4.069089 | false | false | false | false |
Connorrr/ParticleAlarm | IOS/Alarm/Alarm.swift | 1 | 5970 | //
// Alarm.swift
// WeatherAlarm
//
// Created by longyutao on 15-2-28.
// Copyright (c) 2015年 LongGames. All rights reserved.
//
import Foundation
import MediaPlayer
struct Alarm
{
//using memberwise initializer for struct
var label: String
var timeStr: String
var date: Date
var enabled: Bool
var snoozeEnabled: Bool
var UUID: String
var mediaID: String
var mediaLabel: String
var repeatWeekdays: [Int]
}
//singleton, for-in loop supporting
class Alarms: Sequence
{
fileprivate let ud:UserDefaults
fileprivate let alarmKey:String
fileprivate var alarms:[Alarm] = [Alarm]()
//ensure can not be instantiated outside
fileprivate init()
{
ud = UserDefaults.standard
// for key in ud.dictionaryRepresentation().keys {
// NSUserDefaults.standardUserDefaults().removeObjectForKey(key.description)
// }
alarmKey = "myAlarmKey"
alarms = getAllAlarm()
}
//above swift 1.2
static let sharedInstance = Alarms()
//setObject only support "property list objects",so we cannot persist alarms directly
func append(_ alarm: Alarm)
{
alarms.append(alarm)
PersistAlarm(alarm, index: alarms.count-1)
}
func PersistAlarm(_ alarm: Alarm, index: Int)
{
var alarmArray = ud.array(forKey: alarmKey) ?? []
alarmArray.append(["label": alarm.label, "timeStr": alarm.timeStr, "date": alarm.date, "enabled": alarm.enabled, "snoozeEnabled": alarm.snoozeEnabled, "UUID": alarm.UUID, "mediaID": alarm.mediaID, "mediaLabel": Alarms.sharedInstance[index].mediaLabel, "repeatWeekdays": alarm.repeatWeekdays])
ud.set(alarmArray, forKey: alarmKey)
ud.synchronize()
}
func PersistAlarm(_ index: Int)
{
var alarmArray = ud.array(forKey: alarmKey) ?? []
alarmArray[index] = ["label": Alarms.sharedInstance[index].label, "timeStr": Alarms.sharedInstance[index].timeStr, "date": Alarms.sharedInstance[index].date, "enabled": Alarms.sharedInstance[index].enabled, "snoozeEnabled": Alarms.sharedInstance[index].snoozeEnabled, "UUID": Alarms.sharedInstance[index].UUID, "mediaID": Alarms.sharedInstance[index].mediaID, "mediaLabel": Alarms.sharedInstance[index].mediaLabel, "repeatWeekdays": Alarms.sharedInstance[index].repeatWeekdays]
ud.set(alarmArray, forKey: alarmKey)
ud.synchronize()
}
func deleteAlarm(_ index: Int)
{
var alarmArray = ud.array(forKey: alarmKey) ?? []
alarmArray.remove(at: index)
ud.set(alarmArray, forKey: alarmKey)
ud.synchronize()
}
//helper, convert dictionary to [Alarm]
//better if we can get the property name as a string, but Swift does not have any reflection feature now...
fileprivate func getAllAlarm() -> [Alarm]
{
let alarmArray = UserDefaults.standard.array(forKey: alarmKey)
if alarmArray != nil{
let items = alarmArray!
return (items as! Array<Dictionary<String, AnyObject>>).map(){item in Alarm(label: item["label"] as! String, timeStr: item["timeStr"] as! String, date: item["date"] as! Date, enabled: item["enabled"] as! Bool, snoozeEnabled: item["snoozeEnabled"] as! Bool, UUID: item["UUID"] as! String, mediaID: item["mediaID"] as! String, mediaLabel: item["mediaLabel"] as! String, repeatWeekdays: item["repeatWeekdays"] as! [Int])}
}
else
{
return [Alarm]()
}
}
var count:Int
{
return alarms.count
}
func removeAtIndex(_ index: Int)
{
alarms.remove(at: index)
}
subscript(index: Int) -> Alarm{
get{
assert((index < alarms.count && index >= 0), "Index out of range")
return alarms[index]
}
set{
assert((index < alarms.count && index >= 0), "Index out of range")
alarms[index] = newValue
}
}
//helpers for alarm edit. maybe not a good design
func labelAtIndex(_ index: Int) -> String
{
return alarms[index].label
}
func timeStrAtIndex(_ index: Int) -> String
{
return alarms[index].timeStr
}
func dateAtIndex(_ index: Int) -> Date
{
return alarms[index].date
}
func UUIDAtIndex(_ index: Int) -> String
{
return alarms[index].UUID
}
func enabledAtIndex(_ index: Int) -> Bool
{
return alarms[index].enabled
}
func mediaIDAtIndex(_ index: Int) -> String
{
return alarms[index].mediaID
}
func setLabel(_ label: String, AtIndex index: Int)
{
alarms[index].label = label
}
func setDate(_ date: Date, AtIndex index: Int)
{
alarms[index].date = date
}
func setTimeStr(_ timeStr: String, AtIndex index: Int)
{
alarms[index].timeStr = timeStr
}
func setMediaID(_ mediaID: String, AtIndex index: Int)
{
alarms[index].mediaID = mediaID
}
func setMediaLabel(_ mediaLabel: String, AtIndex index: Int)
{
alarms[index].mediaLabel = mediaLabel
}
func setEnabled(_ enabled: Bool, AtIndex index: Int)
{
alarms[index].enabled = enabled
}
func setSnooze(_ snoozeEnabled: Bool, AtIndex index: Int)
{
alarms[index].snoozeEnabled = snoozeEnabled
}
func setWeekdays(_ weekdays: [Int], AtIndex index: Int)
{
alarms[index].repeatWeekdays = weekdays
}
var isEmpty: Bool
{
return alarms.isEmpty
}
//SequenceType Protocol
fileprivate var currentIndex = 0
func makeIterator() -> AnyIterator<Alarm> {
let anyIter = AnyIterator(){self.currentIndex < self.alarms.count ? self.alarms[self.currentIndex] : nil}
self.currentIndex = self.currentIndex + 1
return anyIter
}
}
| mit | 3dba0e65dd28bdd2688352b1139cd331 | 28.544554 | 485 | 0.615449 | 4.430586 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/DAO/BatchFetch/Galleries/FavoriteGalleriesQueueBatchFetcher.swift | 1 | 4816 | //
// FavoriteGalleriesQueueBatchFetcher.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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.
//
class FavoriteGalleriesQueueBatchFetcher: Cancelable {
private let pageSize = 20
private let requestSender: RequestSender
private let completion: GalleriesBatchClosure?
private var operationQueue: OperationQueue?
private var firstRequestHandler: RequestHandler?
private var objectsByPage: Dictionary<PagingData, Array<Gallery>>
private var errorsByPage: Dictionary<PagingData, APIClientError>
init(requestSender: RequestSender, completion: GalleriesBatchClosure?) {
self.requestSender = requestSender
self.completion = completion
self.objectsByPage = Dictionary<PagingData, Array<Gallery>>()
self.errorsByPage = Dictionary<PagingData, APIClientError>()
}
func cancel() {
operationQueue?.cancelAllOperations()
firstRequestHandler?.cancel()
}
func fetch() -> RequestHandler {
guard operationQueue == nil
else {
assert(false) //Fetch should be called only once
return RequestHandler(object: self)
}
let request = FavoriteGalleriesRequest(page: 1, perPage: pageSize)
let handler = GalleriesResponseHandler {
[weak self](galleries, pagingInfo, error) -> (Void) in
guard let strongSelf = self
else { return }
if let galleries = galleries,
let pagingInfo = pagingInfo {
strongSelf.objectsByPage[PagingData(page: 1, pageSize: strongSelf.pageSize)] = galleries
strongSelf.prepareBlockOperations(pagingInfo: pagingInfo)
} else {
strongSelf.completion?(nil, error)
}
}
firstRequestHandler = requestSender.send(request, withResponseHandler: handler)
return RequestHandler(object: self)
}
private func prepareBlockOperations(pagingInfo: PagingInfo) {
operationQueue = OperationQueue()
operationQueue!.maxConcurrentOperationCount = 4
let finishOperation = BlockOperation()
finishOperation.addExecutionBlock {
[unowned finishOperation, weak self] in
guard let strongSelf = self, !finishOperation.isCancelled else { return }
let objects = strongSelf.objectsByPage.sorted(by: { $0.key.page > $1.key.page }).flatMap({ $0.value })
let error = strongSelf.errorsByPage.values.first
DispatchQueue.main.async {
[weak self] in
self?.completion?(objects, error)
}
}
if pagingInfo.totalPages > 1 {
for page in 2...pagingInfo.totalPages {
let pagingData = PagingData(page: page, pageSize: pageSize)
let operation = FavoriteGalleriesBatchFetchOperation(requestSender: requestSender, pagingData: pagingData) {
[weak self](operation, error) in
guard let strongSelf = self,
let operation = operation as? FavoriteGalleriesBatchFetchOperation
else { return }
if let galleries = operation.galleries {
strongSelf.objectsByPage[operation.pagingData] = galleries
}
if let error = error as? APIClientError {
strongSelf.errorsByPage[operation.pagingData] = error
}
}
finishOperation.addDependency(operation)
operationQueue!.addOperation(operation)
}
}
operationQueue!.addOperation(finishOperation)
}
}
| mit | 490023a790eced6b4a8143e94ccfb0b1 | 40.517241 | 124 | 0.652201 | 5.234783 | false | false | false | false |
banxi1988/Staff | Pods/BXForm/Pod/Classes/Cells/LoginButtonCell.swift | 1 | 2533 | //
// LoginButtonCell.swift
// Pods
//
// Created by Haizhen Lee on 16/1/23.
//
//
import UIKit
import BXModel
import BXiOSUtils
import PinAuto
//-LoginButtonCell:stc
//login[t18,l10,r10,h50](cw,f18,text=登录):b
//reg[at10@login,bl14@login](f15,ctt,text=快速注册):b
//reset[bf10@login,y@reg](f15,ctt,text=忘记密码):b
public class LoginButtonCell : StaticTableViewCell{
public let loginButton = UIButton(type:.System)
public let regButton = UIButton(type:.System)
public let resetButton = UIButton(type:.System)
public convenience init() {
self.init(style: .Default, reuseIdentifier: "LoginButtonCellCell")
}
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
public override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
var allOutlets :[UIView]{
return [loginButton,regButton,resetButton]
}
var allUIButtonOutlets :[UIButton]{
return [loginButton,regButton,resetButton]
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public func commonInit(){
staticHeight = 120
frame = CGRect(x: 0, y: 0, width: 320, height: staticHeight)
for childView in allOutlets{
contentView.addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
}
installConstaints()
setupAttrs()
}
public func installConstaints(){
loginButton.pa_height.eq(50).install()
loginButton.pa_trailing.eq(10).install()
loginButton.pa_top.eq(5).install()
loginButton.pa_leading.eq(10).install()
regButton.pa_below(loginButton,offset:14).install()
regButton.pa_leading.to(loginButton).offset(10).install()
resetButton.pa_centerY.to(regButton).install()
resetButton.pa_trailing.to(loginButton).offset(10).install()
}
public func setupAttrs(){
loginButton.setTitle("登录",forState: .Normal)
loginButton.setTitleColor(UIColor.whiteColor(),forState: .Normal)
loginButton.titleLabel?.font = UIFont.systemFontOfSize(18)
regButton.setTitleColor(FormColors.tertiaryTextColor,forState: .Normal)
regButton.setTitle("快速注册",forState: .Normal)
regButton.titleLabel?.font = UIFont.systemFontOfSize(15)
resetButton.setTitleColor(FormColors.tertiaryTextColor,forState: .Normal)
resetButton.setTitle("忘记密码",forState: .Normal)
resetButton.titleLabel?.font = UIFont.systemFontOfSize(15)
}
}
| mit | c2ef9468e3b92abadc06dba254d8ec46 | 29.402439 | 79 | 0.722423 | 3.969745 | false | false | false | false |
frootloops/swift | stdlib/public/SDK/Foundation/NSStringAPI.swift | 6 | 76869 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Exposing the API of NSString on Swift's String
//
//===----------------------------------------------------------------------===//
// Important Note
// ==============
//
// This file is shared between two projects:
//
// 1. https://github.com/apple/swift/tree/master/stdlib/public/SDK/Foundation
// 2. https://github.com/apple/swift-corelibs-foundation/tree/master/Foundation
//
// If you change this file, you must update it in both places.
#if !DEPLOYMENT_RUNTIME_SWIFT
@_exported import Foundation // Clang module
#endif
// Open Issues
// ===========
//
// Property Lists need to be properly bridged
//
func _toNSArray<T, U : AnyObject>(_ a: [T], f: (T) -> U) -> NSArray {
let result = NSMutableArray(capacity: a.count)
for s in a {
result.add(f(s))
}
return result
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// We only need this for UnsafeMutablePointer, but there's not currently a way
// to write that constraint.
extension Optional {
/// Invokes `body` with `nil` if `self` is `nil`; otherwise, passes the
/// address of `object` to `body`.
///
/// This is intended for use with Foundation APIs that return an Objective-C
/// type via out-parameter where it is important to be able to *ignore* that
/// parameter by passing `nil`. (For some APIs, this may allow the
/// implementation to avoid some work.)
///
/// In most cases it would be simpler to just write this code inline, but if
/// `body` is complicated than that results in unnecessarily repeated code.
internal func _withNilOrAddress<NSType : AnyObject, ResultType>(
of object: inout NSType?,
_ body:
(AutoreleasingUnsafeMutablePointer<NSType?>?) -> ResultType
) -> ResultType {
return self == nil ? body(nil) : body(&object)
}
}
#endif
extension String {
//===--- Class Methods --------------------------------------------------===//
//===--------------------------------------------------------------------===//
// @property (class) const NSStringEncoding *availableStringEncodings;
/// An array of the encodings that strings support in the application's
/// environment.
public static var availableStringEncodings: [Encoding] {
var result = [Encoding]()
var p = NSString.availableStringEncodings
while p.pointee != 0 {
result.append(Encoding(rawValue: p.pointee))
p += 1
}
return result
}
// @property (class) NSStringEncoding defaultCStringEncoding;
/// The C-string encoding assumed for any method accepting a C string as an
/// argument.
public static var defaultCStringEncoding: Encoding {
return Encoding(rawValue: NSString.defaultCStringEncoding)
}
// + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
/// Returns a human-readable string giving the name of the specified encoding.
///
/// - Parameter encoding: A string encoding. For possible values, see
/// `String.Encoding`.
/// - Returns: A human-readable string giving the name of `encoding` in the
/// current locale.
public static func localizedName(
of encoding: Encoding
) -> String {
return NSString.localizedName(of: encoding.rawValue)
}
// + (instancetype)localizedStringWithFormat:(NSString *)format, ...
/// Returns a string created by using a given format string as a
/// template into which the remaining argument values are substituted
/// according to the user's default locale.
public static func localizedStringWithFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
return String(format: format, locale: Locale.current,
arguments: arguments)
}
//===--------------------------------------------------------------------===//
// NSString factory functions that have a corresponding constructor
// are omitted.
//
// + (instancetype)string
//
// + (instancetype)
// stringWithCharacters:(const unichar *)chars length:(NSUInteger)length
//
// + (instancetype)stringWithFormat:(NSString *)format, ...
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithCString:(const char *)cString
// encoding:(NSStringEncoding)enc
//===--------------------------------------------------------------------===//
//===--- Adds nothing for String beyond what String(s) does -------------===//
// + (instancetype)stringWithString:(NSString *)aString
//===--------------------------------------------------------------------===//
// + (instancetype)stringWithUTF8String:(const char *)bytes
/// Creates a string by copying the data from a given
/// C array of UTF8-encoded bytes.
public init?(utf8String bytes: UnsafePointer<CChar>) {
if let ns = NSString(utf8String: bytes) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
}
extension String {
//===--- Already provided by String's core ------------------------------===//
// - (instancetype)init
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithBytes:(const void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
/// Creates a new string equivalent to the given bytes interpreted in the
/// specified encoding.
///
/// - Parameters:
/// - bytes: A sequence of bytes to interpret using `encoding`.
/// - encoding: The ecoding to use to interpret `bytes`.
public init? <S: Sequence>(bytes: S, encoding: Encoding)
where S.Iterator.Element == UInt8 {
let byteArray = Array(bytes)
if let ns = NSString(
bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// - (instancetype)
// initWithBytesNoCopy:(void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
// freeWhenDone:(BOOL)flag
/// Creates a new string that contains the specified number of bytes from the
/// given buffer, interpreted in the specified encoding, and optionally
/// frees the buffer.
///
/// - Warning: This initializer is not memory-safe!
public init?(
bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int,
encoding: Encoding, freeWhenDone flag: Bool
) {
if let ns = NSString(
bytesNoCopy: bytes, length: length, encoding: encoding.rawValue,
freeWhenDone: flag) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// - (instancetype)
// initWithCharacters:(const unichar *)characters
// length:(NSUInteger)length
/// Creates a new string that contains the specified number of characters
/// from the given C array of Unicode characters.
public init(
utf16CodeUnits: UnsafePointer<unichar>,
count: Int
) {
self = String._unconditionallyBridgeFromObjectiveC(NSString(characters: utf16CodeUnits, length: count))
}
// - (instancetype)
// initWithCharactersNoCopy:(unichar *)characters
// length:(NSUInteger)length
// freeWhenDone:(BOOL)flag
/// Creates a new string that contains the specified number of characters
/// from the given C array of UTF-16 code units.
public init(
utf16CodeUnitsNoCopy: UnsafePointer<unichar>,
count: Int,
freeWhenDone flag: Bool
) {
self = String._unconditionallyBridgeFromObjectiveC(NSString(
charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy),
length: count,
freeWhenDone: flag))
}
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
/// Produces a string created by reading data from the file at a
/// given path interpreted using a given encoding.
public init(
contentsOfFile path: String,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from the file at
/// a given path and returns by reference the encoding used to
/// interpret the file.
public init(
contentsOfFile path: String,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOfFile: path, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
public init(
contentsOfFile path: String
) throws {
let ns = try NSString(contentsOfFile: path, usedEncoding: nil)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError**)error
/// Produces a string created by reading data from a given URL
/// interpreted using a given encoding. Errors are written into the
/// inout `error` argument.
public init(
contentsOf url: URL,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOf: url, encoding: enc.rawValue)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from a given URL
/// and returns by reference the encoding used to interpret the
/// data. Errors are written into the inout `error` argument.
public init(
contentsOf url: URL,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
public init(
contentsOf url: URL
) throws {
let ns = try NSString(contentsOf: url, usedEncoding: nil)
self = String._unconditionallyBridgeFromObjectiveC(ns)
}
// - (instancetype)
// initWithCString:(const char *)nullTerminatedCString
// encoding:(NSStringEncoding)encoding
/// Produces a string containing the bytes in a given C array,
/// interpreted according to a given encoding.
public init?(
cString: UnsafePointer<CChar>,
encoding enc: Encoding
) {
if let ns = NSString(cString: cString, encoding: enc.rawValue) {
self = String._unconditionallyBridgeFromObjectiveC(ns)
} else {
return nil
}
}
// FIXME: handle optional locale with default arguments
// - (instancetype)
// initWithData:(NSData *)data
// encoding:(NSStringEncoding)encoding
/// Returns a `String` initialized by converting given `data` into
/// Unicode characters using a given `encoding`.
public init?(data: Data, encoding: Encoding) {
guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil }
self = String._unconditionallyBridgeFromObjectiveC(s)
}
// - (instancetype)initWithFormat:(NSString *)format, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted.
public init(format: String, _ arguments: CVarArg...) {
self = String(format: format, arguments: arguments)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to the user's default locale.
public init(format: String, arguments: [CVarArg]) {
self = String(format: format, locale: nil, arguments: arguments)
}
// - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: Locale?, _ args: CVarArg...) {
self = String(format: format, locale: locale, arguments: args)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// locale:(id)locale
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: Locale?, arguments: [CVarArg]) {
#if DEPLOYMENT_RUNTIME_SWIFT
self = withVaList(arguments) {
String._unconditionallyBridgeFromObjectiveC(
NSString(format: format, locale: locale?._bridgeToObjectiveC(), arguments: $0)
)
}
#else
self = withVaList(arguments) {
NSString(format: format, locale: locale, arguments: $0) as String
}
#endif
}
}
extension StringProtocol where Index == String.Index {
//===--- Bridging Helpers -----------------------------------------------===//
//===--------------------------------------------------------------------===//
/// The corresponding `NSString` - a convenience for bridging code.
// FIXME(strings): There is probably a better way to bridge Self to NSString
var _ns: NSString {
return self._ephemeralString._bridgeToObjectiveC()
}
// self can be a Substring so we need to subtract/add this offset when
// passing _ns to the Foundation APIs. Will be 0 if self is String.
@_inlineable
@_versioned
internal var _substringOffset: Int {
return self.startIndex.encodedOffset
}
/// Return an `Index` corresponding to the given offset in our UTF-16
/// representation.
func _index(_ utf16Index: Int) -> Index {
return Index(encodedOffset: utf16Index + _substringOffset)
}
@_inlineable
@_versioned
internal func _toRelativeNSRange(_ r: Range<String.Index>) -> NSRange {
return NSRange(
location: r.lowerBound.encodedOffset - _substringOffset,
length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset)
}
/// Return a `Range<Index>` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _range(_ r: NSRange) -> Range<Index> {
return _index(r.location)..<_index(r.location + r.length)
}
/// Return a `Range<Index>?` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _optionalRange(_ r: NSRange) -> Range<Index>? {
if r.location == NSNotFound {
return nil
}
return _range(r)
}
/// Invoke `body` on an `Int` buffer. If `index` was converted from
/// non-`nil`, convert the buffer to an `Index` and write it into the
/// memory referred to by `index`
func _withOptionalOutParameter<Result>(
_ index: UnsafeMutablePointer<Index>?,
_ body: (UnsafeMutablePointer<Int>?) -> Result
) -> Result {
var utf16Index: Int = 0
let result = (index != nil ? body(&utf16Index) : body(nil))
index?.pointee = _index(utf16Index)
return result
}
/// Invoke `body` on an `NSRange` buffer. If `range` was converted
/// from non-`nil`, convert the buffer to a `Range<Index>` and write
/// it into the memory referred to by `range`
func _withOptionalOutParameter<Result>(
_ range: UnsafeMutablePointer<Range<Index>>?,
_ body: (UnsafeMutablePointer<NSRange>?) -> Result
) -> Result {
var nsRange = NSRange(location: 0, length: 0)
let result = (range != nil ? body(&nsRange) : body(nil))
range?.pointee = self._range(nsRange)
return result
}
//===--- Instance Methods/Properties-------------------------------------===//
//===--------------------------------------------------------------------===//
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// @property BOOL boolValue;
// - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
/// Returns a Boolean value that indicates whether the string can be
/// converted to the specified encoding without loss of information.
///
/// - Parameter encoding: A string encoding.
/// - Returns: `true` if the string can be encoded in `encoding` without loss
/// of information; otherwise, `false`.
public func canBeConverted(to encoding: String.Encoding) -> Bool {
return _ns.canBeConverted(to: encoding.rawValue)
}
// @property NSString* capitalizedString
/// A copy of the string with each word changed to its corresponding
/// capitalized spelling.
///
/// This property performs the canonical (non-localized) mapping. It is
/// suitable for programming operations that require stable results not
/// depending on the current locale.
///
/// A capitalized string is a string with the first character in each word
/// changed to its corresponding uppercase value, and all remaining
/// characters set to their corresponding lowercase values. A "word" is any
/// sequence of characters delimited by spaces, tabs, or line terminators.
/// Some common word delimiting punctuation isn't considered, so this
/// property may not generally produce the desired results for multiword
/// strings. See the `getLineStart(_:end:contentsEnd:for:)` method for
/// additional information.
///
/// Case transformations aren’t guaranteed to be symmetrical or to produce
/// strings of the same lengths as the originals.
public var capitalized: String {
return _ns.capitalized as String
}
// @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0);
/// A capitalized representation of the string that is produced
/// using the current locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedCapitalized: String {
return _ns.localizedCapitalized
}
// - (NSString *)capitalizedStringWithLocale:(Locale *)locale
/// Returns a capitalized representation of the string
/// using the specified locale.
public func capitalized(with locale: Locale?) -> String {
return _ns.capitalized(with: locale) as String
}
// - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
/// Returns the result of invoking `compare:options:` with
/// `NSCaseInsensitiveSearch` as the only option.
public func caseInsensitiveCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.caseInsensitiveCompare(aString._ephemeralString)
}
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// - (unichar)characterAtIndex:(NSUInteger)index
//
// We have a different meaning for "Character" in Swift, and we are
// trying not to expose error-prone UTF-16 integer indexes
// - (NSString *)
// commonPrefixWithString:(NSString *)aString
// options:(StringCompareOptions)mask
/// Returns a string containing characters this string and the
/// given string have in common, starting from the beginning of each
/// up to the first characters that aren't equivalent.
public func commonPrefix<
T : StringProtocol
>(with aString: T, options: String.CompareOptions = []) -> String {
return _ns.commonPrefix(with: aString._ephemeralString, options: options)
}
// - (NSComparisonResult)
// compare:(NSString *)aString
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range locale:(id)locale
/// Compares the string using the specified options and
/// returns the lexical ordering for the range.
public func compare<T : StringProtocol>(
_ aString: T,
options mask: String.CompareOptions = [],
range: Range<Index>? = nil,
locale: Locale? = nil
) -> ComparisonResult {
// According to Ali Ozer, there may be some real advantage to
// dispatching to the minimal selector for the supplied options.
// So let's do that; the switch should compile away anyhow.
let aString = aString._ephemeralString
return locale != nil ? _ns.compare(
aString,
options: mask,
range: _toRelativeNSRange(
range ?? startIndex..<endIndex
),
locale: locale?._bridgeToObjectiveC()
)
: range != nil ? _ns.compare(
aString,
options: mask,
range: _toRelativeNSRange(range!)
)
: !mask.isEmpty ? _ns.compare(aString, options: mask)
: _ns.compare(aString)
}
// - (NSUInteger)
// completePathIntoString:(NSString **)outputName
// caseSensitive:(BOOL)flag
// matchesIntoArray:(NSArray **)outputArray
// filterTypes:(NSArray *)filterTypes
/// Interprets the string as a path in the file system and
/// attempts to perform filename completion, returning a numeric
/// value that indicates whether a match was possible, and by
/// reference the longest path that matches the string.
///
/// - Returns: The actual number of matching paths.
public func completePath(
into outputName: UnsafeMutablePointer<String>? = nil,
caseSensitive: Bool,
matchesInto outputArray: UnsafeMutablePointer<[String]>? = nil,
filterTypes: [String]? = nil
) -> Int {
#if DEPLOYMENT_RUNTIME_SWIFT
var outputNamePlaceholder: String?
var outputArrayPlaceholder = [String]()
let res = self._ns.completePath(
into: &outputNamePlaceholder,
caseSensitive: caseSensitive,
matchesInto: &outputArrayPlaceholder,
filterTypes: filterTypes
)
if let n = outputNamePlaceholder {
outputName?.pointee = n
} else {
outputName?.pointee = ""
}
outputArray?.pointee = outputArrayPlaceholder
return res
#else // DEPLOYMENT_RUNTIME_SWIFT
var nsMatches: NSArray?
var nsOutputName: NSString?
let result: Int = outputName._withNilOrAddress(of: &nsOutputName) {
outputName in outputArray._withNilOrAddress(of: &nsMatches) {
outputArray in
// FIXME: completePath(...) is incorrectly annotated as requiring
// non-optional output parameters. rdar://problem/25494184
let outputNonOptionalName = unsafeBitCast(
outputName, to: AutoreleasingUnsafeMutablePointer<NSString?>.self)
let outputNonOptionalArray = unsafeBitCast(
outputArray, to: AutoreleasingUnsafeMutablePointer<NSArray?>.self)
return self._ns.completePath(
into: outputNonOptionalName,
caseSensitive: caseSensitive,
matchesInto: outputNonOptionalArray,
filterTypes: filterTypes
)
}
}
if let matches = nsMatches {
// Since this function is effectively a bridge thunk, use the
// bridge thunk semantics for the NSArray conversion
outputArray?.pointee = matches as! [String]
}
if let n = nsOutputName {
outputName?.pointee = n as String
}
return result
#endif // DEPLOYMENT_RUNTIME_SWIFT
}
// - (NSArray *)
// componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
/// Returns an array containing substrings from the string
/// that have been divided by characters in the given set.
public func components(separatedBy separator: CharacterSet) -> [String] {
return _ns.components(separatedBy: separator)
}
// - (NSArray *)componentsSeparatedByString:(NSString *)separator
/// Returns an array containing substrings from the string that have been
/// divided by the given separator.
///
/// The substrings in the resulting array appear in the same order as the
/// original string. Adjacent occurrences of the separator string produce
/// empty strings in the result. Similarly, if the string begins or ends
/// with the separator, the first or last substring, respectively, is empty.
/// The following example shows this behavior:
///
/// let list1 = "Karin, Carrie, David"
/// let items1 = list1.components(separatedBy: ", ")
/// // ["Karin", "Carrie", "David"]
///
/// // Beginning with the separator:
/// let list2 = ", Norman, Stanley, Fletcher"
/// let items2 = list2.components(separatedBy: ", ")
/// // ["", "Norman", "Stanley", "Fletcher"
///
/// If the list has no separators, the array contains only the original
/// string itself.
///
/// let name = "Karin"
/// let list = name.components(separatedBy: ", ")
/// // ["Karin"]
///
/// - Parameter separator: The separator string.
/// - Returns: An array containing substrings that have been divided from the
/// string using `separator`.
// FIXME(strings): now when String conforms to Collection, this can be
// replaced by split(separator:maxSplits:omittingEmptySubsequences:)
public func components<
T : StringProtocol
>(separatedBy separator: T) -> [String] {
return _ns.components(separatedBy: separator._ephemeralString)
}
// - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the string as a C string
/// using a given encoding.
public func cString(using encoding: String.Encoding) -> [CChar]? {
return withExtendedLifetime(_ns) {
(s: NSString) -> [CChar]? in
_persistCString(s.cString(using: encoding.rawValue))
}
}
// - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
//
// - (NSData *)
// dataUsingEncoding:(NSStringEncoding)encoding
// allowLossyConversion:(BOOL)flag
/// Returns a `Data` containing a representation of
/// the `String` encoded using a given encoding.
public func data(
using encoding: String.Encoding,
allowLossyConversion: Bool = false
) -> Data? {
return _ns.data(
using: encoding.rawValue,
allowLossyConversion: allowLossyConversion)
}
// @property NSString* decomposedStringWithCanonicalMapping;
/// A string created by normalizing the string's contents using Form D.
public var decomposedStringWithCanonicalMapping: String {
return _ns.decomposedStringWithCanonicalMapping
}
// @property NSString* decomposedStringWithCompatibilityMapping;
/// A string created by normalizing the string's contents using Form KD.
public var decomposedStringWithCompatibilityMapping: String {
return _ns.decomposedStringWithCompatibilityMapping
}
//===--- Importing Foundation should not affect String printing ---------===//
// Therefore, we're not exposing this:
//
// @property NSString* description
//===--- Omitted for consistency with API review results 5/20/2014 -----===//
// @property double doubleValue;
// - (void)
// enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block
/// Enumerates all the lines in a string.
public func enumerateLines(
invoking body: @escaping (_ line: String, _ stop: inout Bool) -> Void
) {
_ns.enumerateLines {
(line: String, stop: UnsafeMutablePointer<ObjCBool>)
in
var stop_ = false
body(line, &stop_)
if stop_ {
stop.pointee = true
}
}
}
// @property NSStringEncoding fastestEncoding;
/// The fastest encoding to which the string can be converted without loss
/// of information.
public var fastestEncoding: String.Encoding {
return String.Encoding(rawValue: _ns.fastestEncoding)
}
// - (BOOL)
// getCString:(char *)buffer
// maxLength:(NSUInteger)maxBufferCount
// encoding:(NSStringEncoding)encoding
/// Converts the `String`'s content to a given encoding and
/// stores them in a buffer.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
public func getCString(
_ buffer: inout [CChar], maxLength: Int, encoding: String.Encoding
) -> Bool {
return _ns.getCString(&buffer,
maxLength: Swift.min(buffer.count, maxLength),
encoding: encoding.rawValue)
}
// - (NSUInteger)hash
/// An unsigned integer that can be used as a hash table address.
public var hash: Int {
return _ns.hash
}
// - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the number of bytes required to store the
/// `String` in a given encoding.
public func lengthOfBytes(using encoding: String.Encoding) -> Int {
return _ns.lengthOfBytes(using: encoding.rawValue)
}
// - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString
/// Compares the string and the given string using a case-insensitive,
/// localized, comparison.
public
func localizedCaseInsensitiveCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.localizedCaseInsensitiveCompare(aString._ephemeralString)
}
// - (NSComparisonResult)localizedCompare:(NSString *)aString
/// Compares the string and the given string using a localized comparison.
public func localizedCompare<
T : StringProtocol
>(_ aString: T) -> ComparisonResult {
return _ns.localizedCompare(aString._ephemeralString)
}
/// Compares the string and the given string as sorted by the Finder.
public func localizedStandardCompare<
T : StringProtocol
>(_ string: T) -> ComparisonResult {
return _ns.localizedStandardCompare(string._ephemeralString)
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property long long longLongValue
// @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0);
/// A lowercase version of the string that is produced using the current
/// locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedLowercase: String {
return _ns.localizedLowercase
}
// - (NSString *)lowercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to lowercase, taking into account the specified
/// locale.
public func lowercased(with locale: Locale?) -> String {
return _ns.lowercased(with: locale)
}
// - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the maximum number of bytes needed to store the
/// `String` in a given encoding.
public
func maximumLengthOfBytes(using encoding: String.Encoding) -> Int {
return _ns.maximumLengthOfBytes(using: encoding.rawValue)
}
// @property NSString* precomposedStringWithCanonicalMapping;
/// A string created by normalizing the string's contents using Form C.
public var precomposedStringWithCanonicalMapping: String {
return _ns.precomposedStringWithCanonicalMapping
}
// @property NSString * precomposedStringWithCompatibilityMapping;
/// A string created by normalizing the string's contents using Form KC.
public var precomposedStringWithCompatibilityMapping: String {
return _ns.precomposedStringWithCompatibilityMapping
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (id)propertyList
/// Parses the `String` as a text representation of a
/// property list, returning an NSString, NSData, NSArray, or
/// NSDictionary object, according to the topmost element.
public func propertyList() -> Any {
return _ns.propertyList()
}
// - (NSDictionary *)propertyListFromStringsFileFormat
/// Returns a dictionary object initialized with the keys and
/// values found in the `String`.
public func propertyListFromStringsFileFormat() -> [String : String] {
return _ns.propertyListFromStringsFileFormat() as! [String : String]? ?? [:]
}
#endif
// - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Returns a Boolean value indicating whether the string contains the given
/// string, taking the current locale into account.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@available(OSX 10.11, iOS 9.0, *)
public func localizedStandardContains<
T : StringProtocol
>(_ string: T) -> Bool {
return _ns.localizedStandardContains(string._ephemeralString)
}
// @property NSStringEncoding smallestEncoding;
/// The smallest encoding to which the string can be converted without
/// loss of information.
public var smallestEncoding: String.Encoding {
return String.Encoding(rawValue: _ns.smallestEncoding)
}
// - (NSString *)
// stringByAddingPercentEncodingWithAllowedCharacters:
// (NSCharacterSet *)allowedCharacters
/// Returns a new string created by replacing all characters in the string
/// not in the specified set with percent encoded characters.
public func addingPercentEncoding(
withAllowedCharacters allowedCharacters: CharacterSet
) -> String? {
// FIXME: the documentation states that this method can return nil if the
// transformation is not possible, without going into further details. The
// implementation can only return nil if malloc() returns nil, so in
// practice this is not possible. Still, to be consistent with
// documentation, we declare the method as returning an optional String.
//
// <rdar://problem/17901698> Docs for -[NSString
// stringByAddingPercentEncodingWithAllowedCharacters] don't precisely
// describe when return value is nil
return _ns.addingPercentEncoding(withAllowedCharacters:
allowedCharacters
)
}
// - (NSString *)stringByAppendingFormat:(NSString *)format, ...
/// Returns a string created by appending a string constructed from a given
/// format string and the following arguments.
public func appendingFormat<
T : StringProtocol
>(
_ format: T, _ arguments: CVarArg...
) -> String {
return _ns.appending(
String(format: format._ephemeralString, arguments: arguments))
}
// - (NSString *)stringByAppendingString:(NSString *)aString
/// Returns a new string created by appending the given string.
// FIXME(strings): shouldn't it be deprecated in favor of `+`?
public func appending<
T : StringProtocol
>(_ aString: T) -> String {
return _ns.appending(aString._ephemeralString)
}
/// Returns a string with the given character folding options
/// applied.
public func folding(
options: String.CompareOptions = [], locale: Locale?
) -> String {
return _ns.folding(options: options, locale: locale)
}
// - (NSString *)stringByPaddingToLength:(NSUInteger)newLength
// withString:(NSString *)padString
// startingAtIndex:(NSUInteger)padIndex
/// Returns a new string formed from the `String` by either
/// removing characters from the end, or by appending as many
/// occurrences as necessary of a given pad string.
public func padding<
T : StringProtocol
>(
toLength newLength: Int,
withPad padString: T,
startingAt padIndex: Int
) -> String {
return _ns.padding(
toLength: newLength,
withPad: padString._ephemeralString,
startingAt: padIndex)
}
// @property NSString* stringByRemovingPercentEncoding;
/// A new string made from the string by replacing all percent encoded
/// sequences with the matching UTF-8 characters.
public var removingPercentEncoding: String? {
return _ns.removingPercentEncoding
}
// - (NSString *)
// stringByReplacingCharactersInRange:(NSRange)range
// withString:(NSString *)replacement
/// Returns a new string in which the characters in a
/// specified range of the `String` are replaced by a given string.
public func replacingCharacters<
T : StringProtocol, R : RangeExpression
>(in range: R, with replacement: T) -> String where R.Bound == Index {
return _ns.replacingCharacters(
in: _toRelativeNSRange(range.relative(to: self)),
with: replacement._ephemeralString)
}
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
//
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
// options:(StringCompareOptions)options
// range:(NSRange)searchRange
/// Returns a new string in which all occurrences of a target
/// string in a specified range of the string are replaced by
/// another given string.
public func replacingOccurrences<
Target : StringProtocol,
Replacement : StringProtocol
>(
of target: Target,
with replacement: Replacement,
options: String.CompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
let target = target._ephemeralString
let replacement = replacement._ephemeralString
return (searchRange != nil) || (!options.isEmpty)
? _ns.replacingOccurrences(
of: target,
with: replacement,
options: options,
range: _toRelativeNSRange(
searchRange ?? startIndex..<endIndex
)
)
: _ns.replacingOccurrences(of: target, with: replacement)
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (NSString *)
// stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a new string made by replacing in the `String`
/// all percent escapes with the matching characters as determined
/// by a given encoding.
@available(swift, deprecated: 3.0, obsoleted: 4.0,
message: "Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding.")
public func replacingPercentEscapes(
using encoding: String.Encoding
) -> String? {
return _ns.replacingPercentEscapes(using: encoding.rawValue)
}
#endif
// - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
/// Returns a new string made by removing from both ends of
/// the `String` characters contained in a given character set.
public func trimmingCharacters(in set: CharacterSet) -> String {
return _ns.trimmingCharacters(in: set)
}
// @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0);
/// An uppercase version of the string that is produced using the current
/// locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedUppercase: String {
return _ns.localizedUppercase as String
}
// - (NSString *)uppercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to uppercase, taking into account the specified
/// locale.
public func uppercased(with locale: Locale?) -> String {
return _ns.uppercased(with: locale)
}
//===--- Omitted due to redundancy with "utf8" property -----------------===//
// - (const char *)UTF8String
// - (BOOL)
// writeToFile:(NSString *)path
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to a file at a given
/// path using a given encoding.
public func write<
T : StringProtocol
>(
toFile path: T, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
try _ns.write(
toFile: path._ephemeralString,
atomically: useAuxiliaryFile,
encoding: enc.rawValue)
}
// - (BOOL)
// writeToURL:(NSURL *)url
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to the URL specified
/// by url using the specified encoding.
public func write(
to url: URL, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
try _ns.write(
to: url, atomically: useAuxiliaryFile, encoding: enc.rawValue)
}
// - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0);
#if !DEPLOYMENT_RUNTIME_SWIFT
/// Perform string transliteration.
@available(OSX 10.11, iOS 9.0, *)
public func applyingTransform(
_ transform: StringTransform, reverse: Bool
) -> String? {
return _ns.applyingTransform(transform, reverse: reverse)
}
// - (void)
// enumerateLinguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(LinguisticTaggerOptions)opts
// orthography:(Orthography *)orthography
// usingBlock:(
// void (^)(
// NSString *tag, NSRange tokenRange,
// NSRange sentenceRange, BOOL *stop)
// )block
/// Performs linguistic analysis on the specified string by
/// enumerating the specific range of the string, providing the
/// Block with the located tags.
public func enumerateLinguisticTags<
T : StringProtocol, R : RangeExpression
>(
in range: R,
scheme tagScheme: T,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
invoking body:
(String, Range<Index>, Range<Index>, inout Bool) -> Void
) where R.Bound == Index {
let range = range.relative(to: self)
_ns.enumerateLinguisticTags(
in: _toRelativeNSRange(range),
scheme: tagScheme._ephemeralString,
options: opts,
orthography: orthography != nil ? orthography! : nil
) {
var stop_ = false
body($0, self._range($1), self._range($2), &stop_)
if stop_ {
$3.pointee = true
}
}
}
#endif
// - (void)
// enumerateSubstringsInRange:(NSRange)range
// options:(NSStringEnumerationOptions)opts
// usingBlock:(
// void (^)(
// NSString *substring,
// NSRange substringRange,
// NSRange enclosingRange,
// BOOL *stop)
// )block
/// Enumerates the substrings of the specified type in the specified range of
/// the string.
///
/// Mutation of a string value while enumerating its substrings is not
/// supported. If you need to mutate a string from within `body`, convert
/// your string to an `NSMutableString` instance and then call the
/// `enumerateSubstrings(in:options:using:)` method.
///
/// - Parameters:
/// - range: The range within the string to enumerate substrings.
/// - opts: Options specifying types of substrings and enumeration styles.
/// If `opts` is omitted or empty, `body` is called a single time with
/// the range of the string specified by `range`.
/// - body: The closure executed for each substring in the enumeration. The
/// closure takes four arguments:
/// - The enumerated substring. If `substringNotRequired` is included in
/// `opts`, this parameter is `nil` for every execution of the
/// closure.
/// - The range of the enumerated substring in the string that
/// `enumerate(in:options:_:)` was called on.
/// - The range that includes the substring as well as any separator or
/// filler characters that follow. For instance, for lines,
/// `enclosingRange` contains the line terminators. The enclosing
/// range for the first string enumerated also contains any characters
/// that occur before the string. Consecutive enclosing ranges are
/// guaranteed not to overlap, and every single character in the
/// enumerated range is included in one and only one enclosing range.
/// - An `inout` Boolean value that the closure can use to stop the
/// enumeration by setting `stop = true`.
public func enumerateSubstrings<
R : RangeExpression
>(
in range: R,
options opts: String.EnumerationOptions = [],
_ body: @escaping (
_ substring: String?, _ substringRange: Range<Index>,
_ enclosingRange: Range<Index>, inout Bool
) -> Void
) where R.Bound == Index {
_ns.enumerateSubstrings(
in: _toRelativeNSRange(range.relative(to: self)), options: opts) {
var stop_ = false
body($0,
self._range($1),
self._range($2),
&stop_)
if stop_ {
UnsafeMutablePointer($3).pointee = true
}
}
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property float floatValue;
// - (BOOL)
// getBytes:(void *)buffer
// maxLength:(NSUInteger)maxBufferCount
// usedLength:(NSUInteger*)usedBufferCount
// encoding:(NSStringEncoding)encoding
// options:(StringEncodingConversionOptions)options
// range:(NSRange)range
// remainingRange:(NSRangePointer)leftover
/// Writes the given `range` of characters into `buffer` in a given
/// `encoding`, without any allocations. Does not NULL-terminate.
///
/// - Parameter buffer: A buffer into which to store the bytes from
/// the receiver. The returned bytes are not NUL-terminated.
///
/// - Parameter maxBufferCount: The maximum number of bytes to write
/// to buffer.
///
/// - Parameter usedBufferCount: The number of bytes used from
/// buffer. Pass `nil` if you do not need this value.
///
/// - Parameter encoding: The encoding to use for the returned bytes.
///
/// - Parameter options: A mask to specify options to use for
/// converting the receiver's contents to `encoding` (if conversion
/// is necessary).
///
/// - Parameter range: The range of characters in the receiver to get.
///
/// - Parameter leftover: The remaining range. Pass `nil` If you do
/// not need this value.
///
/// - Returns: `true` iff some characters were converted.
///
/// - Note: Conversion stops when the buffer fills or when the
/// conversion isn't possible due to the chosen encoding.
///
/// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes.
public func getBytes<
R : RangeExpression
>(
_ buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: String.Encoding,
options: String.EncodingConversionOptions = [],
range: R,
remaining leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool where R.Bound == Index {
return _withOptionalOutParameter(leftover) {
self._ns.getBytes(
&buffer,
maxLength: Swift.min(buffer.count, maxBufferCount),
usedLength: usedBufferCount,
encoding: encoding.rawValue,
options: options,
range: _toRelativeNSRange(range.relative(to: self)),
remaining: $0)
}
}
// - (void)
// getLineStart:(NSUInteger *)startIndex
// end:(NSUInteger *)lineEndIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first line and
/// the end of the last line touched by the given range.
public func getLineStart<
R : RangeExpression
>(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: R
) where R.Bound == Index {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getLineStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toRelativeNSRange(range.relative(to: self)))
}
}
}
}
// - (void)
// getParagraphStart:(NSUInteger *)startIndex
// end:(NSUInteger *)endIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first paragraph
/// and the end of the last paragraph touched by the given range.
public func getParagraphStart<
R : RangeExpression
>(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: R
) where R.Bound == Index {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getParagraphStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toRelativeNSRange(range.relative(to: self)))
}
}
}
}
//===--- Already provided by core Swift ---------------------------------===//
// - (instancetype)initWithString:(NSString *)aString
//===--- Initializers that can fail dropped for factory functions -------===//
// - (instancetype)initWithUTF8String:(const char *)bytes
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property NSInteger integerValue;
// @property Int intValue;
//===--- Omitted by apparent agreement during API review 5/20/2014 ------===//
// @property BOOL absolutePath;
// - (BOOL)isEqualToString:(NSString *)aString
// - (NSRange)lineRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the line or lines
/// containing a given range.
public func lineRange<
R : RangeExpression
>(for aRange: R) -> Range<Index> where R.Bound == Index {
return _range(_ns.lineRange(
for: _toRelativeNSRange(aRange.relative(to: self))))
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (NSArray *)
// linguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(LinguisticTaggerOptions)opts
// orthography:(Orthography *)orthography
// tokenRanges:(NSArray**)tokenRanges
/// Returns an array of linguistic tags for the specified
/// range and requested tags within the receiving string.
public func linguisticTags<
T : StringProtocol, R : RangeExpression
>(
in range: R,
scheme tagScheme: T,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil // FIXME:Can this be nil?
) -> [String] where R.Bound == Index {
var nsTokenRanges: NSArray?
let result = tokenRanges._withNilOrAddress(of: &nsTokenRanges) {
self._ns.linguisticTags(
in: _toRelativeNSRange(range.relative(to: self)),
scheme: tagScheme._ephemeralString,
options: opts,
orthography: orthography,
tokenRanges: $0) as NSArray
}
if let nsTokenRanges = nsTokenRanges {
tokenRanges?.pointee = (nsTokenRanges as [AnyObject]).map {
self._range($0.rangeValue)
}
}
return result as! [String]
}
// - (NSRange)paragraphRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the
/// paragraph or paragraphs containing a given range.
public func paragraphRange<
R : RangeExpression
>(for aRange: R) -> Range<Index> where R.Bound == Index {
return _range(
_ns.paragraphRange(for: _toRelativeNSRange(aRange.relative(to: self))))
}
#endif
// - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(StringCompareOptions)mask
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(StringCompareOptions)mask
// range:(NSRange)aRange
/// Finds and returns the range in the `String` of the first
/// character from a given character set found in a given range with
/// given options.
public func rangeOfCharacter(
from aSet: CharacterSet,
options mask: String.CompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
return _optionalRange(
_ns.rangeOfCharacter(
from: aSet,
options: mask,
range: _toRelativeNSRange(
aRange ?? startIndex..<endIndex
)
)
)
}
// - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex
/// Returns the range in the `String` of the composed
/// character sequence located at a given index.
public
func rangeOfComposedCharacterSequence(at anIndex: Index) -> Range<Index> {
return _range(
_ns.rangeOfComposedCharacterSequence(at: anIndex.encodedOffset))
}
// - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range
/// Returns the range in the string of the composed character
/// sequences for a given range.
public func rangeOfComposedCharacterSequences<
R : RangeExpression
>(
for range: R
) -> Range<Index> where R.Bound == Index {
// Theoretically, this will be the identity function. In practice
// I think users will be able to observe differences in the input
// and output ranges due (if nothing else) to locale changes
return _range(
_ns.rangeOfComposedCharacterSequences(
for: _toRelativeNSRange(range.relative(to: self))))
}
// - (NSRange)rangeOfString:(NSString *)aString
//
// - (NSRange)
// rangeOfString:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(StringCompareOptions)mask
// range:(NSRange)aRange
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(StringCompareOptions)mask
// range:(NSRange)searchRange
// locale:(Locale *)locale
/// Finds and returns the range of the first occurrence of a
/// given string within a given range of the `String`, subject to
/// given options, using the specified locale, if any.
public func range<
T : StringProtocol
>(
of aString: T,
options mask: String.CompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: Locale? = nil
) -> Range<Index>? {
let aString = aString._ephemeralString
return _optionalRange(
locale != nil ? _ns.range(
of: aString,
options: mask,
range: _toRelativeNSRange(
searchRange ?? startIndex..<endIndex
),
locale: locale
)
: searchRange != nil ? _ns.range(
of: aString, options: mask, range: _toRelativeNSRange(searchRange!)
)
: !mask.isEmpty ? _ns.range(of: aString, options: mask)
: _ns.range(of: aString)
)
}
// - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Finds and returns the range of the first occurrence of a given string,
/// taking the current locale into account. Returns `nil` if the string was
/// not found.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@available(OSX 10.11, iOS 9.0, *)
public func localizedStandardRange<
T : StringProtocol
>(of string: T) -> Range<Index>? {
return _optionalRange(
_ns.localizedStandardRange(of: string._ephemeralString))
}
#if !DEPLOYMENT_RUNTIME_SWIFT
// - (NSString *)
// stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the `String` using a given
/// encoding to determine the percent escapes necessary to convert
/// the `String` into a legal URL string.
@available(swift, deprecated: 3.0, obsoleted: 4.0,
message: "Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.")
public func addingPercentEscapes(
using encoding: String.Encoding
) -> String? {
return _ns.addingPercentEscapes(using: encoding.rawValue)
}
#endif
//===--- From the 10.10 release notes; not in public documentation ------===//
// No need to make these unavailable on earlier OSes, since they can
// forward trivially to rangeOfString.
/// Returns `true` iff `other` is non-empty and contained within
/// `self` by case-sensitive, non-literal search.
///
/// Equivalent to `self.rangeOfString(other) != nil`
public func contains<T : StringProtocol>(_ other: T) -> Bool {
let r = self.range(of: other) != nil
if #available(OSX 10.10, iOS 8.0, *) {
_sanityCheck(r == _ns.contains(other._ephemeralString))
}
return r
}
/// Returns a Boolean value indicating whether the given string is non-empty
/// and contained within this string by case-insensitive, non-literal
/// search, taking into account the current locale.
///
/// Locale-independent case-insensitive operation, and other needs, can be
/// achieved by calling `range(of:options:range:locale:)`.
///
/// Equivalent to:
///
/// range(of: other, options: .caseInsensitiveSearch,
/// locale: Locale.current) != nil
public func localizedCaseInsensitiveContains<
T : StringProtocol
>(_ other: T) -> Bool {
let r = self.range(
of: other, options: .caseInsensitive, locale: Locale.current
) != nil
if #available(OSX 10.10, iOS 8.0, *) {
_sanityCheck(r ==
_ns.localizedCaseInsensitiveContains(other._ephemeralString))
}
return r
}
}
// Deprecated slicing
extension StringProtocol where Index == String.Index {
// - (NSString *)substringFromIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` from the one at a given index to the end.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript with a 'partial range from' operator.")
public func substring(from index: Index) -> String {
return _ns.substring(from: index.encodedOffset)
}
// - (NSString *)substringToIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` up to, but not including, the one at a given index.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript with a 'partial range upto' operator.")
public func substring(to index: Index) -> String {
return _ns.substring(to: index.encodedOffset)
}
// - (NSString *)substringWithRange:(NSRange)aRange
/// Returns a string object containing the characters of the
/// `String` that lie within a given range.
@available(swift, deprecated: 4.0,
message: "Please use String slicing subscript.")
public func substring(with aRange: Range<Index>) -> String {
return _ns.substring(with: _toRelativeNSRange(aRange))
}
}
extension StringProtocol {
// - (const char *)fileSystemRepresentation
/// Returns a file system-specific representation of the `String`.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public var fileSystemRepresentation: [CChar] {
fatalError("unavailable function can't be called")
}
// - (BOOL)
// getFileSystemRepresentation:(char *)buffer
// maxLength:(NSUInteger)maxLength
/// Interprets the `String` as a system-independent path and
/// fills a buffer with a C-string in a format and encoding suitable
/// for use with file-system calls.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public func getFileSystemRepresentation(
_ buffer: inout [CChar], maxLength: Int) -> Bool {
fatalError("unavailable function can't be called")
}
//===--- Kept for consistency with API review results 5/20/2014 ---------===//
// We decided to keep pathWithComponents, so keeping this too
// @property NSString lastPathComponent;
/// Returns the last path component of the `String`.
@available(*, unavailable, message: "Use lastPathComponent on URL instead.")
public var lastPathComponent: String {
fatalError("unavailable function can't be called")
}
//===--- Renamed by agreement during API review 5/20/2014 ---------------===//
// @property NSUInteger length;
/// Returns the number of Unicode characters in the `String`.
@available(*, unavailable,
message: "Take the count of a UTF-16 view instead, i.e. str.utf16.count")
public var utf16Count: Int {
fatalError("unavailable function can't be called")
}
// @property NSArray* pathComponents
/// Returns an array of NSString objects containing, in
/// order, each path component of the `String`.
@available(*, unavailable, message: "Use pathComponents on URL instead.")
public var pathComponents: [String] {
fatalError("unavailable function can't be called")
}
// @property NSString* pathExtension;
/// Interprets the `String` as a path and returns the
/// `String`'s extension, if any.
@available(*, unavailable, message: "Use pathExtension on URL instead.")
public var pathExtension: String {
fatalError("unavailable function can't be called")
}
// @property NSString *stringByAbbreviatingWithTildeInPath;
/// Returns a new string that replaces the current home
/// directory portion of the current path with a tilde (`~`)
/// character.
@available(*, unavailable, message: "Use abbreviatingWithTildeInPath on NSString instead.")
public var abbreviatingWithTildeInPath: String {
fatalError("unavailable function can't be called")
}
// - (NSString *)stringByAppendingPathComponent:(NSString *)aString
/// Returns a new string made by appending to the `String` a given string.
@available(*, unavailable, message: "Use appendingPathComponent on URL instead.")
public func appendingPathComponent(_ aString: String) -> String {
fatalError("unavailable function can't be called")
}
// - (NSString *)stringByAppendingPathExtension:(NSString *)ext
/// Returns a new string made by appending to the `String` an
/// extension separator followed by a given extension.
@available(*, unavailable, message: "Use appendingPathExtension on URL instead.")
public func appendingPathExtension(_ ext: String) -> String? {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByDeletingLastPathComponent;
/// Returns a new string made by deleting the last path
/// component from the `String`, along with any final path
/// separator.
@available(*, unavailable, message: "Use deletingLastPathComponent on URL instead.")
public var deletingLastPathComponent: String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByDeletingPathExtension;
/// Returns a new string made by deleting the extension (if
/// any, and only the last) from the `String`.
@available(*, unavailable, message: "Use deletingPathExtension on URL instead.")
public var deletingPathExtension: String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByExpandingTildeInPath;
/// Returns a new string made by expanding the initial
/// component of the `String` to its full path value.
@available(*, unavailable, message: "Use expandingTildeInPath on NSString instead.")
public var expandingTildeInPath: String {
fatalError("unavailable function can't be called")
}
// - (NSString *)
// stringByFoldingWithOptions:(StringCompareOptions)options
// locale:(Locale *)locale
@available(*, unavailable, renamed: "folding(options:locale:)")
public func folding(
_ options: String.CompareOptions = [], locale: Locale?
) -> String {
fatalError("unavailable function can't be called")
}
// @property NSString* stringByResolvingSymlinksInPath;
/// Returns a new string made from the `String` by resolving
/// all symbolic links and standardizing path.
@available(*, unavailable, message: "Use resolvingSymlinksInPath on URL instead.")
public var resolvingSymlinksInPath: String {
fatalError("unavailable property")
}
// @property NSString* stringByStandardizingPath;
/// Returns a new string made by removing extraneous path
/// components from the `String`.
@available(*, unavailable, message: "Use standardizingPath on URL instead.")
public var standardizingPath: String {
fatalError("unavailable function can't be called")
}
// - (NSArray *)stringsByAppendingPaths:(NSArray *)paths
/// Returns an array of strings made by separately appending
/// to the `String` each string in a given array.
@available(*, unavailable, message: "Map over paths with appendingPathComponent instead.")
public func strings(byAppendingPaths paths: [String]) -> [String] {
fatalError("unavailable function can't be called")
}
}
// Pre-Swift-3 method names
extension String {
@available(*, unavailable, renamed: "localizedName(of:)")
public static func localizedNameOfStringEncoding(
_ encoding: String.Encoding
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.")
public static func pathWithComponents(_ components: [String]) -> String {
fatalError("unavailable function can't be called")
}
// + (NSString *)pathWithComponents:(NSArray *)components
/// Returns a string built from the strings in a given array
/// by concatenating them with a path separator between each pair.
@available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.")
public static func path(withComponents components: [String]) -> String {
fatalError("unavailable function can't be called")
}
}
extension StringProtocol {
@available(*, unavailable, renamed: "canBeConverted(to:)")
public func canBeConvertedToEncoding(_ encoding: String.Encoding) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "capitalizedString(with:)")
public func capitalizedStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "commonPrefix(with:options:)")
public func commonPrefixWith(
_ aString: String, options: String.CompareOptions) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "completePath(into:outputName:caseSensitive:matchesInto:filterTypes:)")
public func completePathInto(
_ outputName: UnsafeMutablePointer<String>? = nil,
caseSensitive: Bool,
matchesInto matchesIntoArray: UnsafeMutablePointer<[String]>? = nil,
filterTypes: [String]? = nil
) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "components(separatedBy:)")
public func componentsSeparatedByCharactersIn(
_ separator: CharacterSet
) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "components(separatedBy:)")
public func componentsSeparatedBy(_ separator: String) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "cString(usingEncoding:)")
public func cStringUsingEncoding(_ encoding: String.Encoding) -> [CChar]? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "data(usingEncoding:allowLossyConversion:)")
public func dataUsingEncoding(
_ encoding: String.Encoding,
allowLossyConversion: Bool = false
) -> Data? {
fatalError("unavailable function can't be called")
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@available(*, unavailable, renamed: "enumerateLinguisticTags(in:scheme:options:orthography:_:)")
public func enumerateLinguisticTagsIn(
_ range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options,
orthography: NSOrthography?,
_ body:
(String, Range<Index>, Range<Index>, inout Bool) -> Void
) {
fatalError("unavailable function can't be called")
}
#endif
@available(*, unavailable, renamed: "enumerateSubstrings(in:options:_:)")
public func enumerateSubstringsIn(
_ range: Range<Index>,
options opts: String.EnumerationOptions = [],
_ body: (
_ substring: String?, _ substringRange: Range<Index>,
_ enclosingRange: Range<Index>, inout Bool
) -> Void
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)")
public func getBytes(
_ buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: String.Encoding,
options: String.EncodingConversionOptions = [],
range: Range<Index>,
remainingRange leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getLineStart(_:end:contentsEnd:for:)")
public func getLineStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getParagraphStart(_:end:contentsEnd:for:)")
public func getParagraphStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lengthOfBytes(using:)")
public func lengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lineRange(for:)")
public func lineRangeFor(_ aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@available(*, unavailable, renamed: "linguisticTags(in:scheme:options:orthography:tokenRanges:)")
public func linguisticTagsIn(
_ range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil
) -> [String] {
fatalError("unavailable function can't be called")
}
#endif
@available(*, unavailable, renamed: "lowercased(with:)")
public func lowercaseStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "maximumLengthOfBytes(using:)")
public
func maximumLengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "paragraphRange(for:)")
public func paragraphRangeFor(_ aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfCharacter(from:options:range:)")
public func rangeOfCharacterFrom(
_ aSet: CharacterSet,
options mask: String.CompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfComposedCharacterSequence(at:)")
public
func rangeOfComposedCharacterSequenceAt(_ anIndex: Index) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfComposedCharacterSequences(for:)")
public func rangeOfComposedCharacterSequencesFor(
_ range: Range<Index>
) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "range(of:options:range:locale:)")
public func rangeOf(
_ aString: String,
options mask: String.CompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: Locale? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "localizedStandardRange(of:)")
public func localizedStandardRangeOf(_ string: String) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "addingPercentEncoding(withAllowedCharacters:)")
public func addingPercentEncodingWithAllowedCharacters(
_ allowedCharacters: CharacterSet
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "addingPercentEscapes(using:)")
public func addingPercentEscapesUsingEncoding(
_ encoding: String.Encoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "appendingFormat")
public func stringByAppendingFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "padding(toLength:with:startingAt:)")
public func byPaddingToLength(
_ newLength: Int, withString padString: String, startingAt padIndex: Int
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingCharacters(in:with:)")
public func replacingCharactersIn(
_ range: Range<Index>, withString replacement: String
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingOccurrences(of:with:options:range:)")
public func replacingOccurrencesOf(
_ target: String,
withString replacement: String,
options: String.CompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingPercentEscapes(usingEncoding:)")
public func replacingPercentEscapesUsingEncoding(
_ encoding: String.Encoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "trimmingCharacters(in:)")
public func byTrimmingCharactersIn(_ set: CharacterSet) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "strings(byAppendingPaths:)")
public func stringsByAppendingPaths(_ paths: [String]) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(from:)")
public func substringFrom(_ index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(to:)")
public func substringTo(_ index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(with:)")
public func substringWith(_ aRange: Range<Index>) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "uppercased(with:)")
public func uppercaseStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "write(toFile:atomically:encoding:)")
public func writeToFile(
_ path: String, atomically useAuxiliaryFile:Bool,
encoding enc: String.Encoding
) throws {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "write(to:atomically:encoding:)")
public func writeToURL(
_ url: URL, atomically useAuxiliaryFile: Bool,
encoding enc: String.Encoding
) throws {
fatalError("unavailable function can't be called")
}
}
| apache-2.0 | cd2f8482f020caa0257460170e873d8c | 34.422581 | 279 | 0.677014 | 4.781178 | false | false | false | false |
ZhengShouDong/CloudPacker | Sources/CloudPacker/Libraries/CryptoSwift/AES.Cryptors.swift | 1 | 5277 | //
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
// MARK: Cryptors
extension AES: Cryptors {
public func makeEncryptor() throws -> AES.Encryptor {
return try AES.Encryptor(aes: self)
}
public func makeDecryptor() throws -> AES.Decryptor {
return try AES.Decryptor(aes: self)
}
}
// MARK: Encryptor
extension AES {
public struct Encryptor: Updatable {
private var worker: BlockModeWorker
private let padding: Padding
private var accumulated = Array<UInt8>()
private var processedBytesTotalCount: Int = 0
private let paddingRequired: Bool
init(aes: AES) throws {
padding = aes.padding
worker = try aes.blockMode.worker(blockSize: AES.blockSize, cipherOperation: aes.encrypt)
paddingRequired = aes.blockMode.options.contains(.paddingRequired)
}
public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
accumulated += bytes
if isLast {
accumulated = padding.add(to: accumulated, blockSize: AES.blockSize)
}
var processedBytes = 0
var encrypted = Array<UInt8>(reserveCapacity: accumulated.count)
for chunk in accumulated.batched(by: AES.blockSize) {
if isLast || (accumulated.count - processedBytes) >= AES.blockSize {
encrypted += worker.encrypt(chunk)
processedBytes += chunk.count
}
}
accumulated.removeFirst(processedBytes)
processedBytesTotalCount += processedBytes
return encrypted
}
}
}
// MARK: Decryptor
extension AES {
public struct Decryptor: RandomAccessCryptor {
private var worker: BlockModeWorker
private let padding: Padding
private var accumulated = Array<UInt8>()
private var processedBytesTotalCount: Int = 0
private let paddingRequired: Bool
private var offset: Int = 0
private var offsetToRemove: Int = 0
init(aes: AES) throws {
padding = aes.padding
switch aes.blockMode {
case .CFB, .OFB, .CTR:
// CFB, OFB, CTR uses encryptBlock to decrypt
worker = try aes.blockMode.worker(blockSize: AES.blockSize, cipherOperation: aes.encrypt)
default:
worker = try aes.blockMode.worker(blockSize: AES.blockSize, cipherOperation: aes.decrypt)
}
paddingRequired = aes.blockMode.options.contains(.paddingRequired)
}
public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
// prepend "offset" number of bytes at the beginning
if offset > 0 {
accumulated += Array<UInt8>(repeating: 0, count: offset) + bytes
offsetToRemove = offset
offset = 0
} else {
accumulated += bytes
}
var processedBytes = 0
var plaintext = Array<UInt8>(reserveCapacity: accumulated.count)
for chunk in accumulated.batched(by: AES.blockSize) {
if isLast || (accumulated.count - processedBytes) >= AES.blockSize {
plaintext += worker.decrypt(chunk)
// remove "offset" from the beginning of first chunk
if offsetToRemove > 0 {
plaintext.removeFirst(offsetToRemove)
offsetToRemove = 0
}
processedBytes += chunk.count
}
}
accumulated.removeFirst(processedBytes)
processedBytesTotalCount += processedBytes
if isLast {
plaintext = padding.remove(from: plaintext, blockSize: AES.blockSize)
}
return plaintext
}
@discardableResult public mutating func seek(to position: Int) -> Bool {
guard var worker = self.worker as? RandomAccessBlockModeWorker else {
return false
}
worker.counter = UInt(position / AES.blockSize)
self.worker = worker
offset = position % AES.blockSize
accumulated = []
return true
}
}
}
| apache-2.0 | fa35d3d826f905a5b8daf2ffffcf0c26 | 36.41844 | 217 | 0.607847 | 5.234127 | false | false | false | false |
passt0r/MaliDeck | MaliDeck/MembersTableViewCell.swift | 1 | 2933 | //
// MembersTableViewCell.swift
// MaliDeck
//
// Created by Dmytro Pasinchuk on 12.11.16.
// Copyright © 2016 Dmytro Pasinchuk. All rights reserved.
//
import UIKit
class MembersTableViewCell: UITableViewCell {
//MARK: Properties
@IBOutlet weak var memberCellView: UIView!
@IBOutlet weak var memberPhoto: UIImageView!
@IBOutlet weak var memberName: UILabel!
@IBOutlet weak var memberFaction: UILabel!
@IBOutlet weak var memberCoastOrCash: UILabel!
@IBOutlet weak var coastOrCashLabel: UILabel!
@IBOutlet weak var nameStack: UIStackView!
@IBOutlet weak var factionStack: UIStackView!
@IBOutlet weak var costStack: UIStackView!
//MARK: Member properties on stack, NOT USED!
@IBOutlet weak var memberPropertyStack: UIStackView!
@IBOutlet weak var dfStack: UIStackView!
@IBOutlet weak var wpStack: UIStackView!
@IBOutlet weak var wdStack: UIStackView!
@IBOutlet weak var wkStack: UIStackView!
@IBOutlet weak var cgStack: UIStackView!
@IBOutlet weak var htStack: UIStackView!
//Not used, did not working, wiil be used in future for creating table-like borders
/* func borderInit(stack: UIStackView) {
let borderView = UIView(frame: stack.frame)
borderView.layer.borderWidth = 2
borderView.layer.borderColor = UIColor.black.cgColor
borderView.clipsToBounds = true
stack.addArrangedSubview(borderView)
} */
//MARK: Members ptoperties
@IBOutlet weak var dfCount: UILabel!
@IBOutlet weak var wpCount: UILabel!
@IBOutlet weak var wdCount: UILabel!
@IBOutlet weak var wkCount: UILabel!
@IBOutlet weak var cgCount: UILabel!
@IBOutlet weak var htCount: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
//let stackArray: [UIStackView] = [nameStack, factionStack, costStack, memberPropertyStack, dfStack, wpStack, wdStack, wkStack, cgStack, htStack]
/* for stack in stackArray {
borderInit(stack: stack) //init borders to all stack
}
*/
memberPhoto.layer.borderWidth = 1
memberPhoto.layer.borderColor = UIColor.black.cgColor
//MARK: Cell image properties
memberCellView.backgroundColor = UIColor.clear
let paperView = UIImageView(image: UIImage(named: "paper"))
paperView.frame = memberCellView.bounds
paperView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
paperView.layer.cornerRadius = 8
paperView.clipsToBounds = true
memberCellView.insertSubview(paperView, at: 0)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| gpl-3.0 | aa399d5026ae701ac20ea875902838ec | 30.191489 | 153 | 0.665075 | 4.75974 | false | false | false | false |
KrishMunot/swift | validation-test/stdlib/IOKitOverlay.swift | 5 | 621 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: OS=macosx
import IOKit
import IOKit.hid
import StdlibUnittest
var IOKitTests = TestSuite("IOKit")
IOKitTests.test("IOReturn value") {
// Error codes are computed by a helper function so it's enough to test one.
// The value is taken from the OS X 10.11 SDK.
expectEqual(Int(kIOReturnStillOpen), -536870190)
}
IOKitTests.test("IOReturn type") {
let manager = IOHIDManagerCreate(nil, 0)!.takeRetainedValue()
let result = IOHIDManagerClose(manager, 0)
expectTrue(result.dynamicType == kIOReturnNotOpen.dynamicType)
}
runAllTests()
| apache-2.0 | 13c6036db84da85d5e386caae58b5d85 | 24.875 | 78 | 0.748792 | 3.718563 | false | true | false | false |
GuiBayma/PasswordVault | PasswordVault/Scenes/Item Detail/ItemDetailView.swift | 1 | 1672 | //
// ItemDetailView.swift
// PasswordVault
//
// Created by Guilherme Bayma on 8/1/17.
// Copyright © 2017 Bayma. All rights reserved.
//
import UIKit
import SnapKit
class ItemDetailView: UIView {
// MARK: - Components
let nameLabel = UILabel()
let userLabel = UILabel()
let passwordLabel = UILabel()
// MARK: - Initialization
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
self.addSubview(nameLabel)
self.addSubview(userLabel)
self.addSubview(passwordLabel)
setConstraints()
}
// MARK: - Constraints
internal func setConstraints() {
// name label
nameLabel.snp.makeConstraints { (maker) in
maker.bottom.equalTo(userLabel.snp.top).offset(-40)
maker.centerX.equalTo(userLabel.snp.centerX)
}
nameLabel.font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightSemibold)
// user name label
userLabel.snp.makeConstraints { (maker) in
maker.centerX.equalTo(self.snp.centerX)
maker.centerY.equalTo(self.snp.centerY)
}
userLabel.font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightSemibold)
// password label
passwordLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(userLabel.snp.bottom).offset(20)
maker.centerX.equalTo(userLabel.snp.centerX)
}
passwordLabel.font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightSemibold)
}
}
| mit | 5f2ea14c5e0f589140a0685d486a5dc0 | 25.951613 | 88 | 0.633154 | 4.504043 | false | false | false | false |
KrishMunot/swift | test/ClangModules/objc_parse.swift | 2 | 21922 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -I %S/Inputs/custom-modules %s -verify
// REQUIRES: objc_interop
import AppKit
import AVFoundation
import objc_ext
import TestProtocols
import ObjCParseExtras
import ObjCParseExtrasToo
import ObjCParseExtrasSystem
func markUsed<T>(_ t: T) {}
func testAnyObject(_ obj: AnyObject) {
_ = obj.nsstringProperty
}
// Construction
func construction() {
_ = B()
}
// Subtyping
func treatBAsA(_ b: B) -> A {
return b
}
// Instance method invocation
func instanceMethods(_ b: B) {
var i = b.method(1, with: 2.5 as Float)
i = i + b.method(1, with: 2.5 as Double)
// BOOL
b.setEnabled(true)
// SEL
b.perform(#selector(NSObject.isEqual(_:)), with: b)
if let result = b.perform(#selector(B.getAsProto), with: nil) {
_ = result.takeUnretainedValue()
}
// Renaming of redundant parameters.
b.performAdd(1, withValue:2, withValue2:3, withValue:4) // expected-error{{argument 'withValue' must precede argument 'withValue2'}}
b.performAdd(1, withValue:2, withValue:4, withValue2: 3)
b.performAdd(1, 2, 3, 4) // expected-error{{missing argument labels 'withValue:withValue:withValue2:' in call}} {{19-19=withValue: }} {{22-22=withValue: }} {{25-25=withValue2: }}
// Both class and instance methods exist.
b.description
b.instanceTakesObjectClassTakesFloat(b)
b.instanceTakesObjectClassTakesFloat(2.0) // expected-error{{cannot convert value of type 'Double' to expected argument type 'AnyObject!'}}
// Instance methods with keyword components
var obj = NSObject()
var prot = NSObjectProtocol.self
b.`protocol`(prot, hasThing:obj)
b.doThing(obj, protocol: prot)
}
// Class method invocation
func classMethods(_ b: B, other: NSObject) {
var i = B.classMethod()
i += B.classMethod(1)
i += B.classMethod(1, with: 2)
i += b.classMethod() // expected-error{{static member 'classMethod' cannot be used on instance of type 'B'}}
// Both class and instance methods exist.
B.description()
B.instanceTakesObjectClassTakesFloat(2.0)
B.instanceTakesObjectClassTakesFloat(other) // expected-error{{cannot convert value of type 'NSObject' to expected argument type 'Float'}}
// Call an instance method of NSObject.
var c: AnyClass = B.myClass() // no-warning
c = b.myClass() // no-warning
}
// Instance method invocation on extensions
func instanceMethodsInExtensions(_ b: B) {
b.method(1, onCat1:2.5)
b.method(1, onExtA:2.5)
b.method(1, onExtB:2.5)
b.method(1, separateExtMethod:3.5)
let m1 = b.method(_:onCat1:)
m1(1, onCat1: 2.5)
let m2 = b.method(_:onExtA:)
m2(1, onExtA: 2.5)
let m3 = b.method(_:onExtB:)
m3(1, onExtB: 2.5)
let m4 = b.method(_:separateExtMethod:)
m4(1, separateExtMethod: 2.5)
}
func dynamicLookupMethod(_ b: AnyObject) {
if let m5 = b.method(_:separateExtMethod:) {
m5(1, separateExtMethod: 2.5)
}
}
// Properties
func properties(_ b: B) {
var i = b.counter
b.counter = i + 1
i = i + b.readCounter
b.readCounter = i + 1 // expected-error{{cannot assign to property: 'readCounter' is a get-only property}}
b.setCounter(5) // expected-error{{value of type 'B' has no member 'setCounter'}}
// Informal properties in Objective-C map to methods, not variables.
b.informalProp()
// An informal property cannot be made formal in a subclass. The
// formal property is simply ignored.
b.informalMadeFormal()
b.informalMadeFormal = i // expected-error{{cannot assign to property: 'b' is a 'let' constant}}
b.setInformalMadeFormal(5)
b.overriddenProp = 17
// Dynamic properties.
var obj : AnyObject = b
var optStr = obj.nsstringProperty
if optStr != nil {
var s : String = optStr!
}
// Properties that are Swift keywords
var prot = b.`protocol`
}
// Construction.
func newConstruction(_ a: A, aproxy: AProxy) {
var b : B = B()
b = B(int: 17)
b = B(int:17)
b = B(double:17.5, 3.14159)
b = B(bbb:b)
b = B(forWorldDomination:())
b = B(int: 17, andDouble : 3.14159)
b = B.new(with: a)
B.alloc()._initFoo()
b.notAnInit()
// init methods are not imported by themselves.
b.initWithInt(17) // expected-error{{value of type 'B' has no member 'initWithInt'}}
// init methods on non-NSObject-rooted classes
AProxy(int: 5) // expected-warning{{unused}}
}
// Indexed subscripting
func indexedSubscripting(_ b: B, idx: Int, a: A) {
b[idx] = a
_ = b[idx] as! A
}
// Keyed subscripting
func keyedSubscripting(_ b: B, idx: A, a: A) {
b[a] = a
var a2 = b[a] as! A
let dict = NSMutableDictionary()
dict[NSString()] = a
let value = dict[NSString()]
dict[nil] = a // expected-error {{nil is not compatible with expected argument type 'NSCopying'}}
let q = dict[nil] // expected-error {{nil is not compatible with expected argument type 'NSCopying'}}
_ = q
}
// Typed indexed subscripting
func checkHive(_ hive: Hive, b: Bee) {
let b2 = hive.bees[5] as Bee
b2.buzz()
}
// Protocols
func testProtocols(_ b: B, bp: BProto) {
var bp2 : BProto = b
var b2 : B = bp // expected-error{{cannot convert value of type 'BProto' to specified type 'B'}}
bp.method(1, with: 2.5 as Float)
bp.method(1, withFoo: 2.5) // expected-error{{incorrect argument label in call (have '_:withFoo:', expected '_:with:')}}
bp2 = b.getAsProto()
var c1 : Cat1Proto = b
var bcat1 = b.getAsProtoWithCat()
c1 = bcat1
bcat1 = c1 // expected-error{{cannot assign value of type 'Cat1Proto' to type 'protocol<BProto, Cat1Proto>!'}}
}
// Methods only defined in a protocol
func testProtocolMethods(_ b: B, p2m: P2.Type) {
b.otherMethod(1, with: 3.14159)
b.p2Method()
b.initViaP2(3.14159, second: 3.14159) // expected-error{{value of type 'B' has no member 'initViaP2'}}
// Imported constructor.
var b2 = B(viaP2: 3.14159, second: 3.14159)
p2m.init(viaP2:3.14159, second: 3.14159)
}
func testId(_ x: AnyObject) {
x.perform!("foo:", with: x) // expected-warning{{no method declared with Objective-C selector 'foo:'}}
x.performAdd(1, withValue: 2, withValue: 3, withValue2: 4)
x.performAdd!(1, withValue: 2, withValue: 3, withValue2: 4)
x.performAdd?(1, withValue: 2, withValue: 3, withValue2: 4)
}
class MySubclass : B {
// Override a regular method.
override func anotherMethodOnB() {}
// Override a category method
override func anotherCategoryMethod() {}
}
func getDescription(_ array: NSArray) {
array.description
}
// Method overriding with unfortunate ordering.
func overridingTest(_ srs: SuperRefsSub) {
let rs : RefedSub
rs.overridden()
}
func almostSubscriptableValueMismatch(_ as1: AlmostSubscriptable, a: A) {
as1[a] // expected-error{{type 'AlmostSubscriptable' has no subscript members}}
}
func almostSubscriptableKeyMismatch(_ bc: BadCollection, key: NSString) {
// FIXME: We end up importing this as read-only due to the mismatch between
// getter/setter element types.
var _ : AnyObject = bc[key]
}
func almostSubscriptableKeyMismatchInherited(_ bc: BadCollectionChild,
key: String) {
var value : AnyObject = bc[key] // no-warning, inherited from parent
bc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}}
}
func almostSubscriptableKeyMismatchInherited(_ roc: ReadOnlyCollectionChild,
key: String) {
var value : AnyObject = roc[key] // no-warning, inherited from parent
roc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}}
}
// Use of 'Class' via dynamic lookup.
func classAnyObject(_ obj: NSObject) {
obj.myClass().description!()
}
// Protocol conformances
class Wobbler : NSWobbling { // expected-note{{candidate is not '@objc', but protocol requires it}} {{7-7=@objc }}
// expected-error@-1{{type 'Wobbler' does not conform to protocol 'NSWobbling'}}
@objc func wobble() { }
func returnMyself() -> Self { return self } // expected-note{{candidate is not '@objc', but protocol requires it}} {{3-3=@objc }}
}
extension Wobbler : NSMaybeInitWobble { // expected-error{{type 'Wobbler' does not conform to protocol 'NSMaybeInitWobble'}}
}
@objc class Wobbler2 : NSObject, NSWobbling { // expected-note{{Objective-C method 'init' provided by implicit initializer 'init()' does not match the requirement's selector ('initWithWobble:')}}
func wobble() { }
func returnMyself() -> Self { return self }
}
extension Wobbler2 : NSMaybeInitWobble { // expected-error{{type 'Wobbler2' does not conform to protocol 'NSMaybeInitWobble'}}
}
func optionalMemberAccess(_ w: NSWobbling) {
w.wobble()
w.wibble() // expected-error{{value of optional type '(() -> Void)?' not unwrapped; did you mean to use '!' or '?'?}} {{11-11=!}}
var x: AnyObject = w[5] // expected-error{{value of optional type 'AnyObject!?' not unwrapped; did you mean to use '!' or '?'?}} {{26-26=!}}
}
func protocolInheritance(_ s: NSString) {
var _: NSCoding = s
}
func ivars(_ hive: Hive) {
var d = hive.bees.description
hive.queen.description() // expected-error{{value of type 'Hive' has no member 'queen'}}
}
class NSObjectable : NSObjectProtocol {
@objc var description : String { return "" }
@objc(conformsToProtocol:) func conforms(to _: Protocol) -> Bool { return false }
@objc(isKindOfClass:) func isKind(of aClass: AnyClass) -> Bool { return false }
}
// Properties with custom accessors
func customAccessors(_ hive: Hive, bee: Bee) {
markUsed(hive.isMakingHoney)
markUsed(hive.makingHoney()) // expected-error{{value of type 'Hive' has no member 'makingHoney'}}
hive.setMakingHoney(true) // expected-error{{value of type 'Hive' has no member 'setMakingHoney'}}
hive.`guard`.description // okay
hive.`guard`.description! // no-warning
hive.`guard` = bee // no-warning
}
// instancetype/Dynamic Self invocation.
func testDynamicSelf(_ queen: Bee, wobbler: NSWobbling) {
var hive = Hive()
// Factory method with instancetype result.
var hive1 = Hive(queen: queen)
hive1 = hive
hive = hive1
// Instance method with instancetype result.
var hive2 = hive.visit()
hive2 = hive
hive = hive2
// Instance method on a protocol with instancetype result.
var wobbler2 = wobbler.returnMyself()
var wobbler: NSWobbling = wobbler2
wobbler2 = wobbler
// Instance method on a base class with instancetype result, called on the
// class itself.
// FIXME: This should be accepted.
// FIXME: The error is lousy, too.
let baseClass: ObjCParseExtras.Base.Type = ObjCParseExtras.Base.returnMyself() // expected-error{{missing argument for parameter #1 in call}}
}
func testRepeatedProtocolAdoption(_ w: NSWindow) {
w.description
}
class ProtocolAdopter1 : FooProto {
@objc var bar: CInt // no-warning
init() { bar = 5 }
}
class ProtocolAdopter2 : FooProto {
@objc var bar: CInt {
get { return 42 }
set { /* do nothing! */ }
}
}
class ProtocolAdopterBad1 : FooProto { // expected-error{{type 'ProtocolAdopterBad1' does not conform to protocol 'FooProto'}}
@objc var bar: Int = 0 // expected-note{{candidate has non-matching type 'Int'}}
}
class ProtocolAdopterBad2 : FooProto { // expected-error{{type 'ProtocolAdopterBad2' does not conform to protocol 'FooProto'}}
let bar: CInt = 0 // expected-note{{candidate is not settable, but protocol requires it}}
}
class ProtocolAdopterBad3 : FooProto { // expected-error{{type 'ProtocolAdopterBad3' does not conform to protocol 'FooProto'}}
var bar: CInt { // expected-note{{candidate is not settable, but protocol requires it}}
return 42
}
}
@objc protocol RefinedFooProtocol : FooProto {}
func testPreferClassMethodToCurriedInstanceMethod(_ obj: NSObject) {
// FIXME: We shouldn't need the ": Bool" type annotation here.
// <rdar://problem/18006008>
let _: Bool = NSObject.isEqual(obj)
_ = NSObject.isEqual(obj) as (NSObject!) -> Bool // no-warning
}
func testPropertyAndMethodCollision(_ obj: PropertyAndMethodCollision,
rev: PropertyAndMethodReverseCollision) {
obj.object = nil
obj.object(obj, doSomething:Selector("action"))
obj.dynamicType.classRef = nil
obj.dynamicType.classRef(obj, doSomething:Selector("action"))
rev.object = nil
rev.object(rev, doSomething:Selector("action"))
rev.dynamicType.classRef = nil
rev.dynamicType.classRef(rev, doSomething:Selector("action"))
var value: AnyObject
value = obj.protoProp()
value = obj.protoPropRO()
value = obj.dynamicType.protoClassProp()
value = obj.dynamicType.protoClassPropRO()
_ = value
}
func testSubscriptAndPropertyRedeclaration(_ obj: SubscriptAndProperty) {
_ = obj.x
obj.x = 5
obj.objectAtIndexedSubscript(5) // expected-error{{'objectAtIndexedSubscript' is unavailable: use subscripting}}
obj.setX(5) // expected-error{{value of type 'SubscriptAndProperty' has no member 'setX'}}
_ = obj[0]
obj[1] = obj
obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}}
}
func testSubscriptAndPropertyWithProtocols(_ obj: SubscriptAndPropertyWithProto) {
_ = obj.x
obj.x = 5
obj.setX(5) // expected-error{{value of type 'SubscriptAndPropertyWithProto' has no member 'setX'}}
_ = obj[0]
obj[1] = obj
obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}}
}
func testProtocolMappingSameModule(_ obj: AVVideoCompositionInstruction, p: AVVideoCompositionInstructionProtocol) {
markUsed(p.enablePostProcessing)
markUsed(obj.enablePostProcessing)
_ = obj.backgroundColor
}
func testProtocolMappingDifferentModules(_ obj: ObjCParseExtrasToo.ProtoOrClass, p: ObjCParseExtras.ProtoOrClass) {
markUsed(p.thisIsTheProto)
markUsed(obj.thisClassHasAnAwfulName)
let _: ProtoOrClass? // expected-error{{'ProtoOrClass' is ambiguous for type lookup in this context}}
_ = ObjCParseExtrasToo.ClassInHelper() // expected-error{{'ClassInHelper' cannot be constructed because it has no accessible initializers}}
_ = ObjCParseExtrasToo.ProtoInHelper()
_ = ObjCParseExtrasTooHelper.ClassInHelper()
_ = ObjCParseExtrasTooHelper.ProtoInHelper() // expected-error{{'ProtoInHelper' cannot be constructed because it has no accessible initializers}}
}
func testProtocolClassShadowing(_ obj: ClassInHelper, p: ProtoInHelper) {
let _: ObjCParseExtrasToo.ClassInHelper = obj
let _: ObjCParseExtrasToo.ProtoInHelper = p
}
func testDealloc(_ obj: NSObject) {
// dealloc is subsumed by deinit.
// FIXME: Special-case diagnostic in the type checker?
obj.dealloc() // expected-error{{value of type 'NSObject' has no member 'dealloc'}}
}
func testConstantGlobals() {
markUsed(MAX)
markUsed(SomeImageName)
markUsed(SomeNumber.description)
MAX = 5 // expected-error{{cannot assign to value: 'MAX' is a 'let' constant}}
SomeImageName = "abc" // expected-error{{cannot assign to value: 'SomeImageName' is a 'let' constant}}
SomeNumber = nil // expected-error{{cannot assign to value: 'SomeNumber' is a 'let' constant}}
}
func testWeakVariable() {
let _: AnyObject = globalWeakVar
}
class IncompleteProtocolAdopter : Incomplete, IncompleteOptional { // expected-error {{type 'IncompleteProtocolAdopter' cannot conform to protocol 'Incomplete' because it has requirements that cannot be satisfied}}
@objc func getObject() -> AnyObject { return self }
}
func testNullarySelectorPieces(_ obj: AnyObject) {
obj.foo(1, bar: 2, 3) // no-warning
obj.foo(1, 2, bar: 3) // expected-error{{cannot call value of non-function type 'AnyObject?!'}}
}
func testFactoryMethodAvailability() {
_ = DeprecatedFactoryMethod() // expected-warning{{'init()' is deprecated: use something newer}}
}
func testRepeatedMembers(_ obj: RepeatedMembers) {
obj.repeatedMethod()
}
// rdar://problem/19726164
class FooDelegateImpl : NSObject, FooDelegate {
var _started = false
var isStarted: Bool {
get { return _started }
@objc(setStarted:) set { _started = newValue }
}
}
class ProtoAdopter : NSObject, ExplicitSetterProto, OptionalSetterProto {
var foo: AnyObject? // no errors about conformance
var bar: AnyObject? // no errors about conformance
}
func testUnusedResults(_ ur: UnusedResults) {
_ = ur.producesResult()
ur.producesResult() // expected-warning{{result of call to 'producesResult()' is unused}}
}
func testCStyle() {
ExtraSelectors.cStyle(0, 1, 2) // expected-error{{type 'ExtraSelectors' has no member 'cStyle'}}
}
func testProtocolQualified(_ obj: CopyableNSObject, cell: CopyableSomeCell,
plainObj: NSObject, plainCell: SomeCell) {
_ = obj as NSObject // expected-error {{'CopyableNSObject' (aka 'protocol<NSCopying, NSObjectProtocol>') is not convertible to 'NSObject'; did you mean to use 'as!' to force downcast?}} {{11-13=as!}}
_ = obj as NSObjectProtocol
_ = obj as NSCopying
_ = obj as SomeCell // expected-error {{'CopyableNSObject' (aka 'protocol<NSCopying, NSObjectProtocol>') is not convertible to 'SomeCell'; did you mean to use 'as!' to force downcast?}} {{11-13=as!}}
_ = cell as NSObject
_ = cell as NSObjectProtocol
_ = cell as NSCopying // expected-error {{'CopyableSomeCell' (aka 'SomeCell') is not convertible to 'NSCopying'; did you mean to use 'as!' to force downcast?}} {{12-14=as!}}
_ = cell as SomeCell
_ = plainObj as CopyableNSObject // expected-error {{'NSObject' is not convertible to 'CopyableNSObject' (aka 'protocol<NSCopying, NSObjectProtocol>'); did you mean to use 'as!' to force downcast?}} {{16-18=as!}}
_ = plainCell as CopyableSomeCell // FIXME: This is not really typesafe.
}
extension Printing {
func testImplicitWarnUnqualifiedAccess() {
print() // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self) // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self, options: self) // no-warning
}
static func testImplicitWarnUnqualifiedAccess() {
print() // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self) // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self, options: self) // no-warning
}
}
// <rdar://problem/21979968> The "with array" initializers for NSCountedSet and NSMutable set should be properly disambiguated.
func testSetInitializers() {
let a: [AnyObject] = [NSObject()]
let _ = NSCountedSet(array: a)
let _ = NSMutableSet(array: a)
}
func testNSUInteger(_ obj: NSUIntegerTests, uint: UInt, int: Int) {
obj.consumeUnsigned(uint) // okay
obj.consumeUnsigned(int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
obj.consumeUnsigned(0, withTheNSUIntegerHere: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.consumeUnsigned(0, withTheNSUIntegerHere: int) // okay
obj.consumeUnsigned(uint, andAnother: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.consumeUnsigned(uint, andAnother: int) // okay
do {
let x = obj.unsignedProducer()
let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
do {
obj.unsignedProducer(uint, fromCount: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.unsignedProducer(int, fromCount: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
let x = obj.unsignedProducer(uint, fromCount: int) // okay
let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
do {
obj.normalProducer(uint, fromUnsigned: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.normalProducer(int, fromUnsigned: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
let x = obj.normalProducer(int, fromUnsigned: uint)
let _: String = x // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
}
let _: String = obj.normalProp // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let _: String = obj.unsignedProp // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
do {
testUnsigned(int, uint) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
testUnsigned(uint, int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
let x = testUnsigned(uint, uint) // okay
let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
// NSNumber
let num = NSNumber(value: uint)
let _: String = num.uintValue // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
// <rdar://problem/25168818> Don't import None members in NS_OPTIONS types
let _ = NSRuncingOptions.none // expected-error {{'none' is unavailable: use [] to construct an empty option set}}
| apache-2.0 | 4a21db0c3feb4809db659849143fb705 | 35.415282 | 214 | 0.698887 | 3.923049 | false | true | false | false |
tkremenek/swift | test/Concurrency/Runtime/async_taskgroup_cancel_parent_affects_group.swift | 1 | 1332 | // RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) | %FileCheck %s --dump-input always
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
import Dispatch
@available(SwiftStdlib 5.5, *)
func asyncEcho(_ value: Int) async -> Int {
value
}
@available(SwiftStdlib 5.5, *)
func test_taskGroup_cancel_parent_affects_group() async {
let x = detach {
await withTaskGroup(of: Int.self, returning: Void.self) { group in
group.spawn {
await Task.sleep(3_000_000_000)
let c = Task.isCancelled
print("group task isCancelled: \(c)")
return 0
}
_ = await group.next()
let c = Task.isCancelled
print("group isCancelled: \(c)")
}
let c = Task.isCancelled
print("detached task isCancelled: \(c)")
}
x.cancel()
try! await x.get()
// CHECK: group task isCancelled: true
// CHECK: group isCancelled: true
// CHECK: detached task isCancelled: true
// CHECK: done
print("done")
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
await test_taskGroup_cancel_parent_affects_group()
}
}
| apache-2.0 | 9134fa4bb36e1a973a13822a43b4d942 | 23.218182 | 193 | 0.665916 | 3.741573 | false | true | false | false |
SwiftFMI/iOS_2017_2018 | Lectures/code/10.11.2017/UITableView Demo/UITableView Demo/ViewController.swift | 1 | 6295 | //
// ViewController.swift
// UITableView Demo
//
// Created by Emil Atanasov on 11/10/17.
// Copyright © 2017 SwiftFMI. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for i in 1...50 {
items.append("New Item \(i)")
}
tableView.dataSource = self
tableView.delegate = self
}
@IBAction func deleteItem(_ sender: Any) {
items.removeFirst()
// tableView.reloadData();
tableView.beginUpdates()
tableView.deleteRows(at:[IndexPath(row: 0, section: 0)], with: .right)
tableView.endUpdates()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = items[indexPath.row]
print(item)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//:MARK dataSource
var items:[String] = [];
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("IP: \(indexPath)")
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell")
let item = items[indexPath.row]
cell?.textLabel?.text = item
return cell!
}
// :MARK
// func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
// let item = items[indexPath.row]
// print("\(item) - \(editingStyle)")
// }
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let item = items[indexPath.row]
print("\(item)")
let more = UITableViewRowAction(style: .normal, title: "More") { action, index in
//self.isEditing = false
print("more button tapped")
}
more.backgroundColor = UIColor.lightGray
let favorite = UITableViewRowAction(style: .normal, title: "Favorite") { action, index in
//self.isEditing = false
print("favorite button tapped")
}
favorite.backgroundColor = UIColor.orange
let share = UITableViewRowAction(style: .normal, title: "Share") { action, index in
//self.isEditing = false
print("share button tapped")
}
share.backgroundColor = UIColor.blue
return [share, favorite, more]
}
}
class TableViewController: UITableViewController {
var items:[String] = [];
let sections = 3
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for i in 1...15 {
items.append("Item \(i)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Section \(section + 1)"
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sections
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell? = nil
print("IP: \(indexPath)")
if indexPath.section == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "myButtonCell")
} else {
cell = tableView.dequeueReusableCell(withIdentifier: "myCell")
}
let item = items[indexPath.row]
cell?.textLabel?.text = item
// cell?.textLabel?.backgroundColor = UIColor.green
// cell?.textLabel?.textColor = UIColor.red
return cell!
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
var r:[String] = []
for i in 1...sections {
r.append("Section \(i)")
}
return r
}
}
class TableViewControllerFinal: UITableViewController {
var items:[String] = [];
let sections = 1
// override func numberOfSections(in tableView: UITableView) -> Int {
// return sections
// }
//
// override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// return "Section \(section + 1)"
// }
//
// override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
// var r:[String] = []
// for i in 1...sections {
// r.append("Section \(i)")
// }
//
// return r
// }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell")
let data = items[indexPath.row]
cell?.textLabel?.text = data
return cell!
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for i in 1...10 {
items.append("Item \(i)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 6d5d59b708de884baf3f14aaef7e674d | 26.012876 | 129 | 0.585002 | 5.201653 | false | false | false | false |
grant/20-Apps | Day 18 Swift/Day 18 Swift/ViewController.swift | 2 | 2415 | //
// ViewController.swift
// Day 18 Swift
//
// Created by Grant Timmerman on 8/26/14.
// Copyright (c) 2014 Grant Timmerman. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// The number of taps to store in the array
let numTapsToStore = 3
// Main label
var label:UILabel;
// The dates for the last N number of taps
var tapTimes:[NSDate] = [];
required init(coder aDecoder: NSCoder) {
self.label = UILabel()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Setup UILabel
label.frame = CGRect(x: 0,y: 0,width: self.view.frame.size.width, height: self.view.frame.size.height)
label.text = "Tap"
label.textAlignment = NSTextAlignment.Center
label.textColor = UIColor.whiteColor()
label.font = UIFont.systemFontOfSize(50)
self.view.addSubview(label)
// Set background color
self.view.backgroundColor = UIColor(red: 255/255, green: 214/255, blue: 59/255, alpha: 255)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didTap(sender: UITapGestureRecognizer) {
addTap()
updateLabel()
}
// Adds a tap
func addTap() {
tapTimes.append(NSDate())
if (tapTimes.count > numTapsToStore) {
tapTimes.removeAtIndex(0)
}
}
// Updates the tap label
func updateLabel() {
let tapSpeed:Double = getTapSpeed()
switch tapSpeed {
case 0...200:
label.text = "swift!"
case 201...250:
label.text = "blazing"
case 251...300:
label.text = "fast"
case 301...350:
label.text = "medium"
default:
label.text = "slow"
}
}
// Calculates the tap speed by averaging the last N taps
func getTapSpeed() -> Double {
if (tapTimes.count <= 1) {
return Double.infinity
} else {
let firstTime:Double = tapTimes[0].timeIntervalSince1970 * 1000
let lastTime:Double = tapTimes[tapTimes.count - 1].timeIntervalSince1970 * 1000
let speed:Double = lastTime - firstTime
return speed
}
}
} | mit | 241f794d186ac80b30b9137aa3fdfedc | 26.770115 | 110 | 0.57971 | 4.406934 | false | false | false | false |
jeffreybergier/Hipstapaper | Hipstapaper/Packages/V3Localize/Sources/V3Localize/Raw/Shortcuts.swift | 1 | 3489 | //
// Created by Jeffrey Bergier on 2022/08/13.
//
// MIT License
//
// Copyright (c) 2021 Jeffrey Bergier
//
// 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 SwiftUI
extension KeyboardShortcut {
internal static let commandO = KeyboardShortcut("o", modifiers: [.command] )
internal static let commandShiftO = KeyboardShortcut("o", modifiers: [.command, .shift] )
internal static let commandN = KeyboardShortcut("n", modifiers: [.command] )
internal static let commandShiftN = KeyboardShortcut("n", modifiers: [.command, .shift] )
// TODO: Change to Command A
internal static let commandShiftA = KeyboardShortcut("a", modifiers: [.command, .shift] )
internal static let commandShiftE = KeyboardShortcut("e", modifiers: [.command, .shift] )
internal static let commandOptionE = KeyboardShortcut("e", modifiers: [.command, .option] )
internal static let commandControlE = KeyboardShortcut("e", modifiers: [.command, .control])
internal static let commandR = KeyboardShortcut("r", modifiers: [.command] )
internal static let commandShiftR = KeyboardShortcut("r", modifiers: [.command, .shift] )
internal static let commandOptionR = KeyboardShortcut("r", modifiers: [.command, .option] )
internal static let commandShiftI = KeyboardShortcut("i", modifiers: [.command, .shift] )
internal static let commandL = KeyboardShortcut("l", modifiers: [.command] )
internal static let commandY = KeyboardShortcut("y", modifiers: [.command] )
internal static let commandReturn = KeyboardShortcut(.return, modifiers: [.command] )
internal static let commandBraceLeft = KeyboardShortcut("[", modifiers: [.command] )
internal static let commandBraceRight = KeyboardShortcut("]", modifiers: [.command] )
internal static let commandPeriod = KeyboardShortcut(".", modifiers: [.command] )
internal static let commandDelete = KeyboardShortcut(.delete, modifiers: [.command] )
internal static let commandOptionDelete = KeyboardShortcut(.delete, modifiers: [.command, .option] )
internal static let commandEscape = KeyboardShortcut(.escape, modifiers: [.command] )
}
| mit | a0abf55f960d051738c6dc4c693e4db2 | 66.096154 | 104 | 0.671253 | 4.702156 | false | false | false | false |
sunfei/RxSwift | Playgrounds/ObservablesOperators/Observables+Filtering.playground/Contents.swift | 3 | 1436 | import Cocoa
import RxSwift
/*:
# To use playgrounds please open `Rx.xcworkspace`, build `RxSwift-OSX` scheme and then open playgrounds in `Rx.xcworkspace` tree view.
*/
/*:
## Filtering Observables
Operators that selectively emit items from a source Observable.
### `where` / `filter`
emit only those items from an Observable that pass a predicate test
[More info in reactive.io website]( http://reactivex.io/documentation/operators/filter.html )
*/
example("filter") {
let onlyEvensSubscriber = returnElements(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>- filter {
$0 % 2 == 0
}
>- subscribeNext { value in
println("\(value)")
}
}
/*:
### `distinctUntilChanged`
suppress duplicate items emitted by an Observable
[More info in reactive.io website]( http://reactivex.io/documentation/operators/distinct.html )
*/
example("distinctUntilChanged") {
let distinctUntilChangedSubscriber = returnElements(1, 2, 3, 1, 1, 4)
>- distinctUntilChanged
>- subscribeNext { value in
println("\(value)")
}
}
/*:
### `take`
Emit only the first n items emitted by an Observable
[More info in reactive.io website]( http://reactivex.io/documentation/operators/take.html )
*/
example("take") {
let distinctUntilChangedSubscriber = returnElements(1, 2, 3, 4, 5, 6)
>- take(3)
>- subscribeNext { value in
println("\(value)")
}
}
| mit | 49db6031bd101eb52dcf7545a07b1069 | 23.338983 | 134 | 0.651114 | 4 | false | false | false | false |
wuleijun/Zeus | Zeus/ViewControllers/活动/HistoryActivityVC.swift | 1 | 1593 | //
// HistoryActivityVC.swift
// Zeus
//
// Created by 吴蕾君 on 16/3/31.
// Copyright © 2016年 rayjuneWu. All rights reserved.
//
import UIKit
class HistoryActivityVC: BaseViewController {
@IBOutlet weak var tableView: UITableView!
let activityCellId = "ActivityCell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: activityCellId, bundle:nil), forCellReuseIdentifier: activityCellId)
tableView.rowHeight = ActivityCell.heightOfCell()
tableView.keyboardDismissMode = .OnDrag
}
}
extension HistoryActivityVC : UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
defer{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
let activityDetailVC = UIViewController.controllerWith(storyboardName: "ActivityDetailVC", viewControllerId: "ActivityDetailVC")
navigationController?.pushViewController(activityDetailVC, animated: true)
}
}
extension HistoryActivityVC : UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let activityCell = tableView.dequeueReusableCellWithIdentifier(activityCellId) as! ActivityCell
return activityCell
}
} | mit | ff494998a28c2da0869df3af8bec8ff5 | 30.7 | 136 | 0.717172 | 5.369492 | false | false | false | false |
eviathan/Salt | Pepper/Code Examples/Apple/AudioUnitV3ExampleABasicAudioUnitExtensionandHostImplementation/AUv3Host/OSX/HostViewController.swift | 1 | 8634 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
View controller managing selection of an audio unit and presets, opening/closing an audio unit's view, and starting/stopping audio playback.
*/
import Cocoa
import AVFoundation
import CoreAudioKit
class HostViewController: NSViewController {
@IBOutlet weak var instrumentEffectsSelector: NSSegmentedControl!
@IBOutlet weak var playButton: NSButton!
@IBOutlet weak var effectTable: NSTableView!
@IBOutlet weak var showCustomViewButton: NSButton!
@IBOutlet weak var auViewContainer: NSView!
@IBOutlet weak var verticalLine: NSBox!
@IBOutlet weak var horizontalViewSizeConstraint: NSLayoutConstraint!
@IBOutlet weak var verticalViewSizeConstraint: NSLayoutConstraint!
@IBOutlet weak var verticalLineLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var verticalLineTrailingConstraint: NSLayoutConstraint!
let kAUViewSizeDefaultWidth: CGFloat = 484.0
let kAUViewSizeDefaultHeight:CGFloat = 400.0
var isDisplayingCustomView: Bool = false
var auView: NSView?
var playEngine: SimplePlayEngine!
override func viewDidLoad() {
super.viewDidLoad()
horizontalViewSizeConstraint.constant = 0;
verticalLineLeadingConstraint.constant = 0;
verticalLineTrailingConstraint.constant = 0;
showCustomViewButton.isEnabled = false
playEngine = SimplePlayEngine(componentType: kAudioUnitType_Effect) {
self.effectTable.reloadData()
}
}
func numberOfRowsInTableView(_ aTableView: NSTableView) -> Int {
if aTableView === effectTable {
return playEngine.availableAudioUnits.count + 1
}
return 0
}
@IBAction func togglePlay(_ sender: AnyObject?) {
let isPlaying = playEngine.togglePlay()
playButton.title = isPlaying ? "Stop" : "Play"
}
@IBAction func selectInstrumentOrEffect(_ sender: AnyObject?) {
let isInstrument = instrumentEffectsSelector.selectedSegment == 0 ? false : true
if (isInstrument) {
playEngine.setInstrument()
} else {
playEngine.setEffect()
}
playButton.title = "Play"
effectTable.reloadData()
if (self.effectTable.selectedRow <= 0) {
self.showCustomViewButton.isEnabled = false
} else {
self.showCustomViewButton.isEnabled = true
}
closeAUView()
}
func closeAUView() {
if (!isDisplayingCustomView) {
return;
}
isDisplayingCustomView = false
auView?.removeFromSuperview()
auView = nil
horizontalViewSizeConstraint.constant = 0
verticalLineLeadingConstraint.constant = 0;
verticalLineTrailingConstraint.constant = 0;
verticalLine.isHidden = true
showCustomViewButton.title = "Show Custom View"
}
@IBAction func openViewAction(_ sender: AnyObject?) {
if (isDisplayingCustomView) {
if (auView != nil) {
closeAUView()
return
}
} else {
/*
Request the view controller asynchronously from the audio unit. This
only happens if the audio unit is non-nil.
*/
playEngine.testAudioUnit?.requestViewController { [weak self] viewController in
guard let strongSelf = self else {return}
guard let viewController = viewController else {return}
strongSelf.showCustomViewButton.title = "Hide Custom View"
strongSelf.verticalLine.isHidden = false
strongSelf.verticalLineLeadingConstraint.constant = 8
strongSelf.verticalLineTrailingConstraint.constant = 8
let view = viewController.view
view.translatesAutoresizingMaskIntoConstraints = false
view.postsFrameChangedNotifications = true
var viewSize: NSSize = view.frame.size
viewSize.width = max(view.frame.width, self!.kAUViewSizeDefaultWidth)
viewSize.height = max(view.frame.height, self!.kAUViewSizeDefaultHeight)
strongSelf.horizontalViewSizeConstraint.constant = viewSize.width;
strongSelf.verticalViewSizeConstraint.constant = viewSize.height;
let superview = strongSelf.auViewContainer
superview?.addSubview(view)
let preferredSize = viewController.preferredContentSize
let views = ["view": view]; //, "superview": superview];
let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
superview?.addConstraints(horizontalConstraints)
// If a view has no preferred size, or a large preferred size, add a leading and trailing constraint. Otherwise, just a trailing constraint
if (preferredSize.height == 0 || preferredSize.height > strongSelf.kAUViewSizeDefaultHeight) {
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
superview?.addConstraints(verticalConstraints)
} else {
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
superview?.addConstraints(verticalConstraints)
}
NotificationCenter.default.addObserver(strongSelf, selector: #selector(HostViewController.auViewSizeChanged(_:)), name:
NSNotification.Name.NSViewFrameDidChange, object: nil)
strongSelf.auView = view
strongSelf.auView?.needsDisplay = true
strongSelf.auViewContainer.needsDisplay = true
strongSelf.isDisplayingCustomView = true
}
}
}
func auViewSizeChanged(_ notification : NSNotification) {
if (notification.object! as! NSView === auView ) {
self.horizontalViewSizeConstraint.constant = (notification.object! as AnyObject).frame.size.width
if ((notification.object! as AnyObject).frame.size.height > self.kAUViewSizeDefaultHeight) {
self.verticalViewSizeConstraint.constant = (notification.object! as AnyObject).frame.size.height
}
}
}
func tableView(_ tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
if tableView === effectTable {
let result = tableView.make(withIdentifier: "MyView", owner: self) as! NSTableCellView
if row > 0 && row <= playEngine.availableAudioUnits.count {
let component = playEngine.availableAudioUnits[row - 1];
result.textField!.stringValue = "\(component.name) (\(component.manufacturerName))"
} else {
if playEngine.isEffect() {
result.textField!.stringValue = "(No effect)"
} else {
result.textField!.stringValue = "(No instrument)"
}
}
return result
}
return nil
}
func tableViewSelectionDidChange(_ aNotification: NSNotification) {
let tableView: NSTableView = aNotification.object as! NSTableView
if tableView === effectTable {
self.closeAUView()
let row = tableView.selectedRow
let component: AVAudioUnitComponent?
if row > 0 {
component = playEngine.availableAudioUnits[row-1]
showCustomViewButton.isEnabled = true
} else {
component = nil
showCustomViewButton.isEnabled = false
}
playEngine.selectAudioUnitComponent(component, completionHandler: {})
}
}
}
| apache-2.0 | 3b709021ffc91d267f4121b83cd5be9b | 38.415525 | 181 | 0.606233 | 6.074595 | false | false | false | false |
koehlermichael/focus | Blockzilla/OverlayView.swift | 1 | 6327 | /* 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 SnapKit
protocol OverlayViewDelegate: class {
func overlayViewDidTouchEmptyArea(_ overlayView: OverlayView)
func overlayViewDidPressSettings(_ overlayView: OverlayView)
func overlayView(_ overlayView: OverlayView, didSearchForQuery query: String)
}
class OverlayView: UIView {
weak var delegate: OverlayViewDelegate?
fileprivate let settingsButton = UIButton()
private let searchButton = InsetButton()
private let searchBorder = UIView()
private var bottomConstraint: Constraint!
private var presented = false
private var searchQuery = ""
init() {
super.init(frame: CGRect.zero)
KeyboardHelper.defaultHelper.addDelegate(delegate: self)
searchButton.isHidden = true
searchButton.alpha = 0
searchButton.titleLabel?.font = UIConstants.fonts.searchButton
searchButton.titleLabel?.lineBreakMode = .byTruncatingTail
searchButton.contentHorizontalAlignment = .left
searchButton.setImage(#imageLiteral(resourceName: "icon_searchfor"), for: .normal)
searchButton.setImage(#imageLiteral(resourceName: "icon_searchfor"), for: .highlighted)
let padding = UIConstants.layout.searchButtonInset
searchButton.imageEdgeInsets = UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding)
searchButton.titleEdgeInsets = UIEdgeInsets(top: padding, left: padding * 2, bottom: padding, right: padding)
searchButton.addTarget(self, action: #selector(didPressSearch), for: .touchUpInside)
addSubview(searchButton)
searchBorder.isHidden = true
searchBorder.alpha = 0
searchBorder.backgroundColor = UIConstants.colors.settingsButtonBorder
addSubview(searchBorder)
settingsButton.setImage(#imageLiteral(resourceName: "icon_settings"), for: .normal)
settingsButton.contentEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
settingsButton.addTarget(self, action: #selector(didPressSettings), for: .touchUpInside)
addSubview(settingsButton)
searchButton.snp.makeConstraints { make in
make.top.leading.trailing.equalTo(self)
}
searchBorder.snp.makeConstraints { make in
make.leading.trailing.equalTo(self)
make.top.equalTo(searchButton.snp.bottom)
make.height.equalTo(1)
}
settingsButton.snp.makeConstraints { make in
make.trailing.equalTo(self)
bottomConstraint = make.bottom.equalTo(self).constraint
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setSearchQuery(query: String, animated: Bool) {
searchQuery = query
let query = query.trimmingCharacters(in: .whitespaces)
// Show or hide the search button depending on whether there's entered text.
if searchButton.isHidden != query.isEmpty {
let duration = animated ? UIConstants.layout.searchButtonAnimationDuration : 0
searchButton.animateHidden(query.isEmpty, duration: duration)
searchBorder.animateHidden(query.isEmpty, duration: duration)
}
// Use [ and ] to help find the position of the search query, then delete them.
let searchTitle = NSMutableString(string: String(format: UIConstants.strings.searchButton, "[\(query)]"))
let startIndex = searchTitle.range(of: "[")
let endIndex = searchTitle.range(of: "]", options: .backwards)
searchTitle.deleteCharacters(in: endIndex)
searchTitle.deleteCharacters(in: startIndex)
let attributedString = NSMutableAttributedString(string: searchTitle as String)
let queryRange = NSMakeRange(startIndex.location, (query as NSString).length)
let fullRange = NSMakeRange(0, searchTitle.length)
attributedString.addAttributes([NSFontAttributeName: UIConstants.fonts.searchButtonQuery], range: queryRange)
attributedString.addAttributes([NSForegroundColorAttributeName: UIColor.white], range: fullRange)
searchButton.setAttributedTitle(attributedString, for: .normal)
}
fileprivate func animateWithKeyboard(keyboardState: KeyboardState) {
UIView.animate(withDuration: keyboardState.animationDuration, animations: {
let keyboardHeight = keyboardState.intersectionHeightForView(view: self)
self.bottomConstraint.update(offset: -keyboardHeight)
self.layoutIfNeeded()
})
}
@objc private func didPressSearch() {
delegate?.overlayView(self, didSearchForQuery: searchQuery)
}
@objc private func didPressSettings() {
delegate?.overlayViewDidPressSettings(self)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
delegate?.overlayViewDidTouchEmptyArea(self)
}
func dismiss() {
setSearchQuery(query: "", animated: false)
self.isUserInteractionEnabled = false
animateHidden(true, duration: UIConstants.layout.overlayAnimationDuration) {
self.isUserInteractionEnabled = true
}
}
func present() {
setSearchQuery(query: "", animated: false)
self.isUserInteractionEnabled = false
animateHidden(false, duration: UIConstants.layout.overlayAnimationDuration) {
self.isUserInteractionEnabled = true
}
}
}
extension OverlayView: KeyboardHelperDelegate {
public func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) {
animateWithKeyboard(keyboardState: state)
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) {
animateWithKeyboard(keyboardState: state)
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) {}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidHideWithState state: KeyboardState) {}
}
| mpl-2.0 | d750b7cf12083235fcd0fe761d5a120e | 40.900662 | 117 | 0.707286 | 5.339241 | false | false | false | false |
githubError/KaraNotes | KaraNotes/KaraNotes/Attention/Model/CPFSearchArticleModel.swift | 1 | 1662 | //
// CPFSearchArticleModel.swift
// KaraNotes
//
// Created by 崔鹏飞 on 2017/5/2.
// Copyright © 2017年 崔鹏飞. All rights reserved.
//
import Foundation
struct CPFSearchArticleModel {
var article_create_time:TimeInterval
var article_id:String
var article_show_img:String
var article_title:String
var user_name:String
var article_create_formatTime:String {
return timestampToString(timestamp: article_create_time)
}
var article_show_img_URL:URL {
return URL(string: article_show_img)!
}
}
extension CPFSearchArticleModel {
static func parse(json: JSONDictionary) -> CPFSearchArticleModel {
guard let userinfo = json["userinfo"] as? JSONDictionary else {fatalError("解析CPFSearchArticleModel出错")}
guard let user_name = userinfo["user_name"] as? String else {fatalError("解析CPFSearchArticleModel出错")}
guard let article_create_time = json["article_create_time"] as? TimeInterval else {fatalError("解析CPFSearchArticleModel出错")}
guard let article_id = json["article_id"] as? String else {fatalError("解析CPFSearchArticleModel出错")}
guard let article_show_img = json["article_show_img"] as? String else {fatalError("解析CPFSearchArticleModel出错")}
guard let article_title = json["article_title"] as? String else {fatalError("解析CPFSearchArticleModel出错")}
return CPFSearchArticleModel(article_create_time: article_create_time, article_id: article_id, article_show_img: article_show_img, article_title: article_title, user_name: user_name)
}
}
| apache-2.0 | 4efa483309199cb0c3fd158c1e88f7ad | 36.186047 | 190 | 0.697311 | 4.491573 | false | false | false | false |
Virpik/T | src/UI/TableView/TableViewModel/TableViewModel.Handlers.swift | 1 | 1544 | //
// TableViewModel.Handlers.swift
// TDemo
//
// Created by Virpik on 29/12/2017.
// Copyright © 2017 Virpik. All rights reserved.
//
import Foundation
import UIKit
public extension TableViewModel {
public struct Handlers {
public typealias DefaultBlock = ((AnyRowModel, UITableViewCell, IndexPath) -> Void)
// debug
public var handler: Block?
public var handlerDidScroll: ((UIScrollView) -> Void)?
public var handlerDidSelect: DefaultBlock?
public var handlerDidDeselect: DefaultBlock?
public var moveHandlers: MoveHandlers?
public init() {
}
}
public struct MoveHandlers {
/// Захват ячейки перемещения
public var handlerBeginMove: ((_ context: CellContext) -> Void)?
/// Каждый такт перемещения захваченой ячейки (context.indexPath == to || != to)
public var handlerMove: ((_ atContext: CellContext, _ toContext: CellContext?) -> Void)?
/// При перемещении ячейки в таблице (context.indexPath != to)
public var handlerDidMove: ((_ atContext: CellContext, _ toContext: CellContext) -> Void)?
/// При очищении контекста захваченой ячейки
public var handlerEndMove: ((_ atContext: CellContext, _ toContext: CellContext?) -> Void)?
public init() {
}
}
}
| mit | 100686608f2739de246ecf183557f882 | 27.38 | 99 | 0.60747 | 4.698675 | false | false | false | false |
sven820/Brick | Brick/Pods/ReactiveCocoa/ReactiveCocoa/UIKit/UIBarButtonItem.swift | 2 | 1396 | import ReactiveSwift
import UIKit
extension Reactive where Base: UIBarButtonItem {
/// The current associated action of `self`.
private var associatedAction: Atomic<(action: CocoaAction<Base>, disposable: Disposable?)?> {
return associatedValue { _ in Atomic(nil) }
}
/// The action to be triggered when the button is pressed. It also controls
/// the enabled state of the button.
public var pressed: CocoaAction<Base>? {
get {
return associatedAction.value?.action
}
nonmutating set {
base.target = newValue
base.action = newValue.map { _ in CocoaAction<Base>.selector }
associatedAction
.swap(newValue.map { action in
let disposable = isEnabled <~ action.isEnabled
return (action, disposable)
})?
.disposable?.dispose()
}
}
/// Sets the style of the bar button item.
public var style: BindingTarget<UIBarButtonItem.Style> {
return makeBindingTarget { $0.style = $1 }
}
/// Sets the width of the bar button item.
public var width: BindingTarget<CGFloat> {
return makeBindingTarget { $0.width = $1 }
}
/// Sets the possible titles of the bar button item.
public var possibleTitles: BindingTarget<Set<String>?> {
return makeBindingTarget { $0.possibleTitles = $1 }
}
/// Sets the custom view of the bar button item.
public var customView: BindingTarget<UIView?> {
return makeBindingTarget { $0.customView = $1 }
}
}
| mit | dbc688e0c2b110f32f324804621e014d | 27.489796 | 94 | 0.704871 | 3.888579 | false | false | false | false |
liuxuan30/ios-charts | ChartsDemo-macOS/PlaygroundChart.playground/Pages/LineChart.xcplaygroundpage/Contents.swift | 4 | 4805 | //
// PlayGround
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// Copyright © 2017 thierry Hentic.
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
/*:
****
[Menu](Menu)
[Previous](@previous) | [Next](@next)
****
*/
//: # Line Chart
import Cocoa
import Charts
import PlaygroundSupport
let r = CGRect(x: 0, y: 0, width: 600, height: 600)
var chartView = LineChartView(frame: r)
//: ### General
chartView.dragEnabled = true
chartView.setScaleEnabled ( true)
chartView.drawGridBackgroundEnabled = false
chartView.pinchZoomEnabled = true
chartView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
chartView.borderColor = NSUIColor.black
chartView.borderLineWidth = 1.0
chartView.drawBordersEnabled = true
//: ### xAxis
let xAxis = chartView.xAxis
xAxis.labelFont = NSUIFont.systemFont(ofSize: CGFloat(12.0))
xAxis.labelTextColor = #colorLiteral(red: 0.1764705926, green: 0.01176470611, blue: 0.5607843399, alpha: 1)
xAxis.drawGridLinesEnabled = true
xAxis.drawAxisLineEnabled = true
xAxis.labelPosition = .bottom
xAxis.labelRotationAngle = 0
xAxis.axisMinimum = 0
//: ### LeftAxis
let leftAxis = chartView.leftAxis
leftAxis.labelTextColor = #colorLiteral(red: 0.215686274509804, green: 0.709803921568627, blue: 0.898039215686275, alpha: 1.0)
leftAxis.axisMaximum = 200.0
leftAxis.axisMinimum = 0.0
leftAxis.drawGridLinesEnabled = true
leftAxis.drawZeroLineEnabled = false
leftAxis.granularityEnabled = true
//: ### RightAxis
let rightAxis = chartView.rightAxis
rightAxis.labelTextColor = #colorLiteral(red: 1, green: 0.1474981606, blue: 0, alpha: 1)
rightAxis.axisMaximum = 900.0
rightAxis.axisMinimum = -200.0
rightAxis.drawGridLinesEnabled = false
rightAxis.granularityEnabled = false
//: ### Legend
let legend = chartView.legend
legend.font = NSUIFont(name: "HelveticaNeue-Light", size: CGFloat(12.0))!
legend.textColor = NSUIColor.labelOrBlack
legend.form = .square
legend.drawInside = false
legend.orientation = .horizontal
legend.verticalAlignment = .bottom
legend.horizontalAlignment = .left
//: ### Description
chartView.chartDescription?.enabled = false
//: ### ChartDataEntry
var yVals1 = [ChartDataEntry]()
var yVals2 = [ChartDataEntry]()
var yVals3 = [ChartDataEntry]()
let range = 30.0
for i in 0..<20 {
let mult: Double = range / 2.0
let val = Double(arc4random_uniform(UInt32(mult))) + 50
yVals1.append(ChartDataEntry(x: Double(i), y: val))
}
for i in 0..<20 - 1 {
let mult: Double = range
let val = Double(arc4random_uniform(UInt32(mult))) + 450
yVals2.append(ChartDataEntry(x: Double(i), y: val))
}
for i in 0..<20 {
let mult: Double = range
let val = Double(arc4random_uniform(UInt32(mult))) + 500
yVals3.append(ChartDataEntry(x: Double(i), y: val))
}
var set1 = LineChartDataSet()
var set2 = LineChartDataSet()
var set3 = LineChartDataSet()
set1 = LineChartDataSet(values: yVals1, label: "DataSet 1")
set1.axisDependency = .left
set1.colors = [#colorLiteral(red: 0.215686274509804, green: 0.709803921568627, blue: 0.898039215686275, alpha: 1.0)]
set1.circleColors = [NSUIColor.white]
set1.lineWidth = 2.0
set1.circleRadius = 3.0
set1.fillAlpha = 65 / 255.0
set1.fillColor = #colorLiteral(red: 0.215686274509804, green: 0.709803921568627, blue: 0.898039215686275, alpha: 1.0)
set1.highlightColor = NSUIColor.blue
set1.highlightEnabled = true
set1.drawCircleHoleEnabled = false
set2 = LineChartDataSet(values: yVals2, label: "DataSet 2")
set2.axisDependency = .right
set2.colors = [NSUIColor.red]
set2.circleColors = [NSUIColor.white]
set2.lineWidth = 2.0
set2.circleRadius = 3.0
set2.fillAlpha = 65 / 255.0
set2.fillColor = NSUIColor.red
set2.highlightColor = NSUIColor.red
set2.highlightEnabled = true
set2.drawCircleHoleEnabled = false
set3 = LineChartDataSet(values: yVals3, label: "DataSet 3")
set3.axisDependency = .right
set3.colors = [NSUIColor.green]
set3.circleColors = [NSUIColor.white]
set3.lineWidth = 2.0
set3.circleRadius = 3.0
set3.fillAlpha = 65 / 255.0
set3.fillColor = NSUIColor.yellow.withAlphaComponent(200 / 255.0)
set3.highlightColor = NSUIColor.green
set3.highlightEnabled = true
set3.drawCircleHoleEnabled = false
var dataSets = [LineChartDataSet]()
dataSets.append(set1)
dataSets.append(set2)
dataSets.append(set3)
//: ### LineChartData
let data = LineChartData(dataSets: dataSets)
data.setValueTextColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1))
data.setValueFont(NSUIFont(name: "HelveticaNeue-Light", size: CGFloat(9.0)))
chartView.data = data
chartView.data?.notifyDataChanged()
chartView.notifyDataSetChanged()
/*:---*/
//: ### Setup for the live view
PlaygroundPage.current.liveView = chartView
/*:
****
[Previous](@previous) | [Next](@next)
*/
| apache-2.0 | c11337c834ad62d12c62632b1a8df2a9 | 29.598726 | 126 | 0.745212 | 3.571747 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ColorPixel/ColorPixel.swift | 1 | 12710 | //
// ColorPixel.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public protocol ColorPixel: Hashable {
associatedtype Model: ColorModel
init()
init(color: Model, opacity: Double)
init<C: ColorPixel>(_ color: C) where Model == C.Model
func component(_ index: Int) -> Double
mutating func setComponent(_ index: Int, _ value: Double)
var color: Model { get set }
var opacity: Double { get set }
var isOpaque: Bool { get }
func with(opacity: Double) -> Self
func premultiplied() -> Self
func unpremultiplied() -> Self
func blended(source: Self) -> Self
func blended(source: Self, compositingMode: ColorCompositingMode, blendMode: ColorBlendMode) -> Self
}
extension ColorPixel where Self: ScalarMultiplicative {
@inlinable
@inline(__always)
public static var zero: Self {
return Self()
}
}
extension ColorPixel {
@inlinable
@inline(__always)
public init(_ color: Color<Model>) {
self.init(color: color.color, opacity: color.opacity)
}
@inlinable
@inline(__always)
public init<C: ColorPixel>(_ color: C) where Model == C.Model {
self.init(color: color.color, opacity: color.opacity)
}
}
extension ColorPixel {
@inlinable
@inline(__always)
public init() {
self.init(color: Model(), opacity: 0)
}
}
extension ColorPixel {
@inlinable
@inline(__always)
public func with(opacity: Double) -> Self {
var c = self
c.opacity = opacity
return c
}
}
extension ColorPixel {
@inlinable
@inline(__always)
public func premultiplied() -> Self {
return Self(color: color * opacity, opacity: opacity)
}
@inlinable
@inline(__always)
public func unpremultiplied() -> Self {
guard opacity != 0 else { return self }
return Self(color: color / opacity, opacity: opacity)
}
}
extension ColorPixel {
@inlinable
@inline(__always)
public static var bitsPerPixel: Int {
return MemoryLayout<Self>.stride << 3
}
@inlinable
@inline(__always)
public var bitsPerPixel: Int {
return Self.bitsPerPixel
}
}
extension ColorPixel {
@inlinable
@inline(__always)
public static var numberOfComponents: Int {
return Model.numberOfComponents + 1
}
@inlinable
@inline(__always)
public var numberOfComponents: Int {
return Self.numberOfComponents
}
}
extension ColorPixel {
@inlinable
@inline(__always)
public func component(_ index: Int) -> Double {
if index < Model.numberOfComponents {
return color[index]
} else if index == Model.numberOfComponents {
return opacity
} else {
fatalError("Index out of range.")
}
}
@inlinable
@inline(__always)
public mutating func setComponent(_ index: Int, _ value: Double) {
if index < Model.numberOfComponents {
color[index] = value
} else if index == Model.numberOfComponents {
opacity = value
} else {
fatalError("Index out of range.")
}
}
}
extension ColorPixel {
@inlinable
@inline(__always)
public var isOpaque: Bool {
return opacity >= 1
}
}
extension ColorPixel {
@inlinable
@inline(__always)
public mutating func blend(source: Self) {
self = self.blended(source: source)
}
@inlinable
@inline(__always)
public mutating func blend<C: ColorPixel>(source: C) where C.Model == Model {
self = self.blended(source: source)
}
@inlinable
@inline(__always)
public mutating func blend(source: Self, compositingMode: ColorCompositingMode, blendMode: ColorBlendMode) {
self = self.blended(source: source, compositingMode: compositingMode, blendMode: blendMode)
}
@inlinable
@inline(__always)
public mutating func blend<C: ColorPixel>(source: C, compositingMode: ColorCompositingMode, blendMode: ColorBlendMode) where C.Model == Model {
self = self.blended(source: source, compositingMode: compositingMode, blendMode: blendMode)
}
@inlinable
@inline(__always)
public func blended(source: Self) -> Self {
return blended(source: source, compositingMode: .default, blendMode: .default)
}
@inlinable
@inline(__always)
public func blended<C: ColorPixel>(source: C) -> Self where C.Model == Model {
return blended(source: Self(source))
}
@inlinable
@inline(__always)
public func blended<C: ColorPixel>(source: C, compositingMode: ColorCompositingMode, blendMode: ColorBlendMode) -> Self where C.Model == Model {
return blended(source: Self(source), compositingMode: compositingMode, blendMode: blendMode)
}
}
extension ColorPixel where Model == XYZColorModel {
@inlinable
@inline(__always)
public init(x: Double, y: Double, z: Double, opacity: Double = 1) {
self.init(color: XYZColorModel(x: x, y: y, z: z), opacity: opacity)
}
@inlinable
@inline(__always)
public init(luminance: Double, point: Point, opacity: Double = 1) {
self.init(color: XYZColorModel(luminance: luminance, point: point), opacity: opacity)
}
@inlinable
@inline(__always)
public init(luminance: Double, x: Double, y: Double, opacity: Double = 1) {
self.init(color: XYZColorModel(luminance: luminance, x: x, y: y), opacity: opacity)
}
}
extension ColorPixel where Model == YxyColorModel {
@inlinable
@inline(__always)
public init(luminance: Double, point: Point, opacity: Double = 1) {
self.init(color: YxyColorModel(luminance: luminance, point: point), opacity: opacity)
}
@inlinable
@inline(__always)
public init(luminance: Double, x: Double, y: Double, opacity: Double = 1) {
self.init(color: YxyColorModel(luminance: luminance, x: x, y: y), opacity: opacity)
}
}
extension ColorPixel where Model == LabColorModel {
@inlinable
@inline(__always)
public init(lightness: Double, a: Double, b: Double, opacity: Double = 1) {
self.init(color: LabColorModel(lightness: lightness, a: a, b: b), opacity: opacity)
}
@inlinable
@inline(__always)
public init(lightness: Double, chroma: Double, hue: Double, opacity: Double = 1) {
self.init(color: LabColorModel(lightness: lightness, chroma: chroma, hue: hue), opacity: opacity)
}
}
extension ColorPixel where Model == LuvColorModel {
@inlinable
@inline(__always)
public init(lightness: Double, u: Double, v: Double, opacity: Double = 1) {
self.init(color: LuvColorModel(lightness: lightness, u: u, v: v), opacity: opacity)
}
@inlinable
@inline(__always)
public init(lightness: Double, chroma: Double, hue: Double, opacity: Double = 1) {
self.init(color: LuvColorModel(lightness: lightness, chroma: chroma, hue: hue), opacity: opacity)
}
}
extension ColorPixel where Model == GrayColorModel {
@inlinable
@inline(__always)
public init(white: Double, opacity: Double = 1) {
self.init(color: GrayColorModel(white: white), opacity: opacity)
}
}
extension ColorPixel where Model == RGBColorModel {
@inlinable
@inline(__always)
public init(red: Double, green: Double, blue: Double, opacity: Double = 1) {
self.init(color: RGBColorModel(red: red, green: green, blue: blue), opacity: opacity)
}
@inlinable
@inline(__always)
public init(hue: Double, saturation: Double, brightness: Double, opacity: Double = 1) {
self.init(color: RGBColorModel(hue: hue, saturation: saturation, brightness: brightness), opacity: opacity)
}
}
extension ColorPixel where Model == CMYColorModel {
@inlinable
@inline(__always)
public init(cyan: Double, magenta: Double, yellow: Double, opacity: Double = 1) {
self.init(color: CMYColorModel(cyan: cyan, magenta: magenta, yellow: yellow), opacity: opacity)
}
}
extension ColorPixel where Model == CMYKColorModel {
@inlinable
@inline(__always)
public init(cyan: Double, magenta: Double, yellow: Double, black: Double, opacity: Double = 1) {
self.init(color: CMYKColorModel(cyan: cyan, magenta: magenta, yellow: yellow, black: black), opacity: opacity)
}
}
extension ColorPixel where Model == GrayColorModel {
@inlinable
@inline(__always)
public var white: Double {
get {
return color.white
}
set {
color.white = newValue
}
}
}
extension ColorPixel where Model == RGBColorModel {
@inlinable
@inline(__always)
public var red: Double {
get {
return color.red
}
set {
color.red = newValue
}
}
@inlinable
@inline(__always)
public var green: Double {
get {
return color.green
}
set {
color.green = newValue
}
}
@inlinable
@inline(__always)
public var blue: Double {
get {
return color.blue
}
set {
color.blue = newValue
}
}
}
extension ColorPixel where Model == RGBColorModel {
@inlinable
@inline(__always)
public var hue: Double {
get {
return color.hue
}
set {
color.hue = newValue
}
}
@inlinable
@inline(__always)
public var saturation: Double {
get {
return color.saturation
}
set {
color.saturation = newValue
}
}
@inlinable
@inline(__always)
public var brightness: Double {
get {
return color.brightness
}
set {
color.brightness = newValue
}
}
}
extension ColorPixel where Model == CMYColorModel {
@inlinable
@inline(__always)
public var cyan: Double {
get {
return color.cyan
}
set {
color.cyan = newValue
}
}
@inlinable
@inline(__always)
public var magenta: Double {
get {
return color.magenta
}
set {
color.magenta = newValue
}
}
@inlinable
@inline(__always)
public var yellow: Double {
get {
return color.yellow
}
set {
color.yellow = newValue
}
}
}
extension ColorPixel where Model == CMYKColorModel {
@inlinable
@inline(__always)
public var cyan: Double {
get {
return color.cyan
}
set {
color.cyan = newValue
}
}
@inlinable
@inline(__always)
public var magenta: Double {
get {
return color.magenta
}
set {
color.magenta = newValue
}
}
@inlinable
@inline(__always)
public var yellow: Double {
get {
return color.yellow
}
set {
color.yellow = newValue
}
}
@inlinable
@inline(__always)
public var black: Double {
get {
return color.black
}
set {
color.black = newValue
}
}
}
| mit | a26019b4d9e827baa097b0d79e69e461 | 24.26839 | 148 | 0.598112 | 4.442503 | false | false | false | false |
jpchmura/JPCDataSourceController | Source/JPCTableViewController.swift | 1 | 3076 | //
// JPCTableViewController.swift
// JPCDataSourceController
//
// Created by Jon Chmura on 4/9/15.
// Copyright (c) 2015 Jon Chmura. All rights reserved.
//
//
// Source: https://github.com/jpchmura/JPCDataSourceController
//
// License: MIT ( http://opensource.org/licenses/MIT )
//
import UIKit
public class JPCTableViewController: UITableViewController, DataSourceControllerDelegate {
public var dataSourceController: DataSourceController!
public override func loadView() {
super.loadView()
self.dataSourceController = DataSourceController(tableView: self.tableView)
// Some UITableViewDataSource calls are forwarded from the DataSourceController.
self.dataSourceController.tableViewDataSource = self
// By defualt non-grouped style table view will show separators even for cells that aren't present.
// This behavior can be disable by setting the footer to a 0 height view.
if self.tableView.style == .Plain {
self.tableView.tableFooterView = UIView()
}
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.dataSourceController.viewWillAppear()
}
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.dataSourceController.viewWillDisappear()
}
public override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return self.dataSourceController.tableView(tableView, viewForHeaderInSection: section)
}
public override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return self.dataSourceController.tableView(tableView, viewForFooterInSection: section)
}
// MARK: - Data Source Controller Delegate
public func dataSourceController(controller: DataSourceController, cellFactoryForModel model: Model, atIndexPath indexPath: NSIndexPath) -> CellFactory? {
return nil
}
public func dataSourceController(controller: DataSourceController, embeddedCollectionViewForModel model: Model, atIndexPath: NSIndexPath) -> UICollectionView? {
return nil
}
public func dataSourceController(controller: DataSourceController, didTransitionToOperationState toState: DataSourceController.OperationState, fromState: DataSourceController.OperationState) {
}
public func dataSourceController(controller: DataSourceController, didTransitionToContentState toState: DataSourceController.ContentState, fromState: DataSourceController.ContentState) {
}
public func dataSourceController(controller: DataSourceController, shouldErrorForFetches fetchRequests: [FetchRequest]) -> Bool? {
return nil
}
public func dataSourceController(controller: DataSourceController, shouldErrorForModel model: Model) -> Bool? {
return nil
}
}
| mit | 30673866c4799e1b8e3a20b3837833e1 | 35.188235 | 196 | 0.712289 | 5.803774 | false | false | false | false |
roecrew/AudioKit | AudioKit/Common/Playgrounds/Analysis.playground/Pages/Output Waveform Plot.xcplaygroundpage/Contents.swift | 1 | 2147 | //: ## Output Waveform Plot
//: If you open the Assitant editor and make sure it shows the
//: "Output Waveform Plot.xcplaygroundpage (Timeline) view",
//: you should see a plot of the waveform in real time
import XCPlayground
import AudioKit
var oscillator = AKFMOscillator()
oscillator.amplitude = 0.1
oscillator.rampTime = 0.1
AudioKit.output = oscillator
AudioKit.start()
oscillator.start()
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Output Waveform Plot")
addSubview(AKPropertySlider(
property: "Frequency",
format: "%0.2f Hz",
value: oscillator.baseFrequency, maximum: 800,
color: AKColor.yellowColor()
) { frequency in
oscillator.baseFrequency = frequency
})
addSubview(AKPropertySlider(
property: "Carrier Multiplier",
format: "%0.3f",
value: oscillator.carrierMultiplier, maximum: 3,
color: AKColor.redColor()
) { multiplier in
oscillator.carrierMultiplier = multiplier
})
addSubview(AKPropertySlider(
property: "Modulating Multiplier",
format: "%0.3f",
value: oscillator.modulatingMultiplier, maximum: 3,
color: AKColor.greenColor()
) { multiplier in
oscillator.modulatingMultiplier = multiplier
})
addSubview(AKPropertySlider(
property: "Modulation Index",
format: "%0.3f",
value: oscillator.modulationIndex, maximum: 3,
color: AKColor.cyanColor()
) { index in
oscillator.modulationIndex = index
})
addSubview(AKPropertySlider(
property: "Amplitude",
format: "%0.3f",
value: oscillator.amplitude,
color: AKColor.purpleColor()
) { amplitude in
oscillator.amplitude = amplitude
})
addSubview(AKOutputWaveformPlot.createView())
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
| mit | ee0ad90598dfe3dd82c354adfec29606 | 28.410959 | 63 | 0.616674 | 5.314356 | false | false | false | false |
DeveloperJx/JXAutoEncoder | Demo/JXAutoEncoder/Model/ArchiverModel.swift | 1 | 2581 | //
// ArchiverModel.swift
// JXAutoEncoder
//
// Created by jx on 2017/2/9.
// Copyright © 2017年 jx. All rights reserved.
//
import UIKit
class ArchiverModel: JXAutoEncoder {
var bool = true
var int = 1
var double = CGFloat.pi
var string = ""
var array = ["123", "456"]
var dictionary = ["abc": "cba"]
var data = "hello world".data(using: String.Encoding.utf8)
var date = Date()
/// 归档到文件
func archiveToFile() {
var modelFile = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,
FileManager.SearchPathDomainMask.userDomainMask,
true)[0]
modelFile += "/model.data"
NSKeyedArchiver.archiveRootObject(self, toFile: modelFile)
}
/// 从文件中解档
///
/// - Returns: 解档后的Model
class func decodedFromFile() throws -> ArchiverModel {
var modelFile = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,
FileManager.SearchPathDomainMask.userDomainMask,
true)[0]
modelFile += "/model.data"
if FileManager.default.fileExists(atPath: modelFile) {
if let model = NSKeyedUnarchiver.unarchiveObject(withFile: modelFile) as? ArchiverModel {
return model
}else{
throw NSError(domain: "Unarchive fail", code: 100, userInfo: nil)
}
}else{
throw NSError(domain: "File doesn't exists", code: 101, userInfo: nil)
}
}
/// 删除归档文件
class func removeFile() throws {
var modelFile = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,
FileManager.SearchPathDomainMask.userDomainMask,
true)[0]
modelFile += "/model.data"
if FileManager.default.fileExists(atPath: modelFile) {
do {
try FileManager.default.removeItem(at: URL(fileURLWithPath: modelFile))
} catch {
throw NSError(domain: "Remove file fail", code: 101, userInfo: nil)
}
}else{
throw NSError(domain: "File doesn't exists", code: 101, userInfo: nil)
}
}
}
| mit | 98b3c518d724e3241ec8ae4df8cc26ab | 35.753623 | 110 | 0.540221 | 5.537118 | false | false | false | false |
nathawes/swift | test/IRGen/prespecialized-metadata/enum-inmodule-4argument-1distinct_use.swift | 2 | 4274 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5ValueOyS4iGWV" = linkonce_odr hidden constant %swift.enum_vwtable {
// CHECK-SAME: i8* bitcast ({{([^@]+@"\$s4main5ValueOyS4iGwCP+[^\)]+ to i8\*|[^@]+@__swift_memcpy[0-9]+_[0-9]+[^\)]+ to i8\*)}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_noop_void_return{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS4iGwet{{[^)]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS4iGwst{{[^)]+}} to i8*),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS4iGwug{{[^)]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS4iGwup{{[^)]+}} to i8*),
// CHECK-SAME i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS4iGwui{{[^)]+}} to i8*)
// CHECK-SAME: }, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueOyS4iGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// CHECK-SAME: i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main5ValueOyS4iGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: [[INT]] {{32|16}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
enum Value<First, Second, Third, Fourth> {
case first(First)
case second(First, Second)
case third(First, Second, Third)
case fourth(First, Second, Third, Fourth)
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5ValueOyS4iGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Value.fourth(13, 14, 15, 16) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, i8** %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_BUFFER:%[0-9]+]] = bitcast i8** %1 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @swift_getGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_BUFFER]],
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | 620dfcf87615986e0612853e5b14c678 | 42.612245 | 157 | 0.55592 | 2.895664 | false | false | false | false |
TrustWallet/trust-wallet-ios | Trust/AppDelegate.swift | 1 | 3420 | // Copyright DApps Platform Inc. All rights reserved.
import UIKit
import Branch
import RealmSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
var coordinator: AppCoordinator!
//This is separate coordinator for the protection of the sensitive information.
lazy var protectionCoordinator: ProtectionCoordinator = {
return ProtectionCoordinator()
}()
let urlNavigatorCoordinator = URLNavigatorCoordinator()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let sharedMigration = SharedMigrationInitializer()
sharedMigration.perform()
let realm = try! Realm(configuration: sharedMigration.config)
let walletStorage = WalletStorage(realm: realm)
let keystore = EtherKeystore(storage: walletStorage)
coordinator = AppCoordinator(window: window!, keystore: keystore, navigator: urlNavigatorCoordinator)
coordinator.start()
if !UIApplication.shared.isProtectedDataAvailable {
fatalError()
}
protectionCoordinator.didFinishLaunchingWithOptions()
urlNavigatorCoordinator.branch.didFinishLaunchingWithOptions(launchOptions: launchOptions)
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
coordinator.didRegisterForRemoteNotificationsWithDeviceToken(deviceToken: deviceToken)
}
func applicationWillResignActive(_ application: UIApplication) {
protectionCoordinator.applicationWillResignActive()
Lock().setAutoLockTime()
CookiesStore.save()
}
func applicationDidBecomeActive(_ application: UIApplication) {
protectionCoordinator.applicationDidBecomeActive()
CookiesStore.load()
}
func applicationDidEnterBackground(_ application: UIApplication) {
protectionCoordinator.applicationDidEnterBackground()
}
func applicationWillEnterForeground(_ application: UIApplication) {
protectionCoordinator.applicationWillEnterForeground()
}
func application(_ application: UIApplication, shouldAllowExtensionPointIdentifier extensionPointIdentifier: UIApplicationExtensionPointIdentifier) -> Bool {
if extensionPointIdentifier == UIApplicationExtensionPointIdentifier.keyboard {
return false
}
return true
}
// func application(
// _ application: UIApplication,
// didReceiveRemoteNotification userInfo: [AnyHashable: Any],
// fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// Branch.getInstance().handlePushNotification(userInfo)
// }
// Respond to URI scheme links
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool {
return urlNavigatorCoordinator.application(app, open: url, options: options)
}
// Respond to Universal Links
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
Branch.getInstance().continue(userActivity)
return true
}
}
| gpl-3.0 | 55b1d283593d5bc21352d2cb3a7a7638 | 39.714286 | 161 | 0.734211 | 6.309963 | false | false | false | false |
sschiau/swift | test/IRGen/generic_casts.swift | 6 | 6024 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -enable-objc-interop -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
import Foundation
import gizmo
// -- Protocol records for cast-to ObjC protocols
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_ = private constant
// CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section {{"__DATA,__objc_protolist,coalesced,no_dead_strip"|"objc_protolist"|".objc_protolist\$B"}}
// CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section {{"__DATA,__objc_protorefs,coalesced,no_dead_strip"|"objc_protorefs"|".objc_protorefs\$B"}}
// CHECK: @_PROTOCOL_NSRuncing = private constant
// CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section {{"__DATA,__objc_protolist,coalesced,no_dead_strip"|"objc_protolist"|".objc_protolist\$B"}}
// CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section {{"__DATA,__objc_protorefs,coalesced,no_dead_strip"|"objc_protorefs"|".objc_protorefs\$B"}}
// CHECK: @_PROTOCOLS__TtC13generic_casts10ObjCClass2 = private constant { i64, [1 x i8*] } {
// CHECK: i64 1,
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto2_
// CHECK: }
// CHECK: @_DATA__TtC13generic_casts10ObjCClass2 = private constant {{.*}} @_PROTOCOLS__TtC13generic_casts10ObjCClass2
// CHECK: @_PROTOCOL_PROTOCOLS__TtP13generic_casts10ObjCProto2_ = private constant { i64, [1 x i8*] } {
// CHECK: i64 1,
// CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_
// CHECK: }
// CHECK: define hidden swiftcc i64 @"$s13generic_casts8allToIntySixlF"(%swift.opaque* noalias nocapture, %swift.type* %T)
func allToInt<T>(_ x: T) -> Int {
return x as! Int
// CHECK: [[INT_TEMP:%.*]] = alloca %TSi,
// CHECK: [[TYPE_ADDR:%.*]] = bitcast %swift.type* %T to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[TYPE_ADDR]], i64 -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable*
// CHECK: [[SIZE_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8
// CHECK: [[SIZE:%.*]] = load i64, i64* [[SIZE_ADDR]]
// CHECK: [[T_ALLOCA:%.*]] = alloca i8, {{.*}} [[SIZE]], align 16
// CHECK: [[T_TMP:%.*]] = bitcast i8* [[T_ALLOCA]] to %swift.opaque*
// CHECK: [[TEMP:%.*]] = call %swift.opaque* {{.*}}(%swift.opaque* noalias [[T_TMP]], %swift.opaque* noalias %0, %swift.type* %T)
// CHECK: [[T0:%.*]] = bitcast %TSi* [[INT_TEMP]] to %swift.opaque*
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* [[T0]], %swift.opaque* [[T_TMP]], %swift.type* %T, %swift.type* @"$sSiN", i64 7)
// CHECK: [[T0:%.*]] = getelementptr inbounds %TSi, %TSi* [[INT_TEMP]], i32 0, i32 0
// CHECK: [[INT_RESULT:%.*]] = load i64, i64* [[T0]],
// CHECK: ret i64 [[INT_RESULT]]
}
// CHECK: define hidden swiftcc void @"$s13generic_casts8intToAllyxSilF"(%swift.opaque* noalias nocapture sret, i64, %swift.type* %T) {{.*}} {
func intToAll<T>(_ x: Int) -> T {
// CHECK: [[INT_TEMP:%.*]] = alloca %TSi,
// CHECK: [[T0:%.*]] = getelementptr inbounds %TSi, %TSi* [[INT_TEMP]], i32 0, i32 0
// CHECK: store i64 %1, i64* [[T0]],
// CHECK: [[T0:%.*]] = bitcast %TSi* [[INT_TEMP]] to %swift.opaque*
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[T0]], %swift.type* @"$sSiN", %swift.type* %T, i64 7)
return x as! T
}
// CHECK: define hidden swiftcc i64 @"$s13generic_casts8anyToIntySiypF"(%Any* noalias nocapture dereferenceable({{.*}})) {{.*}} {
func anyToInt(_ x: Any) -> Int {
return x as! Int
}
@objc protocol ObjCProto1 {
static func forClass()
static func forInstance()
var prop: NSObject { get }
}
@objc protocol ObjCProto2 : ObjCProto1 {}
@objc class ObjCClass {}
// CHECK: define hidden swiftcc %objc_object* @"$s13generic_casts9protoCastyAA10ObjCProto1_So9NSRuncingpAA0E6CClassCF"(%T13generic_casts9ObjCClassC*) {{.*}} {
func protoCast(_ x: ObjCClass) -> ObjCProto1 & NSRuncing {
// CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_"
// CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing"
// CHECK: call %objc_object* @swift_dynamicCastObjCProtocolUnconditional(%objc_object* {{%.*}}, i64 2, i8** {{%.*}})
return x as! ObjCProto1 & NSRuncing
}
@objc class ObjCClass2 : NSObject, ObjCProto2 {
class func forClass() {}
class func forInstance() {}
var prop: NSObject { return self }
}
// <rdar://problem/15313840>
// Class existential to opaque archetype cast
// CHECK: define hidden swiftcc void @"$s13generic_casts33classExistentialToOpaqueArchetypeyxAA10ObjCProto1_plF"(%swift.opaque* noalias nocapture sret, %objc_object*, %swift.type* %T)
func classExistentialToOpaqueArchetype<T>(_ x: ObjCProto1) -> T {
var x = x
// CHECK: [[X:%.*]] = alloca %T13generic_casts10ObjCProto1P
// CHECK: [[LOCAL:%.*]] = alloca %T13generic_casts10ObjCProto1P
// CHECK: [[LOCAL_OPAQUE:%.*]] = bitcast %T13generic_casts10ObjCProto1P* [[LOCAL]] to %swift.opaque*
// CHECK: [[PROTO_TYPE:%.*]] = call {{.*}}@"$s13generic_casts10ObjCProto1_pMD"
// CHECK: call i1 @swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[LOCAL_OPAQUE]], %swift.type* [[PROTO_TYPE]], %swift.type* %T, i64 7)
return x as! T
}
protocol P {}
protocol Q {}
// CHECK: define hidden swiftcc void @"$s13generic_casts19compositionToMemberyAA1P_pAaC_AA1QpF{{.*}}"(%T13generic_casts1PP* noalias nocapture sret, %T13generic_casts1P_AA1Qp* noalias nocapture dereferenceable({{.*}})) {{.*}} {
func compositionToMember(_ a: P & Q) -> P {
return a
}
| apache-2.0 | b17119e34e7e90eb772941a130bcc2a6 | 52.785714 | 270 | 0.660027 | 3.261505 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard | GrandCentralBoard/Widgets/Bonus/BonusWidget.swift | 2 | 2761 | //
// Created by Krzysztof Werys on 24/02/16.
// Copyright © 2016 Krzysztof Werys. All rights reserved.
//
import UIKit
import GCBCore
import GCBUtilities
private let widgetTitle = "Bonusly".localized.uppercaseString
final class BonusWidget: WidgetControlling {
private let widgetView: BonusWidgetView
private let widgetViewWrapper: UIView
private lazy var errorView: UIView = {
let viewModel = WidgetErrorTemplateViewModel(title: widgetTitle,
subtitle: "Error".localized.uppercaseString)
return WidgetTemplateView.viewWithErrorViewModel(viewModel)
}()
let sources: [UpdatingSource]
let bubbleResizeDuration: NSTimeInterval
let numberOfBubbles: Int
init(sources: [UpdatingSource], bubbleResizeDuration: NSTimeInterval, numberOfBubbles: Int) {
self.widgetView = BonusWidgetView.fromNib()
self.sources = sources
self.bubbleResizeDuration = bubbleResizeDuration
self.numberOfBubbles = numberOfBubbles
let viewModel = WidgetTemplateViewModel(title: widgetTitle,
subtitle: String(format: "Last %d people".localized, numberOfBubbles).uppercaseString,
contentView: widgetView)
let layoutSettings = WidgetTemplateLayoutSettings(contentMargin: UIEdgeInsetsZero)
widgetViewWrapper = WidgetTemplateView.viewWithViewModel(viewModel, layoutSettings: layoutSettings)
}
var view: UIView {
return widgetViewWrapper
}
func update(source: UpdatingSource) {
switch source {
case let source as BonusSource:
updateBonusFromSource(source)
default:
assertionFailure("Expected `source` as instance of `BonusSource`.")
}
}
private func updateBonusFromSource(source: BonusSource) {
source.read { [weak self] result in
guard let strongSelf = self else { return }
switch result {
case .Success(let people):
strongSelf.hideErrorView()
let bonusViewModel = BonusWidgetViewModel(people: people, bubbleResizeDuration: strongSelf.bubbleResizeDuration)
strongSelf.widgetView.render(bonusViewModel)
case .Failure:
strongSelf.displayErrorView()
strongSelf.widgetView.failure()
}
}
}
private func displayErrorView() {
guard !view.subviews.contains(errorView) else { return }
view.fillViewWithView(errorView, animated: false)
}
private func hideErrorView() {
errorView.removeFromSuperview()
}
}
| gpl-3.0 | f5e981d528606ab163d0dbe3e1fec734 | 33.936709 | 134 | 0.640942 | 5.498008 | false | false | false | false |
NGeenLibraries/NGeen | Example/App/Datasource/HeroDatasource.swift | 1 | 2026 | //
// HeroDatasource.swift
// Copyright (c) 2014 NGeen
//
// 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 HeroDatasource: NSObject, UITableViewDataSource, UITableViewDelegate {
var tableData: [Hero] = Array()
//MARK: UITableView delegate
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.tableData.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cellIdentifier: String = "HeroListCell"
var cell: HeroListCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as HeroListCell
if cell == nil {
let nib: [AnyObject] = NSBundle.mainBundle().loadNibNamed(cellIdentifier, owner: self, options: nil)
cell = nib.first as HeroListCell
}
cell.configure(hero: self.tableData[indexPath.row] as Hero)
return cell
}
}
| mit | 3dcbf3fd2332d794495f962500916014 | 44.022222 | 133 | 0.731491 | 4.835322 | false | false | false | false |
pdcgomes/RendezVous | Vendor/docopt/Required.swift | 1 | 754 | //
// Required.swift
// docopt
//
// Created by Pavel S. Mazurin on 3/1/15.
// Copyright (c) 2015 kovpas. All rights reserved.
//
import Foundation
internal class Required: BranchPattern {
override var description: String {
get {
return "Required(\(children))"
}
}
override func match<T: Pattern>(left: [T], collected clld: [T]? = nil) -> MatchResult {
let collected: [Pattern] = clld ?? []
var l: [Pattern] = left
var c = collected
for pattern in children {
var m: Bool
(m, l, c) = pattern.match(l, collected: c)
if !m {
return (false, left, collected)
}
}
return (true, l, c)
}
}
| mit | 9cbbcf3ecb6bcfb2d8ef7f4c4e1c67bd | 22.5625 | 91 | 0.515915 | 3.846939 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.