2020年1月31日金曜日

ios 13, how to change the text field placeholder color from storyboard

How to change  text field placeholder color from storyboard .


  1.  select the UITextfiled of which you want to change the color. if there are several text fields, you have to do the same procedure for each.
  2. open the identity inspector. see the pic.
  3. Find the User Defined Runtime Attributes  and click + button.
  4. Type a new row with Key Path  placeholderLabel.textColor. be reminded that this is for iOS13, Swift 5.0. if it is for lower version, type _placeholderLabel.textColor instead.
  5. choose Type color and select the color as your choice.

2020年1月28日火曜日

Swift on iOS13, UIView present

The change on iOS13,  UIView.present default style is card presentation

card presentation


to make it full screen is easy.

solution
to set .fullscreen or .overFullScreen to

modalPresentationStyle

for example

        let viewCon = SampleViewController2(nibName: "SampleViewController", bundle: .main)
        viewCon.modalPresentationStyle = .fullScreen
        self.present(viewCon, animated: true, completion: nil)



.fullScreen

Discussion

The views belonging to the presenting view controller are removed after the presentation completes.

.overFullScreen

Discussion

The views beneath the presented content are not removed from the view hierarchy when the presentation finishes. So if the presented view controller does not fill the screen with opaque content, the underlying content shows through.


2020年1月25日土曜日

swift, function type. prepare for functional programming with Swift - 1

Function Type
swift can show the type of the return value of a function.
This could be useful when implementing type matching by swift, so it is necessary to see the details of this.

see the official document 

Here is the very intro part of the explaining.

The function in the example below is called greet(person:), because that’s what it does—it takes a person’s name as input and returns a greeting for that person. To accomplish this, you define one input parameter—a String value called person—and a return type of String, which will contain a greeting for that person:
  1. func greet(person: String) -> String {
  2. let greeting = "Hello, " + person + "!"
  3. return greeting
  4. }

typealias
This will create obviously the alias of  a type.


  1. typealias (String) -> String = greetType
  2. func callGreet(callback: greetType) {
  3. let greeting = callback("Hello")
  4. // this is supposed to be greet(person: String) function
  5. return greeting
  6. }

Filter


Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.

let numbers = [1,2,3,4,5]
let greaterThan2 = numbers.filter { $0 > 2}
print(greaterThan2)
[3, 4, 5]

Map

Returns an array containing the results of mapping the given closure over the sequence’s elements.


let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercased() }
print(lowercaseNames)
["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.count }
print(letterCounts)
[6, 6, 3, 4]

Reduce

Returns the result of combining the elements of the sequence using the given closure.

Declaration


func reduce(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result


let numbers = [1,2,3,4,5]
let numberSum = numbers.reduce(0, { x, y in
    x + y
})
print(numberSum)
15


2020年1月23日木曜日

javascript primitive string

Let's see below example

let s1 = '2 + 2'              // creates a string primitive
let s2 = new String('2 + 2')  // creates a String object
console.log(eval(s1))         // returns the number 4
console.log(eval(s2))         // returns the string "2 + 2"

String primitives and String objects

String primitives and String objects also give different results when using eval(). Primitives passed to eval are treated as source code; String objects are treated as all other objects are

ref

The new Windows Terminal

The terminal software installed as the default with WSL linux distribution is not really comfortable. (for example Ubuntu)

However finally I have the better terminal for WSL.
It is Windows terminal, as the name implying this is developed by Microsoft and is open sourced.

https://github.com/microsoft/terminal

It can be installed from Micosoft store but it is still preview.
I think i want to try to build from the source though,
the preview version is already comfortable and i feel really happy with it.


2020年1月22日水曜日

Javascript function, passing variable or value

let's see the below function

function update(o) {
  o.a = o.a + 1;
  o = { a: 100 };
}

and do the following test ,

>const obj = {a:1} 
>update(obj)

console.log(obj)

what is the result ?

it would be 2.

> console.log(obj.a)

1


note that
even if the object is const value, the object keys are not protected.

in the function update(o), first line of o.a is still seeing the value of the obj, which is out of the scope of the function,
then second line, o = {a:100} , which is replacing o in the scope of function to a new object, however obj  in the outside of the function is not changed.

Javascript NaN, comparing or not

NaN is not a number and would appear when you calculate number.

>const result = "foo" * 2;

it will give you NaN as result.

however this

>console.log(result === NaN);

it will print false

because

NaN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN. Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself.


>Number.isNaN(result)
>isNaN(result)

will return true


Xcode. device is not connected.

When Xcode said  your device was not connected but actually it was connected.
it would be solved reboot however avoiding reboot, type the below command.


sudo launchctl stop com.apple.usbmuxd
stackexchange

What is launchd

according to wikipedia,
launchd is an init and operating system service management daemon created by Apple Inc. as part of macOS to replace its BSD-style init and SystemStarter. There have been efforts to port launchd to FreeBSD and derived systems.

it could solve other problems too..

2020年1月18日土曜日

Javascript Boolean()

Boolean()
Creates Boolean objects.
The Boolean object is an object wrapper for a boolean value. (ref)


what do you think the output of the following code ?
const bool = "false";
console.log(Boolean(bool)); 

it will print true.

because Boolean() evaluate values which are nil, or undefined to false but other value for example String to true.

const bool = "false";
console.log(bool == false); // false

console.log(Boolean(bool)); // true

also an empty array [] would be evaluated to true

const bool = [];
console.log(Boolean(bool)); // true


Don't confuse Boolean() and boolean primitive like true or false

XQaurtz 日本語表示

macOSXのXQaurtz 日本語表示

.bash_profile
export LANG='ja_JP.UTF-8'
export LC_ALL='ja_JP.UTF-8'
export LC_MESSAGES='ja_JP.UTF-8'
test -r ~/.bashrc && . ~/.bashrc
を追加
アプリケーション->カスタマイズ
ターミナルの起動を xterm -u8に設定

Custom reduce function to Javascript Allay class

learn how to use Javascript prototype.
let's make a reduce() function of  Allay class using  javascript prototype.


Array.prototype.myReduce = function(callback, initVal) { 
 let acc = initVal; 
  for (i = 0; i < this.length; i++) { 
   acc = callback(acc, this[i]); 
  }; 
 return acc
}


let myArray = [1,2,3]
myArray.myReduce((acc, elem) => { return acc + elem; }, 0)
6


What is reduce() function 

from mozira document of reduce

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));

// expected output: 15



2020年1月16日木曜日

ios customise tabbar with UITabBarController

Here is a sample of creating your own UITabBarController and  customise tab bar behaviour on ios. not only customising tint colour of icon or icon itself but also adding more functionality when switching tab, it required to make your own class inheriting UITabBarController but you want to use the views and tab bar controller scene from story board.
  1. start from tab application default
  2. remove segure from story board connected to views from tab bar scene
  3. set story boad ID to each scene which would be navigated by the tab bar. (FirstView, SecondView for example)
  4. create a new class MyTabBarController
    ```
    class MyTabBarController: UITabBarController, UITabBarControllerDelegate {
    var firstViewController: FirstViewController!
    var secondViewController: SecondViewController!
    override func viewDidLoad() {
    super.viewDidLoad()
    self.delegate = self
    firstViewController = storyboard?.instantiateViewController(withIdentifier: "FirstView") as? FirstViewController
    secondViewController = storyboard?.instantiateViewController(withIdentifier: "SecondView") as? SecondViewController
    firstViewController.tabBarItem.image = UIImage(named: "customFirstImage")
    secondViewController.tabBarItem.image = UIImage(named: "customFirstImage")
    viewControllers = [firstViewController, secondViewController]
    selectedIndex = 0
    }
    /*
    // MARK: - Navigation
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destination.
    // Pass the selected object to the new view controller.
    }
    */
    }
    ```
  5. set MyTabBarController as the class of tab bar controller in the story board

state property swift memo

what is @state property

Overview

SwiftUI manages the storage of any property you declare as a state. When the state value changes, the view invalidates its appearance and recomputes the body. Use the state as the single source of truth for a given view.
State instance isn’t the value itself; it’s a means of reading and mutating the value. To access a state’s underlying value, use its value property.
Only access a state property from inside the view’s body (or from functions called by it). For this reason, you should declare your state properties as private, to prevent clients of your view from accessing it.
You can get a binding from a state with the `binding` property, or by using the `$` prefix operator.

@Environment

Environment

A dynamic view property that reads a value from the view’s environment.

EnvironmentObject

A dynamic view property that uses a bindable object supplied by an ancestor view to invalidate the current view whenever the bindable object changes.

2020年1月10日金曜日

Swift Dictionary Grouping


     There is the comment in the Dictionary souce code.

    /// Creates a new dictionary whose keys are the groupings returned by the

    /// given closure and whose values are arrays of the elements that returned
    /// each key.
    ///
    /// The arrays in the "values" position of the new dictionary each contain at
    /// least one element, with the elements in the same order as the source
    /// sequence.
    ///
    /// The following example declares an array of names, and then creates a
    /// dictionary from that array by grouping the names by first letter:


let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })

EnvironmentObject Swift

EnvironmentObject in Swiftaccording to apple's Document A dynamic view property that uses a bindable object supplied by an ancestor view to invalidate the current view whenever the bindable object changes.

Declaration

@frozen @propertyWrapper struct EnvironmentObject<ObjectTypewhere ObjectType : ObservableObject

what does that mean ?


my understanding is that variable wrapped @EnvironmentObject can be shared 
across all views and update view when the variable is updated.
This is like the way React/Redux store doing.
final class UserData: ObservableObject  {
    @Published var showFavoritesOnly = false
    @Published var landmarks = landmarkData
}
struct LandmarkList: View {

    @EnvironmentObject var userData: UserData

    var body: some View {
        NavigationView{
            List {
                Toggle(isOn: $userData.showFavoritesOnly  , label: {Text("Favorites only")})
                ForEach(userData.landmarks) { landdata in
                    if (!self.userData.showFavoritesOnly || landdata.isFavorite) {
                        NavigationLink(destination: ContentView(landmark:   landdata)) {
                            LandmarkRow(landmark: landdata)
                            }.navigationBarTitle(Text("Landmark"))
                        }
                    }
                }
        }
    }
}


2020年1月7日火曜日

Book for functional Analysis

I fond this book
It is a math book , not for functional programming.
Introductory Functional Analysis With Applications